Skip to content

Instantly share code, notes, and snippets.

@ilhamgusti
Created April 28, 2022 08:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilhamgusti/e9db868eeee76b60da3c9d932877ceed to your computer and use it in GitHub Desktop.
Save ilhamgusti/e9db868eeee76b60da3c9d932877ceed to your computer and use it in GitHub Desktop.
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

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