Last active
June 2, 2017 03:34
-
-
Save nrkn/6d71a5f00ebec186b829a027bd6df3e1 to your computer and use it in GitHub Desktop.
Iterator for depth first search of a tree node
This file contains hidden or 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
const dfsIterator = node => { | |
const nodes = [ node ] | |
const next = () => { | |
const done = nodes.length === 0 | |
if( done ) return { done } | |
const value = nodes.pop() | |
let child = value.lastChild | |
while( child ){ | |
nodes.push( child ) | |
child = child.previousSibling | |
} | |
return { done, value } | |
} | |
return { | |
[Symbol.iterator]: () => ({ next }) | |
} | |
} |
Author
nrkn
commented
Jun 2, 2017
const find = ( node, predicate ) => {
for( current of dfsIterator( node ) )
if( predicate( current ) ) return current
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment