Skip to content

Instantly share code, notes, and snippets.

@nash403
Last active October 3, 2016 12:26
Show Gist options
  • Save nash403/60ebedd8d99f30e2ba388e62472cd08d to your computer and use it in GitHub Desktop.
Save nash403/60ebedd8d99f30e2ba388e62472cd08d to your computer and use it in GitHub Desktop.
Insert an element between array elements
/*
* Insert insertedEl or the result of insertedEl (if it is a function) between the elements of arr.
* Attention: nothing is inserted before the first element or after the last element of arr.
* If the predicate function is defined, the function will instert the value only if the predicate is verified (returns a truthy value).
*
* insertedEl and predicate function are both called with these arguments: prev, curr, tIdx and tArr.
* predicate has one more argument as last which is called value.
* where prev = the accumulator array wich contains the current partial value of the final array or []
* curr = the current element that will be pushed in the prev array
* tIdx = index of curr in the original array
* tArr = the original array
* value (only for predicate) = the value returned by insertedEl
*/
function insertbtwn(arr, insertedEl, predicate) {
const insertion = (typeof insertedEl === 'function') ? insertedEl : function (prec, curr, tIdx, tArr) { return insertedEl; };
return arr.reduce( (prec, curr, tIdx, tArr) => {
if (tIdx > 0) {
let value = insertion(prec, curr, tIdx, tArr);
if (predicate && typeof(predicate) === 'function') {
if (predicate(prec, curr, tIdx, tArr, value)) {
prec.push(value);
}
} else { prec.push(value); }
}
prec.push(curr);
return prec;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment