Skip to content

Commit

Permalink
Solve garageScript#49, Lesson 2: bfsArr - Takes in a tree & returns a…
Browse files Browse the repository at this point in the history
…n array of each level
  • Loading branch information
Alberto Lopez committed Oct 27, 2017
1 parent 3f210bb commit a4fb4ee
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 17 deletions.
1 change: 1 addition & 0 deletions solutions/bfsArr.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const bfs = (current, next=[], result=[current.slice()])=>{

if(current.length === 0 && next.length === 0){
return result;
}
Expand Down
60 changes: 43 additions & 17 deletions test/bfsArr.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,53 @@
const solution = require('../solutions/bfsArr.js');

const tree = {
val: 1,
children: [{val:2,children:[]},{val:3,children:[]}]
}
let a = {v:1};
let b = {v:2};
let c = {v:3};
let d = {v:4};
a['children']=[b,c];
b['children']=[];
c['children']=[d];
d['children']=[];

const tree2 = {
val: 1,
children: [{val:2,children:[{val:4,children:[]},{val:5,children:[]}]},{val:3,children:[{val:6,children:[]},{val:7,children:[]}]}]
}
let e = {val:1};
let f = {val:2};
let g = {val:3};
let h = {val:4};
e['children']=[f,g];
g['children']=[];
f['children']=[h];
h['children']=[];

const tree3 = {
val: 1,
children: [{val:2,children:[{val:4,children:[]},{val:5,children:[]}]},{val:3,children:[{val:6,children:[]},{val:7,children:[{val:9,children:[]}]}]}]
let i = {val:1};
let j = {val:2};
let k = {val:3};
let l = {val:4};
i['children']=[j,k];
j['children']=[];
k['children']=[l];
l['children']=[];

const helperFunct = (c, r, i=0, j=0)=>{
if(c.length === i){
return true;
}
if(j < c[i].length){
if(c[i][j] === r[i][j]){
return helperFunct(c, r, i, j+1);
}else{
return false;
}
}
return helperFunct(c, r, i+1,j=0);
}

const test = (current, result)=>{
if(solution(current).length === result){
console.log('correct levels ');
if(helperFunct(current,result)){
console.log('objects are equal ');
}else{
console.log('incorrect levels ');
console.log('objects are not equal ');
}
}
test([tree], 1);
test([tree2], 3);
test([tree3], 4);
test(solution([a]), [[a],[b,c],[d]]);
test(solution([e]), [[e],[f,g],[h]]);
test(solution([i]), [[i],[{val:10,children:[]},k],[0]]);

0 comments on commit a4fb4ee

Please sign in to comment.