Skip to content

Instantly share code, notes, and snippets.

@sri-rang
Created December 25, 2011 15:51
Show Gist options
  • Save sri-rang/1519449 to your computer and use it in GitHub Desktop.
Save sri-rang/1519449 to your computer and use it in GitHub Desktop.
Functional Programming in JavaScript - 6
var forEach = function (list, action) {
for (var i = 0; i < list.length; i++) {
action(list[i]);
}
};
var reduce = function (combine, base, list) {
forEach(list, function (item) {
base = combine(base, item);
});
return base;
};
var countNegativeNumbers = function (negativeNumbersTillNow, currentNumber) {
if (typeof currentNumber === "number" && currentNumber < 0) {
negativeNumbersTillNow += 1;
}
return negativeNumbersTillNow;
};
var initialCount = 0;
console.log(reduce(countNegativeNumbers, initialCount, [1, -1, 0, 45, "-42", -42]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment