0

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?

1
  • 3
    The posted question does not appear to include any attempt at all to solve the problem. Stack Overflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into in a minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Sep 14, 2019 at 6:20

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Very nice, but I'd define getNumber as f ? f(x) : x, otherwise seven(mul(zero())) will break.
Thanks @georg, I missed that edge case. Thanks for pointing that out :)
@NickParsons, thanks a lot, I have been cracking my mind how to do that. It's quite clear now, you saved my day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.