Skip to content

Instantly share code, notes, and snippets.

@codeofnode
Last active November 26, 2015 13:21
Show Gist options
  • Save codeofnode/537beb3f325ba8faee7b to your computer and use it in GitHub Desktop.
Save codeofnode/537beb3f325ba8faee7b to your computer and use it in GitHub Desktop.
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