Created
January 2, 2019 15:56
-
-
Save mr21/4f58e5ab1ba3c16c456268f4d0c95e9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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