Skip to content

Instantly share code, notes, and snippets.

@jagretz
Created December 25, 2018 14:48
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 jagretz/bfb3ac913d8cf7aaae38349c67c3e4e5 to your computer and use it in GitHub Desktop.
Save jagretz/bfb3ac913d8cf7aaae38349c67c3e4e5 to your computer and use it in GitHub Desktop.
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