Skip to content

Instantly share code, notes, and snippets.

@smagch
Created October 1, 2016 09:45
Show Gist options
  • Save smagch/b010b79f17ba283464605343131a7b04 to your computer and use it in GitHub Desktop.
Save smagch/b010b79f17ba283464605343131a7b04 to your computer and use it in GitHub Desktop.
Test Getting Tree Data in flattened Array
class Tree {
constructor(name) {
this.name = name;
this.children = [];
}
append(item) {
this.children.push(item);
}
getDescendantNames() {
return this.children.reduce((names, item) => {
return names.concat(item.getDescendantNames());
}, [this.name]);
}
}
`
Root
Foo
Bar
Bar2
Foo2
Bar3
Baz
Foo3
`
let root = new Tree('Root');
let foo = new Tree('Foo');
foo.append(new Tree('Bar'));
foo.append(new Tree('Bar2'));
root.append(foo);
let foo2 = new Tree('Foo2');
let bar3 = new Tree('Bar3');
let baz = new Tree('Baz');
bar3.append(baz);
foo2.append(bar3);
root.append(foo2);
let foo3 = new Tree('Foo3');
root.append(foo3);
let names = root.getDescendantNames();
console.log(names);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment