Skip to content

Instantly share code, notes, and snippets.

@jamigibbs
Last active February 3, 2023 09:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamigibbs/adafd95cf738fa872bda to your computer and use it in GitHub Desktop.
Save jamigibbs/adafd95cf738fa872bda to your computer and use it in GitHub Desktop.
Calculating With Functions. eg. seven(times(five()));
function makeNum(num, func) {
if (func === undefined) {
return num;
} else {
return func(num);
}
}
function zero(func) {
return makeNum(0,func);
}
function one(func) {
return makeNum(1,func);
}
function two(func) {
return makeNum(2,func);
}
function three(func) {
return makeNum(3,func);
}
function four(func) {
return makeNum(4,func);
}
function five(func) {
return makeNum(5,func);
}
function six(func) {
return makeNum(6,func);
}
function seven(func) {
return makeNum(7,func);
}
function eight(func) {
return makeNum(8,func);
}
function nine(func) {
return makeNum(9,func);
}
function plus(right) {
return function(left) { return left + right; };
}
function minus(right) {
return function(left) {
return left - right;
};
}
function times(right) {
return function(left) { return left * right; };
}
function dividedBy(right) {
return function(left) { return left / right; };
}
eight(minus(three())); // return 5
six(dividedBy(two())); // return 3
two(plus(five())); // return 7
five(plus(two())); // return 7
seven(times(five())); // return 35
console.log(four(plus(nine()))); // must return 13
@veronaten
Copy link

Thank you!

@timmcwilliams
Copy link

I don't get it. Can you explain some details about how this works? Thank you!

@jamigibbs
Copy link
Author

@timmcwilliams They are higher-order functions which means they operate using other functions either by taking them as arguments or by returning them.

The "left" and "right" attributes indicate whether the mathematical operation (plus(), minus(), divideBy()) is using the number function (one(), two(), three()...) that initially started the calculation (left), or, using the number function (one(), two(), three()...) that was passed in as an argument (right).

The solution is based on this kata: https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39

@timmcwilliams
Copy link

timmcwilliams commented Mar 1, 2022 via email

@saisugavasi9951
Copy link

Hi Jami, I need some clarity on this code can i get?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment