Skip to content

Instantly share code, notes, and snippets.

@nrkn
Last active June 2, 2017 03:34
Show Gist options
  • Save nrkn/6d71a5f00ebec186b829a027bd6df3e1 to your computer and use it in GitHub Desktop.
Save nrkn/6d71a5f00ebec186b829a027bd6df3e1 to your computer and use it in GitHub Desktop.
Iterator for depth first search of a tree node
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 })
}
}
@nrkn
Copy link
Author

nrkn commented Jun 2, 2017

for( current of dfsIterator( node ) )
  console.log( current )

const arr = Array.from( dfsIterator( node ) )

@nrkn
Copy link
Author

nrkn commented Jun 2, 2017

const find = ( node, predicate ) => {
  for( current of dfsIterator( node ) )
    if( predicate( current ) ) return current
}

@nrkn
Copy link
Author

nrkn commented Jun 2, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment