Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create and return a new array with the separator interposed between elements; intersperse :: a -> [a] -> [a]
/**
* Create and return a new array with the separator interposed between elements.
*
* intersperse :: a -> [a] -> [a]
*
* Providing the separator as the first argument allows this method to be easily
* curried and composed with other functions; follows the "data last" approach.
*
* @param {*} separator
* @param {*} array
*/
const intersperse = (separator, list) => {
const length = list.length;
const output = [];
let i = 0;
// eager return is list cannot be interspersed
if (length < 2) {
return Array.from(list);
}
// add each elem and separator to new list
while (i < length - 1) {
output.push(i, separator);
i++;
}
// add the last index to the new list
output.push(list[i])
return output;
}
/**
* For future-safety (avoid built-ins) we can create the intersperse function as a
* polyfill with little effort.
*/
export const interspersePolyfill = (function () {
if (!Array.prototype.intersperse) {
Object.defineProperty(Array.prototype, "intersperse", {
writable: false,
value: intersperse
})
}
}
)();
export default intersperse;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment