Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

walkUp function #20

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/index-fn.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export {default as closest} from "./closest.js";
export {default as find} from "./find.js";
export {default as map} from "./map.js";
export {default as walk} from "./walk.js";
export {default as walkUp} from "./walkUp.js";
22 changes: 22 additions & 0 deletions src/walkUp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import * as parents from "./parents.js";

/**
* Walk up the tree from the given node, calling the callback on each node.
* @param {object} node
* @param {function} callback
* @returns {any} The first non-undefined value returned by the callback, or the highest ancestor node if no undefined value is ever returned.
*/
export default function walkUp (node, callback) {
let previousNode;
while (node) {
const ret = callback(node);
if (ret !== undefined) {
return ret;
}
previousNode = node;
const parent = parents.getParent.call(this, node);
adamjanicki2 marked this conversation as resolved.
Show resolved Hide resolved
// TODO: what should happen if parent is undefined (meaning no parent pointers have been set?)
adamjanicki2 marked this conversation as resolved.
Show resolved Hide resolved
node = parent;
}
return previousNode;
adamjanicki2 marked this conversation as resolved.
Show resolved Hide resolved
}
26 changes: 26 additions & 0 deletions test/walkUp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import walkUp from "../src/walkUp.js";
import trees from "./utils/trees.js";
import updateParents from "../src/updateParents.js";
import copy from "./utils/copy.js"

const tree = copy(trees[0]);
updateParents(tree);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to have some throws tests too, for when we don't have parents. Or should that just be handled in the parents tests?


export default {
name: "walkUp()",
run (node, cb) {
return walkUp(node, cb);
},
tests: [
{
name: "No callback",
args: [tree.right, () => {}],
expect: tree
},
{
name: "Callback returns a value",
args: [tree.right, n => n.name === "1" ? n : undefined],
expect: tree
}
]
};