It is common to see a zip
function taking a key k
and a value v
and create an object with them:
const zip =
(k, v) =>
({[k]: v});
zip("name", "Tom");
//=> {name: "Tom"}
If both key and value are in an array you can spread it in a zip call like that zip(...arr)
. Or you can modify the signature a little bit:
const zip =
([k, v]) =>
({[k]: v});
zip(["name", "Tom"]);
//=> {name: "Tom"}
If the array contains multiple pairs of keys and values then we can design a recursive version of zip
:
const Nil = Symbol();
const zip =
([k = Nil, v = Nil, ...xs], o = {}) =>
k === Nil && v === Nil
? o
: zip(xs, (o[k] = v, o));
zip(["name", "Tom", "id", "48688"]);
//=> {name: "Tom", id: "48688"}
We can now think about slicing your array into chunks of equal number of pairs and apply zip
to each chunk.
First let's write a slices
function that will cut an array into slices of n elements:
const slices =
(xs, n, ys = []) =>
xs.length === 0
? ys
: slices(xs.slice(n), n, (ys.push(xs.slice(0, n)), ys));
slices(["name", "Tom", "id", "48688", "name", "Bob", "id", "91282"], 4);
//=> [["name", "Tom", "id", "48688"],["name", "Bob", "id", "91282"]]
We can now apply zip
to each chunk:
slices(["name", "Tom", "id", "48688", "name", "Bob", "id", "91282"], 4)
.map(chunk => zip(chunk));
//=> [{name: "Tom", id: "48688"},{name: "Bob", id: "91282"}]
const Nil = Symbol();
const zip =
([k = Nil, v = Nil, ...xs], o = {}) =>
k === Nil && v === Nil
? o
: zip(xs, (o[k] = v, o));
const slices =
(xs, n, ys = []) =>
xs.length === 0
? ys
: slices(xs.slice(n), n, (ys.push(xs.slice(0, n)), ys));
console.log(
slices(["name", "Tom", "id", "48688", "name", "Bob", "id", "91282"], 4)
.map(chunk => zip(chunk))
);