Last active
May 24, 2019 13:57
-
-
Save vaidd4/7d5785b87f03d389cf5c9fbbc11a2629 to your computer and use it in GitHub Desktop.
Map to object with a mapping description
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
const f1 = a => a + 1 | |
const f2 = (...args) => args.join(', ') | |
const src = { a: 1, b: 2, c: 3, d: 4, e: 5 } | |
const mapDesc = [ | |
'a', | |
['b', 'f'], | |
[[f1, 'c'], 'g'], | |
[[f2, 'd', 'e'], 'h'] | |
] | |
const dest = map(src, mapDesc) | |
/* | |
* Representation of the mapping: | |
* dest = { | |
* 'a': src['a'], | |
* 'f': src['b'], | |
* 'g': f1(src['c']), | |
* 'h': f2(src['d'], src['e']) | |
* } | |
* | |
* The object created: | |
* { | |
* a: 1, | |
* f: 2, | |
* g: 5, | |
* h: '5, 6' | |
* } | |
*/ | |
// The `map` function as a oneliner: | |
function map (a, d) { | |
return d.reduce( | |
(r, v) => ( | |
(Array.isArray(v) | |
? (Array.isArray(v[0]) | |
? r[v[1]] = v[0][0](...v[0].slice(1).map(k => a[k])) | |
: r[v[1]] = a[v[0]]) | |
: r[v] = a[v]) | |
, r | |
), {}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment