Created
March 11, 2018 22:37
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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