Skip to content

Instantly share code, notes, and snippets.

@mr21
Created January 2, 2019 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mr21/4f58e5ab1ba3c16c456268f4d0c95e9a to your computer and use it in GitHub Desktop.
Save mr21/4f58e5ab1ba3c16c456268f4d0c95e9a to your computer and use it in GitHub Desktop.
"use strict";
class ElementMap {
constructor( data ) {
this._map = new Map();
this._keyToElement = new Map();
this.size = data ? data.length : 0;
if ( data ) {
data.forEach( d => this._map.set( d[ 0 ], d[ 1 ] ) );
}
}
getElement( key ) {
return this._keyToElement.get( key );
}
/* Callbacks */
/* ........................................................................ */
connect( obj ) {
this._root = obj.root;
this._item = obj.item;
this._onset = obj.onset || this._defOnset;
this._ondel = obj.ondelete || this._defOndel;
this._map.forEach( ( val, key ) => this._set( key, val ) );
}
_defOnset( elem, val, key ) {
return val;
}
_defOndel( elem ) {
elem.remove();
}
/* Map overwrite */
/* ........................................................................ */
forEach( fn ) {
this._map.forEach( ( val, key ) => {
fn( this._keyToElement.get( key ), val, key );
} );
}
has( key ) {
return this._map.has( key );
}
get( key ) {
return this._map.get( key );
}
set( key, val ) {
const has = this._map.has( key );
if ( !has ) {
++this.size;
}
this._map.set( key, has
? this._onset( this._keyToElement.get( key ), val, key )
: this._set( key, val ) );
}
_set( key, val ) {
const elem = this._item.cloneNode( true ),
_ = this._keyToElement.set( key, elem ),
val2 = this._onset( elem, val, key );
this._root.append( elem );
return val2;
}
delete( key ) {
const elem = this._keyToElement.get( key );
if ( elem ) {
--this.size;
this._map.delete( key );
this._keyToElement.delete( key );
this._ondel( elem, key );
}
}
clear() {
this._map.forEach( ( val, key ) => {
--this.size;
this._ondel( this._keyToElement.get( key ), key );
} );
this._keyToElement.clear();
this._map.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment