This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
Variadic curried sum function
(19 answers)
Closed 5 months ago.
I have been struggling to understand how to solve a problem below. I understand that it involves currying and I was able to come up with the answer if argument in sum() is included. However, I can't figure out how to solve it with sum() being empty.
I was able to come up with a solution for having a function invocation at the end s(1)(), but not for s(1).
var sum = function() { /* put your code here */};
var s = sum();
alert(s); // 0
alert(s(1)); // 1
alert(s(1)(2)); // 3
alert(s(3)(4)(5)); // 12
This is solution that works with all parameters being included and () at the end.
var sum = function(a){
return function(b){
if(b !== undefined){
return sum(a+b);
}
return a;
}
};
For the first s call console.log(s), I was only able to come up with simple solution below, to be able to return 0. It seems to be impossible to return 0 and then return a function such as s(1).
var sum = function(a){
if(!arguments.length) return 0;
};
var s = sum();
console.log(s);
Related
This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 3 years ago.
I was given the following solution to an exercise:
var s = [23, 65, 98, 5];
Array.prototype.myMap = function(callback) {
var newArray = [];
// Add your code below this line
this.forEach(a => newArray.push(callback(a)));
// Add your code above this line
return newArray;
};
var new_s = s.myMap(function(item) {
return item * 2;
});
the idea is to build your own replacement for .map() method.
My problem is to understand the callback part. So far my understand of a callback, is a funct that is passed into another function (as an arg) and is called after something else.
I cannot see where is another function being passed in as the callback in the solution, so I'm struggling to understand the exercise, mainly: this.forEach(a => newArray.push(callback(a)));
Is there anyone who could clarify this for me?
You can easily visualize synchronous callbacks by replacing the call with the functions code itself.
In your function call, callback is equal to:
function(item) { return item * 2; }
If we insert that into this line:
this.forEach(a => newArray.push(callback(a)));
we get:
this.forEach(a => newArray.push(
/*item = a*/
/*return*/ a * 2;
));
Or in other words, for each a in the array, a * 2 gets pushed to the newArray.
This question already has answers here:
What is returned from a constructor?
(7 answers)
Closed 6 years ago.
I am trying to add a instance inside a function in javscript where i have observed the following behavior
function Calculator () {
this.mm = 66;
return 2 ;
}
var calculator = new Calculator();
console.log(' --> '+calculator.mm); <<< gives output of 66
But the below code
function Calculator () {
this.mm = 66;
return {} ;
}
var calculator = new Calculator();
console.log(' --> '+calculator.mm); <<< gives me undefined
I just want to know what different does returning an object from a primitive datatype make to a function . In other words why am i getting undefined here and not 66.
you should return the variable mm in the second one.
Like return mm;
That should solve your problem.
Since you are not returning anything in the second one, that is why it is coming back as undefined.
This question already has answers here:
Two sets of parentheses after function call
(4 answers)
Closed 6 years ago.
I'm pretty baffled by this question that I came across for my interview prep. It wants me to be able to write a function called multiply that takes in parameters in this haphazard way:
multiply(5)(6);
I tried to write a callback and then refer to this in the return statement, but it was not kosher.
function multiply(function(value){
return this * value;
});
}
Does this problem require recursion?
Thanks!
If you want to call your function in this multiply(5)(6); way,
Then you must be searching for function currying. And that can be accomplished by,
function multiply(a){
return function(b){
return b * a;
}
}
//your way
console.log(multiply(2)(2)) //4
//The standard way
var multiplyBy5 = multiply(5);
var res = multiplyBy5(3);
console.log(res); // 15;
var multiplyBy10 = multiply(10);
var res = multiplyBy5(3);
console.log(res); // 30;
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I am kind of new to javascript and trying to understand some non trivial - at least so i hope :) things.
my question is general, but i have a specific example which can help me ask my question and help you understand what i mean.
the example:
function updateBookmark(bookmark){
var index = _.findIndex($scope.bookmarks, function(b){
return b.id == bookmark.id;
});
return index;
}
obviously the findIndex function is declared somewhere (in our case - lodash.js)
and it gets two parameters (at least two visible parameters: a data set, and a function)
first question:
in this example, what is b? how does b gets its value? i understand b is each of the data set's objects, but i mean - what is going behind the scenes here so b will be what it is??
second question:
the author chose to pass an anonymous function which equals b.id with bookmark.id,
i understand that he can use bookmark.id where he is using it, but how does findIndex has access to this bookmark?!
this function as i concluded earlier is declared somewhere else, does it get all the variables in the scope some how?
what is going on here?
Thanks in advance to responders and sorry for the messy question...
Jim.
If you rewrite some things, it becomes easier to understand.
Starting with the last portion:
// Q: "How does `findIndex`have access to `bookmark`"
_.findIndex(bookmarks, function (b) { });
// A: "It doesn't."
var bookmark = { id: 1 };
var bookmarks = [ /* ... */ ];
function compareWithBookmark( test ) {
return test.id === bookmark.id;
}
_.findIndex(bookmarks, compareWithBookmark);
As you can see, findIndex doesn't actually have any access to bookmark.
Rather, it has access to a function which it can pass a value to test, and that function will return whether that test passed or failed.
Under the covers of .findIndex or [].map or [].filter, they're all just taking a function, making a loop, passing each element into the function one at a time, and doing something with the return value.
function findIndex (array, test) {
var index = -1;
var i = 0;
var l = array.length;
var el;
var result;
for (; i < l; i += 1) {
el = array[i]; // <-- how `b` got its value
result = test(el, i, array); // <-- test(b)
if (!!result) {
index = i;
break;
}
}
return index;
}
The different functions would do different things with the results (map returns a new array which contains each result, filter returns an array where only !!result tests passed, et cetera), but all of them do this inner-looping.
This is also a pretty gross simplification of the looping structure and considerations, but it's exactly what's driving your expected behaviour.
Edit
Here is a full usage of the function I just defined, plus the array, plus the object I'm checking.
var bookmarks = [
{ id: 2 },
{ id: 3 },
{ id: 6 },
{ id: 14 }
];
var bookmark = { id: 3 };
function compareBookmarkIdTest (el) {
return el.id === bookmark.id;
}
var index = findIndex(bookmarks, compareBookmarkIdTest);
index; // 1
Hope that helps.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need a single function which will return the below output.
add(1) = 1
add(1)(2) = 3
add(1)(2)(3) = 6
like wise the function should return the result.
I want a function function add(){} to perform the above task.
Please help me with an optimized solution
Thanks to #ermouth for initial code.
var add = (function() {
var factory = function(value) {
var fn = function(num) {
return factory(value + num);
};
// This is the main hack:
// We will return a function that when compared / concatted will call .toString and return a number.
// Never use this in production code...
fn.toString = function() {
return value;
};
return fn;
};
return factory(0);
})();
add(1); // 1
add(1); // 1
add(1)(2); // 3
add(1)(2)(3); // 6
But beware of equal comparation:
add(2) == add(2) // false
add(2) > add(1) // true
add(2) < add(1) // false
You should wrap your function in a closure and redefine function’s toString method.
var add = (function(initNum) {
var current = initNum || 0;
var fn = function(num) {
current += num;
return fn;
};
fn.toString = function() {
return current
};
return fn;
})(0);
add(1) → 1, then add(2)(3)(4) → 10
try this:
function add() {
var erg = 0;
for(var i in arguments)
erg += arguments[i];
return erg;
}
you can call it like add(1,2,3);
Either you were given a trick question, or you've misunderstood the problem.
You cannot write a function that does this in pure JavaScript (or, for that matter, almost any other language). The problem is that it has to return a number the last time it's called, and a function at all other times. This would be doable if you knew in advance how many times your function is going to be called, but if I understand your question correctly, then you don't know that in advance. You'd need to be able to foretell the future to know when the function would be called for the last time.
You could also do this in a language with macros that let you inspect the syntax of your code as it's being run. This would let you know how long the current chain of calls is, so you'd know when to return a number instead of a function. But JavaScript doesn't do this; in fact, most languages don't.
Is it possible that your interviewers were looking for an add() function that takes a variable number of arguments? That's much easier:
function add() {
return Array.prototype.reduce.call(
arguments,
function (sum, next) {
return sum + next;
},
0
);
}