Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
writing mutable object safely
/**
*
* @param o Object to mutate
* @param ks array of keys, or string of keys
* @param v value to assign
* @param sep custom separator if keys is string. ex: ks:"INIxxADALAHxxKEY", sep is: "xx"
*/
function mutableSet(o, ks, v, sep = '.') {
ks.split && (ks=ks.split(sep));
let i=0, l=ks.length, t=o, x, k;
while (i < l) {
k = ks[i++];
if (k === '__proto__' || k === 'constructor' || k === 'prototype') break;
t = t[k] = (i === l) ? v : (typeof(x=t[k])===typeof(ks)) ? x : (ks[i]*0 !== 0 || !!~(''+ks[i]).indexOf(sep)) ? {} : [];
}
}
@ilhamgusti
Copy link
Author

ilhamgusti commented Apr 28, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment