turisap
turisap

Reputation: 231

calculator on JavaScript functions

I have recently encountered a question during an interview to implement a calculator using functions in JavaScript as follows:

five(plus(one()));     //returns 6
seven(minus(one())); // returns 6

How would I implement it?

Upvotes: 0

Views: 228

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50854

One approach could be to create a function, getNumber(x) which will return a function (call it foo). Foo accepts an operator function as input and applies the operator function to x. However, in your example, the operator function for a number is not always given (eg: one()), and so, if this is the case, the operator function will default to the identity function, which will return the number x (eg: one() needs to return 1) if the operator is not supplied.

You can also create a function setOperator where you can supply an operator function on two numbers (x and y) which is then later called on the result of calling your number functions. The operator function takes in y, which then returns a new function which takes in x. As you can see by your usage of the functions (eg: five(plus(one()))) one() is supplied to the operator first, and then 5 is supplied when calling our foo function, thus, we need to accept y first, and then x.

See example below:

const getNumber = x => (f = x => x) => f(x);
const setOperator = f => y => x => f(x, y);

const five = getNumber(5);
const one = getNumber(1);
const seven = getNumber(7);

const plus = setOperator((x, y) => x+y);
const minus = setOperator((x, y) => x-y);

console.log(five(plus(one()))); // 6
console.log(seven(minus(one()))); // 6

Upvotes: 4

Related Questions