Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Created August 31, 2019 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerrishotts/bde38981facd1623aad5838691118ce5 to your computer and use it in GitHub Desktop.
Save kerrishotts/bde38981facd1623aad5838691118ce5 to your computer and use it in GitHub Desktop.
Dev.to Aug 31 2019 Faro
const split = arr =>
[arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
const interleave = (a, b) =>
a.reduce((shuffled, aIdx, idx) => (shuffled.push(aIdx, b[idx]), shuffled), []);
const faro = arr => interleave(...split(arr));
/* -- Testing -- */
const assert = (exprFn, expected, msg = "Assert") => {
try {
const r = JSON.stringify(exprFn());
if (r !== JSON.stringify(expected)) throw new Error(r);
} catch(err) {
throw new Error(`${msg}: Expected ${expected}, but got ${err.message}`);
}
}
assert(() => faro([]), [], "Zero length");
assert(() => faro([1, 2]), [1, 2], "Two items");
assert(() => faro([1, 2, 3, 4]), [1, 3, 2, 4], "Four items");
assert(() => faro(["a", "b", "c", "d"]), ["a", "c", "b", "d"], "Four string items");
assert(() => faro(['ace', 'two', 'three', 'four', 'five', 'six']),
['ace', 'four', 'two', 'five', 'three', 'six'], "Dev.to test case");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment