Functional Math With Closures

E

ven though javascript is the most widely used programming language in the world, people still bash it. *Closures are confusing and prone to errors*, people will often say. Which is a true statement. However, higher order functions and closures are one of the things javascript does best. It allows us bend the language to do some pretty interesting things.

In one situation, I pointed out one could create a function based math library and just dynamically create equations on the fly rather than having to hard code math logic all over the place, where all numbers and operations are functions that accept functions as arguments. Of course I was challenged on the fact - So, of course I had to write a math library. It looks something like this.

// numbers
exports.one = function( op ){
  return op ? op.call( null, 1 ) : 1;
};

exports.two = function( op ){
  return op ? op.call( null, 2 ) : 2;
};

exports.three = function( op ){
 return op ? op.call( null, 3 ): 3;
};

exports.four = function( op ){
 return op ? op.call( null, 4 ): 4;
}; 

exports.five = function( op ){
 return op ? op.call( null, 5 ): 5;
};

exports.six = function( op ){
 return op ? op.call( null, 6 ): 6;
};

exports.seven = function( op ){
 return op ? op.call( null, 7 ): 7;
};

exports.eight = function( op ){
 return op ? op.call( null, 8 ): 8;
};

exports.nine = function( op ){
 return op ? op.call( null, 9 ): 9;
};

exports.zero = function( op ){
 return op ? op.call( null, 0 ): 0;
};


Simple enough. All of the numbers of 0 through 9. If a number function receives a operation function, it calls it passing its value along returning the result. Otherwise it will just return its value. On to operations.

// operations

exports.plus = function( b ){
  return function( a ){
    return a + b;
  }
};

exports.minus = function( b ){
  return function( a ){
    return a - b;
  }
};

exports.times = function( b ){
  return function( a ){
    return a * b;
  }
};

exports.dividedBy = function( b ){
  return function( a ){
    return a / b;
  }
};

A little more going on, but still simple. Each operation function accepts the right hand side or b and returns a partial application function which will accept the left hand side of the equation, or a. Then it returns the result of the operation. Done. While there may not be a ton of use cases, it illustrates one of the more powerful features of javascript. And it does end up looking nice!

six( times( eight( dividedBy( two( plus( two( ) ) ) ) ) ) ) // 12

Not a complete library, but you get the idea.

closure functional programming arithmetic