localStorage Preferences with Recent Lists in Javascript
A preferences system in Javascript using localStorage and providing a Recents mechanism.
You can use the available commands to retrieve/write data from/to preferences and to add items to Recents Lists.
You can retrieve/write data of any type (boolean, numeric, string, array, object).
When adding an item to a Recents List, the older item in List is removed if the limit has been exceeded. The limit defaults to 10.
The prop property is used to check if the item is already in the list. It defaults to “id”.
I am using it on my React project but can be used on any Javascript project.
Usage
// Get a value from preferences
// PREFS.get( name )
PREFS.get("language")
// Write a value to preferences
// PREFS.set( name, value )
PREFS.set("language", "el")
// Add item to Recents List
// PREFS.addRecent( name, item, [prop], [limit] )
PREFS.addRecent('post', postObject, 'id', 10)
API
get( name:str )
PREFS.get("language")
name | name of the value you want to retrieve |
set( name:str, value:any )
PREFS.set("language", "el")
name | name of the value you want to write |
value | the actual value (can be of any type) |
addRecent( name:str, item:any, [prop:str], [limit:num] )
PREFS.addRecent('post', postObject, 'id', 10)
name | name of the items group |
item | the item you want to add |
prop | the item property that used for comparison identifier |
limit | the limit of the length of Recents List |
Code
const PREFS = {
recentsLimit : 10,
uid : 1,
// user id to have different preferences
// for different users
// Get value from localStorage
get: ( name ) =>{
let prefs = PREFS.getPrefs();
return prefs[ name ];
},
// Write value to localStorage
set: ( name, value ) =>{
let prefs = PREFS.getPrefs();
prefs[ name ] = value
// write to localStorage
prefs = JSON.stringify( prefs )
localStorage
.setItem(`prefs-${PREFS.uid}`, prefs)
},
// Add item to Recents List
addRecent: ( name, item, prop, limit ) => {
prop = prop || 'id'
limit = limit || recentsLimit
let prefs = PREFS.getPrefs();
// remove item from recents if already there
let idx = prefs.recent[ name ]
.findIndex(x=> x[prop] == item[prop] )
if ( idx >= 0 )
prefs.recent[ name ].splice(idx, 1)
// add new item to recents
prefs.recent[ name ].push( item )
// if limit exceeded remove older item
if ( prefs.recent[ name ].length > limit ) {
prefs.recent[ name ].shift()
}
// write to localStorage
prefs = JSON.stringify( prefs )
localStorage.setItem(`prefs-${PREFS.uid}`, prefs)
},
// get Preferences JSON
getPrefs: () => {
// Get from localStorage
let prefs =
localStorage.getItem(`prefs-${PREFS.uid}`)
// Get defaults if localStorage is empty
if ( ! prefs )
prefs = JSON.stringify( PREFS.defaults );
// convert string to JSON
prefs = JSON.parse( prefs )
return prefs;
},
// defaults
defaults : {
language : "en",
color: "#00F",
recent : {
project: [],
post: [],
}
},
}