Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// interweave two arrays with stretching; i.e. if one is shorter than the other, its elements are
// distributed to cover most of the final array
const interweave = (A, B) => {
// create [0..1] index of each item
const map = array => array.map((val, i) => ({
array,
val,
index: array.length === 1 ? 0.5 : i / (array.length - 1)
}));
const a = map(A);
const b = map(B);
// build result by taking lowest index item; alternating in case of equality
const res = [];
let last = {
array: A.length > B.length ? B : A
};
while (a.length > 0 || b.length > 0) {
let next = null;
let nextA = a[0];
let nextB = b[0];
if (!nextA) {
next = b.shift();
} else if (!nextB) {
next = a.shift();
} else if (nextA.index < nextB.index) {
next = a.shift();
} else if (nextA.index > nextB.index) {
next = b.shift();
} else {
next = last.array === B ? a.shift() : b.shift();
}
res.push(next);
last = next;
}
return res.map(it => it.val);
};
console.log(interweave([1],[10,20,30,40]));
// [10, 20, 1, 30, 40]
console.log(interweave([1,2],[10,20,30,40]));
// [10, 1, 20, 30, 2, 40]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment