Created
March 30, 2017 14:48
-
-
Save mainnika/e2f9229080ae29b4f325fbb7d247f9fa to your computer and use it in GitHub Desktop.
iterable modifier
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
'use strict'; | |
const util = require('util'); | |
const dump = (obj) => console.log.call(null, util.inspect(obj)); | |
const change = (obj, path, newValue) => { | |
const iterable = path | |
.split('.') | |
[Symbol.iterator](); | |
for (let iter = iterable.next(), modifier = null; obj !== undefined; iter = iterable.next()) { | |
if (!iter.done) { | |
modifier = ((obj) => (value) => obj[iter.value] = value)(obj); | |
obj = obj[iter.value] | |
continue; | |
} | |
modifier(newValue); | |
return true; | |
} | |
return false; | |
} | |
const example = { | |
foo: { | |
bar: { | |
value: 1, | |
}, | |
}, | |
}; | |
dump(example); | |
change(example, 'foo.bar.value', 2); | |
dump(example); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment