@sovgut/allocate
Version:
<p align="center"> <b>A lightweight TypeScript utility for transforming object and array structures by remapping keys according to a schema. Perfect for API response transformation, data migration, and object restructuring.</b> </p>
77 lines (76 loc) • 2.05 kB
JavaScript
function y(i) {
if (i === null || typeof i != "object") return i;
if (Array.isArray(i)) return i.map((f) => y(f));
const r = {};
for (const f in i)
i.hasOwnProperty(f) && (r[f] = y(i[f]));
return r;
}
function h(i) {
const r = [];
let f = "", t = 0;
for (; t < i.length; )
i[t] === "[" && t + 1 < i.length && i[t + 1] === "]" ? (f && (r.push(f), f = ""), r.push("[]"), t += 2, t < i.length && i[t] === "." && t++) : i[t] === "." ? (f && (r.push(f), f = ""), t++) : (f += i[t], t++);
return f && r.push(f), r;
}
function g(i, r) {
const f = h(r);
function t(e, n) {
if (n >= f.length)
return e;
const s = f[n];
if (s === "[]")
return Array.isArray(e) ? e.map((a) => t(a, n + 1)) : void 0;
if (e != null)
return t(e[s], n + 1);
}
return t(i, 0);
}
function p(i, r, f) {
const t = h(r);
function e(n, s, a) {
if (s >= t.length)
return;
const l = t[s], o = s === t.length - 1;
if (l === "[]") {
if (!Array.isArray(n)) return;
n.forEach((u, A) => {
const c = Array.isArray(a) ? a[A] : a;
e(u, s + 1, c);
});
return;
}
o ? n[l] = a : (t[s + 1] === "[]" ? (!(l in n) || !Array.isArray(n[l])) && (Array.isArray(a) ? n[l] = a.map(() => ({})) : n[l] = []) : (!(l in n) || typeof n[l] != "object" || n[l] === null) && (n[l] = {}), e(n[l], s + 1, a));
}
e(i, 0, f);
}
function P(i, r) {
const f = h(r);
function t(e, n) {
if (n >= f.length || !e)
return !1;
const s = f[n], a = n === f.length - 1;
if (s === "[]") {
if (!Array.isArray(e)) return !1;
let l = !1;
return e.forEach((o) => {
t(o, n + 1) && (l = !0);
}), l;
}
return a ? s in e ? (delete e[s], !0) : !1 : s in e ? t(e[s], n + 1) : !1;
}
t(i, 0);
}
function m(i, r) {
if (i == null || typeof i != "object")
return i;
const f = y(i);
for (const [t, e] of Object.entries(r)) {
const n = g(i, t);
p(f, e, n), t !== e && P(f, t);
}
return f;
}
export {
m as allocate
};