Functional Programming with JavaScript

Really interesting chapter from a great book: functional programming in JavaScript

There are some scripts related to functional programming paradigm in JavaScript from the chapter:

  • Foreach loop
function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}
  • Condition negate
function negate(func) {
  return function() {
    return !func.apply(null, arguments);
  };
}
  • Reduce, sum, array operations
function reduce(combine, base, array) {
  forEach(array, function (element) {
    base = combine(base, element);
  });
  return base;
}

function add(a, b) {
  return a + b;
}

function sum(numbers) {
  return reduce(add, 0, numbers);
}
  • Count, array operation
function count(test, array) {
  return reduce(function(total, element) {
    return total + (test(element) ? 1 : 0);
  }, 0, array);
}
  • Simple equal operation
function equals(x) {
  return function(element) {return x === element;};
}
  • Map, array operation
function map(func, array) {
  var result = [];
  forEach(array, function (element) {
    result.push(func(element));
  });
  return result;
}

 

Eloquent JavaScript

A Modern Introduction to Programming

by Marijn Haverbeke

http://eloquentjavascript.net/

Advertisements

One thought on “Functional Programming with JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s