Last active
November 8, 2022 05:28
-
-
Save Pengeszikra/be44f18701eb75f495d2 to your computer and use it in GitHub Desktop.
ES6 object tree walk generator
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
/* # use >> for( node of Object.walk( yourObject )) console.log( node ) | |
# or more >> | |
let walk=[]; for( node of Object.walk( yourObject , o => isHaveRoutes( o ) ) ) if(isProperWay(node)) walk.push( node ) | |
# recursive generator for Object, avoide circular structure by set. | |
*/ | |
Object.walk = function* ( po , fil , set ) { | |
fil = fil || (()=>true) | |
set = set || new Set() | |
if ( po instanceof Object && !set.has(po) && fil(po) ){ | |
set.add( po ) | |
yield po | |
for(let key of Object.keys( po , set )){ yield* Object.walk( po[key] , fil , set ) } | |
} | |
} | |
// filterless version | |
export function * walker(object, set = new Set()) { | |
if (object instanceof Object && !set.has(object)) { | |
set.add( object ); | |
yield object; | |
for ( let key of Object.keys(object , set)) { | |
yield * walker(object[key], set ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment