Skip to content

Instantly share code, notes, and snippets.

@thelevicole
Last active September 14, 2023 21:29
Show Gist options
  • Save thelevicole/7b9f25e277cdc9ee0b0dfd8a4f59c1a0 to your computer and use it in GitHub Desktop.
Save thelevicole/7b9f25e277cdc9ee0b0dfd8a4f59c1a0 to your computer and use it in GitHub Desktop.
Javascript RAM storage

Random-access memory (RAM) storage for JavaScript

Works similarly to localStorage and sessionStorage but stored in the RAM. However, unlike local and session storage we don't need to serialise objects and arrays before storing.

Store data

var id = Math.random().toString( 36 ).substr( 2, 13 );
ramStorage.setItem( 'randId', id );

Get data

var id = ramStorage.getItem( 'randId' );
// Or...
var id = ramStorage.randId;

Delete data

ramStorage.removeItem( 'randId' );
class RamStorage {
/**
* Class constructor, setup empty storage and field proxy
*/
constructor() {
this.storage = {};
return new Proxy( this, {
get: function( instance, attribute ) {
if ( attribute in instance ) {
return instance[ attribute ];
} else if ( attribute in instance.storage ) {
return instance.storage[ attribute ];
}
}
} );
}
/**
* Store an item with name
*
* @param {String} name
* @param {Mixed} value
* @return {Void}
*/
setItem( name, value ) {
this.storage[ name ] = value;
}
/**
* Get an item by name
*
* @param {String} name
* @return {Mixed}
*/
getItem( name ) {
return this.storage[ name ];
}
/**
* Delete an item by name
*
* @param {String} name
* @return {Void}
*/
removeItem( name ) {
delete this.storage[ name ];
}
}
window.ramStorage = new RamStorage();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment