Jared Rader

Verbal Math in JavaScript

I’m a fan of this fluent calculator exercise (I covered my solution using Ruby in my last blog post), and on another flight, I decided to implement a solution in JavaScript. Ruby’s object-oriented nature and metaprogramming capabilities made the task fairly simple; how would it go in JavaScript?

Recall that this exercise requires one to be able to verbally enter math operations, i.e. one(plus(one())), and return the correct integer result.

In Ruby, because most everything is an object, I was able to call methods on my integers, like 1.send(:+, 1). In JavaScript, integers are just primitive data types - not objects that can receive messages. But JavaScript’s ability to return functions allows us to achieve the same ability.

Again, I started off with the one() function. I knew one() would need to optionally take an argument, which would be an operator function. If no operator function was passed, I simply return 1. Otherwise, I need to return an operation on 1:

function one(opFunc) {
  if (opFunc == undefined) {
    return 1;
  } else {
    // as yet unwritten code

Verbal Math In Ruby

Came across an interesting code challenge on Code Wars a while back. It involved defining methods in a way to be able to type mathematical operations verbally, i.e. one plus one which would return 2.

I pondered over this for a while, and on a flight back from San Francisco came up with a neat solution and even learned a couple interesting things about metaprogramming.

I started with defining one. I know that I’ll want to potentially pass an argument to one. If I don’t have an argument, I’ll just want to return the integer 1. Simple enough. I can just give my method definition argument a default value of nil, check whether I have an operator, and if I don’t, simply return the integer 1:

def one(operator_method = nil)
  if operator_method
    # as yet undefined code

Ok, so what should happen when I get an operator? I decided to find a way to implement plus.