Arithmetic with functions in Javascript - javascript

I am trying to write a function that solves the following math problem: 3625 * 9824 + 777, using only two functions: "add" and "multiply". I am stuck here:
var multiply = function (number) {
return * 9824;
};

You need to refer to the function's argument (number) to "tell" javascript what you're multiplying:
var multiply = function (number) {
return number * 9824;
// Here^
};

Good start.
Remember that the function parameter (in this case, number) can be used as a variable inside the function itself. In your case, you want to multiply whatever number is passed in and return the result. So what you'd be looking for here is:
var multiply = function(num) {
return num * 9842;
}
:) Good luck!

first create your functions:
function add(a, b){
return a+b;
}
function multiply(a,b){
return a*b;
}
then you can call them...
let ans = 0;
ans = multiply(3625, 9824);
ans = sum(ans, 777);
console.log("3625 * 9824 + 777 = ",ans);
Keep going :) and this apply to all functional languages :D

function add(a,b)
{
return (parseInt(a)+parseInt(b));
}
function multiply(a,b)
{
return (parseInt(a)*parseInt(b));
}
var result = add(mutiply(3625,9824),777);

Try this:
function add(a, b) {
return a + b;
};
var resultAdd = add(9824, 777);
function multiply(a, b) {
return a * b;
};
var result = multiply(resultAdd, 36325);

Related

Only allowing a function to run n times with wrapper function

I need to make a wrapper function to invoke a function multiply with a given number num of times to allow the multiply to execute. nTimes(num,2) Then assign to runTwice -- runTwice can be any function that invoke the nTimes function which given a different num input--
In my case, for simplicity, I am only allowing it to run 2 times num=2
If we run the runTwice function the first time and the second time it will return the result of multiply function calculated with the inputs for multiply. Any invocation after the second time will not run the multiply function but will return the latest result of the multiply function.
Here is my implementation using an object to keep track of how many times we have execute the function, the max number allowed to execute and the latest result of multiply
'use strict'
//use a counter object to keep track of counts, max number allowed to run and latest result rendered
let counter = {
count:0,
max: 0,
lastResult: 0
};
let multiply = function(a,b){
if(this.count<this.max){
this.count++;
this.lastResult = a*b;
return a*b;
}else{
return this.lastResult;
}
}
// bind the multiply function to the counter object
multiply = multiply.bind(counter);
let nTimes=function(num,fn){
this.max = num;
return fn;
};
// here the nTimes is only executed ONE time, we will also bind it with the counter object
let runTwice = nTimes.call(counter,3,multiply);
console.log(runTwice(1,3)); // 3
console.log(runTwice(2,3)); // 6
console.log(runTwice(3,3)); // 6
console.log(runTwice(4,3)); // 6
Note that I have altered the simple multiply quite a bit and bind it the counterobject to make it work. Also using call on nTimes to bind counter object.
What can I do to implement the same result with a wrapper function but less alteration to the simple multiply function?
Let's say the multiply function is very simple:
let multiply = function(a,b){ return a*b };
You could use a closure over the count and the last value and check count and decrement and store the last result.
const
multiply = (a, b) => a * b,
maxCall = (fn, max, last) => (...args) => max && max-- ? last = fn(...args) : last,
mult3times = maxCall(multiply, 3);
console.log(mult3times(2, 3));
console.log(mult3times(3, 4));
console.log(mult3times(4, 5));
console.log(mult3times(5, 6));
console.log(mult3times(6, 7));
Nina's answer is great. Here's an alternative, with code that might look slightly easier to read:
function multiply(a, b) {
return a * b;
}
function executeMaxTimes(max, fn) {
let counter = 0, lastResult;
return (...args) => counter++ < max
? lastResult = fn(...args)
: lastResult;
}
const multiplyMaxTwice = executeMaxTimes(2, multiply);
console.log(multiplyMaxTwice(1, 3)); // 3
console.log(multiplyMaxTwice(2, 3)); // 6
console.log(multiplyMaxTwice(3, 3)); // 6
console.log(multiplyMaxTwice(4, 3)); // 6
Seeing how both Nina and Jeto have answered your question, here is a simple and similar way to do it that also keeps a history of all the results in case you want to get them at a later time.
function multiply(a, b) {
return a * b;
}
function runMaxNTimes(num, callBack) {
var results = new Array(num);
var callTimes = 0;
return function(...params) {
return results.length > callTimes ?
results[callTimes++] = callBack(...params) :
results[callTimes - 1];
};
}
var runTwice = runMaxNTimes(2, multiply);
console.log(runTwice(1, 3)); // 3
console.log(runTwice(2, 3)); // 6
console.log(runTwice(3, 3)); // 6
console.log(runTwice(4, 3)); // 6

Sum function currying

I'm trying to write a sum function that does the following:
sum(1)(2)(3) => returns 6
However, I am having hard time with my solution. I know i'm making a silly mistake, can someone point me in the right direction?
My Implementation:
function add(args) {
let sum = args[0];
let func = function(...args2) {
if (!args2[0]) return sum;
sum += args2[0];
return func;
}
return func;
}
add(1)(2)(3);
Additionally, can I write a generic function that does the following?
add(1)(2)(3) or add (1)(2)(3) () => 6
To have an arbitrary amount of calls, all which take a number, you'd need the return value to behave both as a function and a number depending. So that:
const five = add(2)(3);
console.log(five(10)); // behaves like a function
console.log(five + 10); // behaves like a number
I can't think of anyway to do that (or if there's a good reason one should do that) other than what I'd call a hack.
With that said, for fun I was able to do the following by abusing valueOf():
const add = (num1) => {
const func = (num2) => add(num1 + num2);
func.valueOf = () => num1;
return func;
}
console.log(add(1)(2)(3)); // *logs function* [output varies by environment]
console.log(add(1)(2)(3) + 10); // 16
console.log(add(1)(2) + 10); // 13
console.log(add(1) + 10); // 11
console.log(add(1)(2)(3) == 6); // true
console.log(add(1)(2)(3) === 6); // false
console.log(typeof add(1)(2)(3)); // function
console.log(typeof (add(1)(2) + 3)); // number
But that's obviously not very kosher.
Edit: Switched from using toString() to valueOf() per #PatrickRoberts's comment.
Recursion anyone? 😂
function add(n) {
return function(m) {
if (isNaN(m)) return n;
return add(n + m);
};
}
// add(1)(2)(3)() => 6
// add(1)(2)(3)("")() => "6"
// add(1)("2")(3)() => "123"
// functional one liner
const add = n => m => isNaN(m) ? n : add(n + m);
Try this, you omitted the spread operator
function add(...args) {
let sum = args[0];
let func = function(...args2) {
if(args2[0] === undefined) return sum;
sum += args2[0];
return func;
}
return func;
}
console.log(add(1)(2)(3)());
cheers!!
function sum(x){
return function (y){
return function(z){
return x+y+z;
}
}
}
You can call like :
sum(1)(2)(3)

Can I add numbers using JavaScript Closures?

How can I create a closure function, that sums all passed arguments, like this?
Add(2)(2) //4
Add(2)(2)(3) // 7
Add(3)(2)(3)(0) // 8
function Add(number){
return function(number1){
return function(number2){
return number+number1+number2;
}
}
}
alert(Add(2)(2)(2));
I wanted a generalized way to achieve this.
There are duplicates here, probably with better examples, but I can't find one right now. You need to create a closure to keep track of the sum, then return the add function. Give it valueOf and toString methods so it works in other operations:
var add = (function() {
var sum = 0;
function add(n) {
sum += +n || 0;
return add;
}
add.valueOf = function(){
return sum;
}
add.toString = valueOf;
return add;
}());
document.write(add(1)(2)(3)(-2)); // 4
document.write('<br>' + add(2)(1) * 2); // 14
document.write('<br>' + add( -add())); // 0

How to pass a parameter with function signature

I don't have a control over the function invocation and I need to pass a few parameters with a pointer. Is it possible to do it?
var a = function(a, b){
return a + b;
}
b = a; //parameter here???
Any help will be appreciated!
You can use currying, the outer function call will return a pointer to another function that references the parameters you passed. Then you can call the inner function without passing the parameters.
var a = function(x, y) {
function(){
return x + y;
}
}
b = a(2, 3);
b();
The correct way to pass parameters to a is to replace your last line with : b = a(1, 2);.
This will give you 3 as a result, stored into the variable b.
You can see the current value of b at any time by running console.log(b); :
var a = function(a, b){
return a + b;
}
b = a(1, 2); // parameters here
console.log(b); // prints 3
But as I said, the use of b twice here is confusing. A better naming would be :
// sum is a better name
var sum = function(a, b){
return a + b;
}
result = sum(1, 2); // parameters here : 1 corresponds to a, 2 to b
console.log(result); // prints 3
Figured out myself. I am sorry if the question is not clear enough.
This is what I needed.
var a = function(a, b) {
return function(){
console.log(a + b);
}
};
b = a(3, 4);
b();

Javascript: Use reduce() method to find the LCM in an array

I am trying to find the LCM(least common multiples) among several numbers in an array. To get a LCM between each two numbers in the array, I use the reduce() method which is not working.Please tell me what's wrong? Thanks.
function gcd(a,b){
//gcd: greatest common divisor
//use euclidean algorithm
var temp = 0;
while(a !== 0){
temp = a;
a = b % a;
b = temp;
}
return b;
}
function lcm(a,b){
//least common multiple between two numbers
return (a * b / gcd(a,b));
}
function smallestCommons(arr) {
//this function is not working, why?
arr.reduce(function(a, b){
return lcm(a, b);
});
}
smallestCommons([1,2,3,4,5]);
//------>undefined
Your smallestCommons function is missing a return. undefined is the default return value for all functions that don't have an explicit return.
function smallestCommons(arr) {
return arr.reduce(lcm);
}

Categories