Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active August 29, 2015 14:07
Show Gist options
  • Save XoseLluis/3828c338d232a28c240e to your computer and use it in GitHub Desktop.
Save XoseLluis/3828c338d232a28c240e to your computer and use it in GitHub Desktop.
functional style while loop
//http://deploytonenyures.blogspot.fr/2014/10/canceling-functional-style-iteration.html
//function stopCondition(item, index, array) returns true to indicate stop
//function action(item, index, array)
Array.prototype.while = function(stopCondition, action){
var curPos = 0;
while (curPos < this.length && !stopCondition(this[curPos], curPos, this)){
action(this[curPos], curPos, this);
curPos++;
}
};
var items = ["Asturies", "Armenia", "Austria", "France", "Germany"];
items.while(
function(it){
return it[0] != "A";
},
function(it){
console.log(it.toUpperCase());
}
);
console.log("----------------------------");
//using forEach we would have to resort to simulating a break with an Exception:
try{
items.forEach(function(it){
if(it[0] != "A"){
throw "break";
}
console.log(it.toUpperCase());
});
}
catch (ex){
if (ex != "break"){
throw ex;
}
}
console.log("----------------------------");
//but we can do it with _.first and avoid rolling out our own while function
var _ = require('./libs/lodash.js');
_.first(items, function(it){
return it[0] == "A";
})
.forEach(function(it){
console.log(it.toUpperCase());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment