Skip to content

Instantly share code, notes, and snippets.

@frentsel
Last active November 23, 2018 12:08
Show Gist options
  • Save frentsel/4999e9316efe50ab4fc1762b37cdeed3 to your computer and use it in GitHub Desktop.
Save frentsel/4999e9316efe50ab4fc1762b37cdeed3 to your computer and use it in GitHub Desktop.
Binary Tree example (Javascript)
var a = [...Array(5000000).keys()];
var chunk = (data, center) => {
const chunks = [];
while (data.length)
chunks.push(data.splice(0, center));
return chunks;
}
var treeBuild = (array, tree = []) => {
if (!array.length) return tree;
var center = Math.round(array.length / 2);
var [left, right] = chunk([...array], center);
return [...tree, {
value: left.pop(),
left: (left && left.length) ? treeBuild(left) : null,
right: (right && right.length) ? treeBuild(right) : null
}];
};
var treeIterations = 0;
var searchByTree = ([el], find) => {
treeIterations++;
if (find > el.value) {
return searchByTree(el.right, find);
} else if (find < el.value) {
return searchByTree(el.left, find);
}
return el;
}
console.time('treeBuild');
var res = treeBuild(a);
console.timeEnd('treeBuild');
//console.log(JSON.stringify(res, null, 1));
console.time('native');
a.find(el => el === 3950045);
console.timeEnd('native');
console.time('tree');
searchByTree(res, 3950045);
console.log('treeIterations: ', treeIterations);
console.timeEnd('tree');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment