Last active
November 26, 2015 13:21
-
-
Save codeofnode/537beb3f325ba8faee7b to your computer and use it in GitHub Desktop.
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
function isRightPattern (actual, expected){ | |
if(expected instanceof RegExp){ | |
return expected.test(actual); | |
} else { | |
return actual === expected; | |
} | |
} | |
function extractPatterns(obj,expected) { | |
if(!obj || typeof obj !== 'object') return {}; | |
var ar = {}; var path = ''; | |
function inc(k,root) { | |
if(Array.isArray(root)) path += ('[' + k + ']'); | |
else if(path) path += ('.' + k); | |
else path = k; | |
} | |
function dec(root) { | |
if(path) { | |
path = path.substring(0, path.lastIndexOf(Array.isArray(root) ? '[' : '.')); | |
} | |
} | |
function scan(obj) { | |
var k,v; | |
if (obj instanceof Object) { | |
for (k in obj){ | |
if (obj.hasOwnProperty(k)){ | |
v = obj[k]; | |
if(typeof(v) === 'string') { | |
if(isRightPattern(v,expected)) { | |
inc(k,obj); | |
ar[path] = v; | |
dec(); | |
} | |
} else if(v && typeof(v) === 'object') { | |
inc(k,obj); | |
scan(obj[k]); | |
dec(obj); | |
} | |
} | |
} | |
} | |
} | |
scan(obj); | |
return ar; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment