Skip to content

Instantly share code, notes, and snippets.

@elycruz
Last active March 3, 2021 03:40
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 elycruz/fd3a6d35ac751480b212c582db592235 to your computer and use it in GitHub Desktop.
Save elycruz/fd3a6d35ac751480b212c582db592235 to your computer and use it in GitHub Desktop.
Simple tree-map algo (in *.js).
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