Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Evenly interleave two arrays
Array.prototype.chunk = function (groupsize) {
var sets = [];
var chunks = this.length / groupsize;
for (var i = 0, j = 0; i < chunks; i++, j += groupsize) {
sets[i] = this.slice(j, j + groupsize);
}
return sets;
};
var interleave = (a1, a2) => {
if (a1.length < a2.length) {
return interleave(a2, a1);
} else if (a1.length > a2.length) {
const chunksCount = a2.length + 1;
const chunksSize = Math.ceil(a1.length / chunksCount);
return a1
.chunk(chunksSize)
.map((v, i) => (a2.length === i ? v : [...v, a2[i]]))
.flat();
} else {
return a1.map((v, i) => [v, a2[i]]).flat();
}
};
describe("interleave", () => {
it("even input", () => {
const result = interleave(
[1, 2, 3, 4, 5, 6],
["a", "b", "c", "d", "e", "f"]
);
expect(result).toEqual([1, "a", 2, "b", 3, "c", 4, "d", 5, "e", 6, "f"]);
});
it("zero length", () => {
const result = interleave([1, 2, 3, 4, 5, 6], []);
expect(result).toEqual([1, 2, 3, 4, 5, 6]);
});
it("in between", () => {
const result = interleave([1, 2, 3, 4, 5, 6], ["a", "b"]);
expect(result).toEqual([1, 2, "a", 3, 4, "b", 5, 6]);
});
it("in between just one element", () => {
const result = interleave([1, 2, 3, 4, 5, 6], ["a"]);
expect(result).toEqual([1, 2, 3, "a", 4, 5, 6]);
});
it("unbalanced interleave", () => {
const result = interleave([1, 2, 3, 4, 5, 6, 7], ["a", "b"]);
expect(result).toEqual([1, 2, 3, "a", 4, 5, 6, "b", 7]);
});
it("unbalanced interleave one element", () => {
const result = interleave([1, 2, 3, 4, 5, 6, 7], ["a"]);
expect(result).toEqual([1, 2, 3, 4, "a", 5, 6, 7]);
});
it("more unbalanced interleave", () => {
const result = interleave([1, 2, 3, 4, 5, 6, 7, 8], ["a", "b"]);
expect(result).toEqual([1, 2, 3, "a", 4, 5, 6, "b", 7, 8]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment