Last active
November 30, 2016 14:36
-
-
Save pmsorhaindo/fae4dd5896ba677255691482e6a3fbb4 to your computer and use it in GitHub Desktop.
returns a path to the first leaf node in an query tree which passes a given predicate.
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
console.clear(); | |
function findPath(node, predicate) { | |
var depth = 0; | |
var path = []; | |
var found = false; | |
function find(currentNode, i) { | |
if (found) { | |
return path; | |
} | |
path[depth] = i; | |
// console.log('path: ' + path); | |
if(isBranch(currentNode)) { | |
// console.log('i: ' + i + ' depth '+ depth + '. id: ' + currentNode.id); | |
depth++; | |
currentNode.children.forEach(find); | |
depth--; | |
} | |
else { | |
// console.log('i: ' + i + ' depth: ' + depth + ' id: ' + currentNode.id + '. value: ' + currentNode.value); | |
if (predicate(currentNode.value)) { | |
found = true; | |
return; | |
} | |
} | |
return found ? path : undefined; | |
} | |
return find(node, 0); | |
} | |
// utils | |
function predicate(value) { | |
console.log(value[0] === 'this'); | |
return value[0] === 'or'; | |
} | |
function isBranch(node, operator) { | |
return Array.isArray(node.children) && | |
!node.hasOwnProperty('value') && | |
!node.hasOwnProperty('field') && | |
(!operator || operator === node.operator); | |
} | |
//data | |
const query = { | |
id: '1', | |
operator: 'AND', | |
children: [{ | |
id: '2', | |
operator: 'AND', | |
children: [ | |
{ | |
id: '3', | |
opertator: 'OR', | |
children: [ | |
{ | |
id: '4', | |
field: 'BIO', | |
operator: 'OR', | |
value: ['omg', 'kanye'], | |
}, | |
{ | |
id: '5', | |
field: 'BIO', | |
operator: 'OR', | |
value: ['no', 'way'], | |
} | |
] | |
}, | |
], | |
}, { | |
id: '6', | |
operator: 'NOT', | |
children: [ | |
{ | |
id: '7', | |
field: 'BIO', | |
operator: 'OR', | |
value: ['this', 'that'], | |
}, | |
{ | |
id: '8', | |
field: 'BIO', | |
operator: 'OR', | |
value: ['or', 'the', 'other'], | |
}, | |
], | |
}], | |
}; | |
// execution | |
console.log('return this: ' + findPath(query, predicate)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment