This question already has answers here:
"add" function that works with different combinations of chaining/arguments
(4 answers)
Closed 3 years ago.
I was trying to solve a puzzle which takes 'n' arguments and then computes sum.
function add(arg1) {
let total=arg1;
const func = function(...args){
if(!args[0]) return total;
total += args[0];
return func;
}
return func;
}
console.log(add(1)(2)(3)()); // => Should output 6
Question: Using the same logic above example, I am trying to do this:
What if I want to do something like
sum(1)(2)(3) => should give 6
If i do sum(1) => Should output 1
sum(1)(2) => should output 3 and so
forth.
This is what I've tried:
function sum2(num) {
let total = num;
const fn = function(...args) {
if(args[0]) total += args[0];
return total;
}
return fn();
}
console.log(sum2(1)) //=> Works
console.log(sum2(1)(2))// => Fails
Explanation:
Proxy : The Proxy object is used to define custom behaviour for fundamental operations. In javascript you can create traps for pretty much every operation
Used Getter function of the handler to return Sum
Used Apply function of the handler to iterate and perform addition.
function sum2(n) {
sum = n;
const adhoc = new Proxy(function a () {}, {
get (obj, key) {
return () => sum;
},
apply (receiver, ...args) {
sum += args[1][0];
return adhoc;
},
});
return adhoc
}
console.log(sum2(1));
console.log(sum2(1)(2));
console.log(sum2(1)(2)(3));
Related
onceCopy function (testFunc) {
const copyFunc = (a) => {
const copyFunc2 = (b) => {
return testFunc(a);
};
return copyFunc2;
};
return copyFunc;
};
So the function returns the inner function upon first invocation.
Then returns the inner function of the inner function of the second invocation.
Then the second inner function (third invocation) actually returns the passed argument in the parent function and only invokes it with the character we gave it on the second invocation.
Ideally I want to achieve what I'm achieving over many invocations after only the first one if that makes sense.
Edit: Yes sorry, _.once.
Edit: so first invocation onceCopy SHOULD hold a copy of the Func passed
Second invocation SHOULD trigger the copy and gives an ouput
Third invocation SHOULD give the result of the second invocation so should the fourth, fifth, sixth and so on...
My function does do this, but on the second invocation it stores a function (copyFunc2) again, but I just made that because I need somewhere to store "a".
so like we have
function multiplyBy3 (a) {return a*3}
and then once copy stores a copy of multiplyBy3
const actualFunction = onceCopy(multiplyBy3)
then upon second and third invocation what I want
actualFunction(1) = 3
actualFunction(66) = 3
so the passed function ONLY RUNS ONCE
Cant explain more than this, its in the lodash docs.
I'm not familiar with the function you're trying to reimplement, so feel free to correct me if I misunderstood. To wrap a function and ensure it's only called once you don't need multiple nested wrappings, only one with some state.
You need to keep track of whether you already have a result to return (hasResult) and if so, what that result is (result). Keeping these two variables separate allows you to cover the case when result is undefined while keeping the code easy to read and understand.
function once(wrappedFunction) {
let hasResult = false;
let result;
return (...args) => {
if (hasResult) {
return result;
}
result = wrappedFunction.apply(this, args);
hasResult = true;
return result;
}
}
// An example function to wrap
function multiply(a, b) {
return a * b;
}
const demoFunction = once(multiply)
console.log(demoFunction(1, 2)); // 2
console.log(demoFunction(3, 4)); // 2
console.log(demoFunction(5, 6)); // 2
Is this what you were looking for?
The initial function return is kept on subsequent calls. I used a second variable called in case the first call returns undefined, which should also be returned on subsequent calls.
const once = (onceFn) => {
let called;
let value;
return (...args) => {
if (called) return value;
called = true;
return (value = onceFn(...args));
};
};
function multiplyBy3(a) {
return a * 3;
}
const fn = once(multiplyBy3);
console.log(fn(3)); // 9
console.log(fn(66)); // 9
After calling the function for the 1st time, and getting the result, create a new function that returns the result, and use it whenever the wrapped function is called:
const once = fn => {
let func
return (...args) => {
if(func) return func()
const result = fn(...args)
func = () => result
return result
}
}
const multiply = (a, b) => a * b
const demoFunction = once(multiply)
console.log(demoFunction(1, 2)); // 2
console.log(demoFunction(3, 4)); // 2
console.log(demoFunction(5, 6)); // 2
This question already has answers here:
Callback function - use of parentheses
(4 answers)
Closed last year.
I'm beginner at JavaScript and I need some help with this. Let's say a user has to enter a number from the HTML form. Then in another function there is a calculation, but when I'm calling the other function I'm getting NaN. This is my function when I'm entering the number, and if I output this I'm getting the calculated result.
const enterNumbers = number => {
if (number < 10000) {
return 0.062 * number;
} else {
return 0.062 * 20000;
}
If I output this in a third function let's say
const display = () => {
console.log (enterNumbers((number)));
I'm getting the result, but then in another function I want to make some calculation with the number calculated from the enterNumbers function
const calculation = () => {
return enterNumbers * 10;
}
and then when I call the second function in the display function I'm getting a NaN.
What happens if you call?
const calculation = () => {
return enterNumbers(<ANY_NUMBER_HERE>) * 10;
}
This question already has answers here:
Using Array objects as key for ES6 Map
(4 answers)
What memoization libraries are available for Javascript? [closed]
(1 answer)
Closed 1 year ago.
Is there any way we can create a very generic function that supports all arguments?
function memoize(expensivefn) {
const map = new Map();
// args can have array, object, functions and any other data types
return function(...args) {
if (map.has(args)) return map.get(args);
const result = expensivefn(...args);
map.set(args, result);
return result;
};
}
const expensiveFunction = args => {
console.log("A very expensive function, can block the tread!");
};
const memfun = memoize(expensiveFunction);
// calling function with named function
function add(a, b) {
return a + b;
}
memfun(add); // invoke the expensive function
memfun(add); // return from cache
// calling function with anonymous function
memfun(() => {
console.log("print someting!");
}); // invoke the expensive function
memfun(() => {
console.log("print someting!");
}); // return from cache
// Calling function with array and object
memfun([1, 2, 4, 4], { name: "abc" }); // invoke the expensive function
memfun([1, 2, 4, 4], { name: "abc" }); // return from cache
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have a function , i need to delay its return until a value is set (by calling another function call_api basically i need to wait for second function result to be able to return the first function result )
here is what ti got
function getList(s, p)
{
var output = false ;
call_api(s , p , function(result){
console.log(result);
output = result;
})
while (output == false )
{
1 ;
}
return output ;
}
but it wont work while somehow is messing thing up
is there a way to solve this ?
ps : i know about promise / async function but i cant use them (its a test i ant use them in the test )
You could do it using Promises, using a callback, or by checking the value every interval, using setTimeout. You can't do otherwise by definition of the Javascript language.
Using promises:
async function getList(s, p) {
return await new Promise(resolve => call_api(s, p, result => resolve(result)));
}
Using callback:
var output = false;
call_api(s, p, result => {
output = result;
callback();
});
function callback() {
// rest of code
}
Using setTimeout:
var output = false;
call_api(s, p, result => output = result);
checkOutput();
function checkOutput() {
if (output === false) {
setTimeout(checkOutput, 100);
} else {
// rest of code
}
}
Is there any way that I can write the function so that when I call it even by passing arguments differently, it still outputs the same value
I am new to JavaScript and was recently asked this question in an interview -
Write a function sum which when called like sum(2)(3) or sum(2, 3) should return 5.
This could be done individually as follows
function sum(a){
return function(b){
return a+b
}
}
or
function sum(a, b){
return a+b
}
If I follow the first code, it won't execute sum(a, b) and of course the second code will not support sum(a)(b). Is there any way that I can merge the two code snippets so that it executes doesn't matter how I call it ?
You'll need to check how many arguments were passed. If two are passed, return the added values; otherwise, return a function that, when called, returns its argument plus the closure's argument:
const sum = (...args) => {
if (args.length === 2) {
return args[0] + args[1];
}
return arg => arg + args[0];
};
console.log(sum(2)(3));
console.log(sum(2, 3));
More generally, you can create a makeSum function to handle when the total number of arguments to accept is an arbitrary number:
const makeSum = totalArgCount => {
const fn = (...args) => {
if (args.length === totalArgCount) {
return args.reduce((a, b) => a + b, 0);
}
return fn.bind(undefined, ...args);
};
return fn;
};
const sum2 = makeSum(2);
console.log(sum2(2)(3));
console.log(sum2(2, 3));
const sum4 = makeSum(4);
console.log(sum4(2)(3)(4)(5));
console.log(sum4(2, 3, 4)(5));
function sum(a, b) {
return b !== undefined ? (a + b) : function(b) { return a + b; }
}
console.log(sum(1,2));
console.log(sum(1)(3));
You can do it like this, by checking the b argument. If it is undefined, then you return a function. If it is not, you return the sum of the numbers.
Of course you could also check the both arguments are numbers, but this is simple version to illustrate what you want.