@extra-array/set-path-update
Version:
Sets value at path in a nested array.
27 lines (26 loc) • 555 B
JavaScript
;
function is(v) {
return Array.isArray(v);
}
function index(x, i = 0) {
return i < 0 ? Math.max(x.length + i, 0) : Math.min(i, x.length);
}
function set$(x, i, v) {
x[index(x, i)] = v;
return x;
}
function last(x, vd) {
return x.length > 0 ? x[x.length - 1] : vd;
}
function getPath(x, p) {
for (var i of p)
x = is(x) ? x[i] : undefined;
return x;
}
function setPath$(x, p, v) {
var y = getPath(x, p.slice(0, -1));
if (is(y))
set$(y, last(p), v);
return x;
}
module.exports = setPath$;