Skip to content

Instantly share code, notes, and snippets.

@pmsorhaindo
Last active November 30, 2016 14:36
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 pmsorhaindo/fae4dd5896ba677255691482e6a3fbb4 to your computer and use it in GitHub Desktop.
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.
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