Created
July 31, 2015 02:36
-
-
Save mnichols/604d3feeef506e17481f to your computer and use it in GitHub Desktop.
flatten-rashid :)
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
var test = require('tape') | |
//utils | |
function isObject(target) { | |
return toString.call(target) == '[object Object]' | |
} | |
function id(nodes,keys) { | |
return nodes.concat(keys).join('.') | |
} | |
//push model | |
function es5(input) { | |
var result = {} | |
Object.keys(input) | |
.forEach(function(k){ | |
_visit(input,k,[],[],result) | |
}) | |
return result | |
} | |
function _visit(obj,key, keys,nodes,result) { | |
var val = obj[key] | |
keys.push(key) | |
if(!isObject(val)) { | |
var answer = { | |
it: val | |
, nodes: nodes.slice(0,nodes.length -1) | |
, keys: keys.splice(0,keys.length) | |
} | |
result[id(answer.nodes,answer.keys)]= val | |
return result | |
} else { | |
nodes.push(key) | |
Object.keys(val) | |
.forEach(function(k){ | |
_visit(val,k,keys,nodes,result) | |
}) | |
} | |
} | |
//pull model | |
function es6(input) { | |
var result = {} | |
for(var k of Object.keys(input)) { | |
for(let val of visit(input,k,[],[])) { | |
result[id(val.nodes,val.keys)] = val.it | |
} | |
} | |
return result | |
} | |
function* visit(obj, key, keys, nodes) { | |
var val = obj[key] | |
keys.push(key) | |
if(!isObject(val)) { | |
yield { it: val | |
, keys: keys.splice(0,keys.length) | |
, nodes: nodes.slice(0,nodes.length -1) | |
} | |
} else { | |
nodes.push(key) | |
var valk= Object.keys(val) | |
for(var k of valk) { | |
yield* visit(val,k,keys, nodes) | |
} | |
} | |
} | |
test('rashid',function(t){ | |
t.plan(1) | |
var input = { | |
a : 1, | |
b: { | |
c: true, | |
d: { | |
e: 'something' | |
} | |
}, | |
f: false | |
}; | |
var output = { | |
a: 1, | |
'b.c': true, | |
'b.d.e': 'something', | |
f: false | |
}; | |
var obj = es5(input) | |
t.deepEqual(obj, output) | |
}) | |
test('deeprashid',function(t){ | |
t.plan(1) | |
var input = { | |
a : 1, | |
b: { | |
c: true, | |
d: { | |
e: 'something' | |
, h: { | |
j: 'foo' | |
} | |
} | |
}, | |
f: false | |
}; | |
var output = { | |
a: 1, | |
'b.c': true, | |
'b.d.e': 'something', | |
'b.d.h.j': 'foo', | |
f: false | |
}; | |
var obj = es5(input) | |
t.deepEqual(obj, output) | |
}) | |
test('rashid-generators',function(t) { | |
t.plan(1) | |
var input = { | |
a : 1, | |
b: { | |
c: true, | |
d: { | |
e: 'something', | |
h: { | |
j: 'foo' | |
} | |
} | |
}, | |
f: false | |
}; | |
var output = { | |
a: 1 | |
, 'b.c': true | |
, 'b.d.e': 'something' | |
, 'b.d.h.j': 'foo' | |
, f: false | |
} | |
var result = es6(input) | |
t.deepEqual(result,output) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment