Last active
January 28, 2019 17:04
-
-
Save tincho/982fb012eaa3fcbf4811d7b0132a42ca to your computer and use it in GitHub Desktop.
utility to extract values at given paths from given objects
This file contains 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
// iteration 0 | |
// adding deep diving for key paths | |
// based on getProperty() | |
// try on tddbin.com | |
function copyFrom(obj) { | |
const values = (...keys) => keys.map(k => getProperty(k)(obj)); | |
return { values }; | |
} | |
// "clone" of _.get, lets say.... @TODO make "setProperty" in the same fashion | |
function getProperty() { | |
return compose(...mkGetters(Array.from(arguments))); | |
// ES5: | |
// var getters = mkGetters([].slice.call(arguments)); | |
// return compose.apply(null, getters); | |
function mkGetters(args) { | |
var keys = args; | |
if (args.length === 1) { | |
keys = args[0]; | |
if (!Array.prototype.isPrototypeOf(keys)) { | |
keys = pathParser(args[0]); | |
} | |
} | |
return keys.map(curry(get)); | |
} | |
} | |
function pathParser(path) { | |
return path.split(/[\.\[\]]/g).filter(q => q !== ''); | |
} | |
function curry(fn) { | |
return function(arg) { | |
return fn.bind(null, arg); | |
} | |
} | |
var compose = (...fs) => (x) => fs.reduce((p,f) => f(p), x); | |
describe('mocha+assert API description', function() { | |
it('simple values equal?', function() { | |
// arrange | |
var obj = { "a": 14, "b": 13, "c": 11 }; | |
// act | |
var somevalues = copyFrom(obj).values("a", "c"); | |
// assert | |
assert.equal(somevalues[0], 14); | |
assert.equal(somevalues[1], 11); | |
}); | |
it('deep values equal?', function() { | |
var obj = { "a": { "a1": { "a2": 14 } }, "b": 13, "c": 11 }; | |
var somevalues = copyFrom(obj).values("a.a1.a2", "c"); | |
assert.equal(somevalues[0], 14); | |
assert.equal(somevalues[1], 11); | |
}); | |
it('sample usage', function() { | |
var obj = { "a": { "a1": { "a2": 14 } }, "b": 13, "c": 11 }; | |
var keysToCopy = ["a.a1.a2", "c"]; | |
var somevalues = copyFrom(obj).values(...keysToCopy); | |
// so now we have two arrays, one with the keys and one with the values | |
// letsay later we have a v2 of "obj" and want to know if those keys have changed: | |
var obj2 = { /* ... */ }; | |
var newvalues = copyFrom(obj2).values(...keysToCopy); | |
var haveChanged = somevalues.some( (val, i) => newvalues[i] !== val ); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment