Skip to content

Instantly share code, notes, and snippets.

@thisdavej
Created March 11, 2018 22:37
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 thisdavej/87fb763b880eb2a94eee719d7d7027ac to your computer and use it in GitHub Desktop.
Save thisdavej/87fb763b880eb2a94eee719d7d7027ac to your computer and use it in GitHub Desktop.
This JavaScript function called Array.prototype.mapUntil is like Array.prototype.map, but it only maps until a condition (predicate) is true.
Array.prototype.mapUntil = function(fn, predicate) {
const arr = [];
let done = false;
this.forEach(el => {
if (done) return arr;
if (!predicate(el)) arr.push(fn(el));
else done = true;
});
return arr;
};
// Example usage
const a = [1, 3, 5, 2, 3];
// map array multiplying all numbers by 2 until element === 5 is found
const a2 = a.mapUntil(i => i * 2, i => i === 5);
console.log(a2); // [2, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment