Created
August 22, 2016 23:12
-
-
Save jmakeig/0c5798ace0bf253a91189a6918f407ba to your computer and use it in GitHub Desktop.
Recursive descent visitor pattern in JavaScript
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 strict' | |
const json = { | |
"a": ["A", "A", {"b": "B"} ], | |
"c": { "d": "D", "e": ["E", "E"]}, | |
"f": "F" | |
} | |
function isPrimitive(obj) { | |
if(null === obj) return true; | |
if(undefined === obj) return true; | |
if(['string', 'number', 'boolean'].some(type => type === typeof true)) return true; | |
return false; | |
} | |
function visit(obj, visitor) { | |
for(let key of Object.keys(obj)) { | |
if(isPrimitive(obj[key])) { | |
visitor(key, obj[key]); | |
} else if(Array.isArray(obj[key])) { | |
for(let item of obj[key]) { | |
visit(item, visitor); | |
} | |
} else { | |
visit(obj[key], visitor); | |
} | |
} | |
} | |
const out = []; | |
visit(json, (k, v) => out.push(v)); | |
out; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As function or inline (7x slower, so performance VS readability choice):