Last active
March 3, 2021 03:40
-
-
Save elycruz/fd3a6d35ac751480b212c582db592235 to your computer and use it in GitHub Desktop.
Simple tree-map algo (in *.js).
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
class TN { | |
constructor(assocList) { | |
if (assocList) { | |
assocList.forEach(([k, v]) => { | |
this.set(k, v); | |
}); | |
} | |
} | |
set(k, v)) { | |
addToTree(k, v, this); | |
} | |
} | |
var addToTree = (k, v, t = {}) => { | |
if (!k) { | |
return t; | |
} | |
const c = k[0], | |
tail = k.slice(1); | |
if (!tail) { | |
if (!t.nodes) t.nodes = {}; | |
const n = t.nodes[c] || {}; | |
n.value = v; | |
t.nodes[c] = n; | |
return t; | |
} | |
if (!t.nodes) { | |
t.nodes = {[c]: addToTree(tail, v)}; | |
} else if (!t.nodes[c]) { | |
t.nodes[c] = addToTree(tail, v); | |
} else { | |
addToTree(tail, v, t.nodes[c]); | |
} | |
return t; | |
}, | |
findInTree = (k, t) => { | |
if (!k || !t) { | |
return; | |
} | |
const c = k[0], | |
tail = k.slice(1); | |
if (tail && !t.nodes) { | |
return; | |
} | |
if (!tail || !t.nodes) { | |
return t?.nodes[c]?.value; | |
} | |
return findInTree(tail, t.nodes[c]); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment