Last active
June 27, 2022 08:08
-
-
Save fronterior/a09e2c7410eec1e15a7d109bbcda1923 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class ArrayMap extends Map { | |
constructor(...params) { | |
super(); | |
params.forEach(([key, value]) => this.set(key, value)); | |
} | |
set(key, value) { | |
const len = key.length; | |
const cp = [...key]; | |
let chn = super.has(len) ? super.get(len) : (super.set(len, new Map),super.get(len)); | |
let prop = cp.shift(); | |
do { | |
chn = | |
!cp.length ? chn.set(prop, value).get(prop) : | |
chn.has(prop) ? chn.get(prop) : chn.set(prop, cp.length ? new Map : value).get(prop); | |
} while (prop = cp.shift()); | |
return this; | |
} | |
get(key) { | |
const len = key.length; | |
const cp = [...key]; | |
let chn = super.has(len) ? super.get(len) : null; | |
if (!chn) return; | |
let prop = cp.shift(); | |
do { | |
chn = chn.has(prop) ? chn.get(prop) : undefined; | |
} while (prop = cp.shift()); | |
return chn; | |
} | |
has(key) { | |
const len = key.length; | |
const cp = [...key]; | |
let chn = super.has(len) ? super.get(len) : null; | |
if (!chn) return false; | |
let prop = cp.shift(); | |
let result = true; | |
do { | |
chn = chn.has(prop) ? chn.get(prop) : result = false; | |
} while ((prop = cp.shift()) && result); | |
return result; | |
} | |
} | |
am = new ArrayMap(); | |
am.set([1,2], 5); | |
am.set([1,3,5], 7); | |
am.has([1,2,3]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment