Getting NaN when trying to add numbers using recursion [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to add unknown number of arguments without a loop. here's what I have done so far.
var add = function add() {
if (!arguments.length) {
return 0;
} else {
var args = [].slice.call(arguments, 0);
console.log(args[0], arguments);
args.splice(0, 1);
return args[0] + add.apply(this, args); //needtoreadaboutapply
}
};
and this is the output I get when I call add(3,4,5).
So what am I doing wrong and how can I debug such recursive calls in browser console?
3 [3, 4, 5]
4 [4, 5]
5 [5]
NaN

You are removing one element from the argument and accessing the same. So that action will cause problem when dealing with last parameter. When you remove the last parameter the array will be [] empty, at that time if you access arg[0] that will give you undefined. undefined + number = NaN.
Try to use the removed number instead of accessing it from the array,
var add = function add() {
if (!arguments.length) {
return 0;
} else {
var args = [].slice.call(arguments, 0);
var spliced = args.splice(0, 1);
console.log(args[0], arguments);
return spliced[0] + add.apply(this, args); //needtoreadaboutapply
}
};

If you aren't stuck with using recursive functions, you might want to look into using .reduce()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var add = function add() {
var args = [].slice.call(arguments, 0);
return args.reduce(function(sum, num) {
return sum + num;
}, 0);
};

Change return args[0]+add.apply(this,args); to return arguments[0]+ add.apply(this,args)
In the question, I made a mistake of splicing args first and then referencing args[0].

Related

Is there a way I can create infinite closures in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was presented with question and I had no idea how to do it
add() - > returns 0
add(1)() -> returns 1
add(1)(2)() -> returns 3
add(1)(2)(3)(4)() -> 10
Basically it can go on
Here is my one line solution if you love aesthetics
const add = (val) => (val ? (arg) => (arg ? add(val + arg) : val) : 0);
console.log(add(1)(2)(3)())
For Readability:
const add = (val) => {
if (val) {
return (arg) => {
if (arg) {
return add(val + arg);
} else {
return val;
}
};
}
return 0;
};
console.log(add(1)(2)(3)())
Edit : Explaination
I'll try to explain it in a simple way
lets break it down with a example add(1)(2)(3)()
So it happens like this
add(1) is evaluated first
add(1) -> returns a function (say _add())
_add() is a closure so it has access to the val variable (with value 1) and has its own parameter args with value 2
_add(2) -> calls add() again with the result of the addition (val + args)
add(1)(2)(3)() becomes -> _add(2)(3)()
_add(2) checks if it has a parameter args and if it does then it computes val + args and returns add(val +args) else 0
_add(2)(3)() becomes -> add(3)(3)()
add(3) -> _add()
_add(3) -> val + args -> add(val+args) -> add(6)
add(3)(3)() becomes -> _add(6)()
add(6)() -> returns _add()
_add() this time no parameter so return the value
I hope I was able to explain, comment if you have any doubts, I'll try my best
You can access the arguments through the variable arguments. Read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
I'm using a basic for loop, mostly for clarity, to show case it below.
function add() {
var sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
/* Alternative loop
for (let number of arguments) {
sum += number;
} */
return sum;
}
console.log( add(1) );
console.log( add(1, 2) ); // returns 3
console.log( add(1, 2, 3, 4) ); // returns 10
I think you are looking for this.
function add(a){
func = function(b){
func.result+=b;
return func;
}
func.result = a;
return func;
}
console.log(add(2)(2).result);
Each sequential call returns the same function again. You can do it infinitely and access result as property of the returned function.

return value from function VS assign to var and then return? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
From time to time while writing code I'm thinking what is better ?
just return value from function or create variable for this value and then return. Is it just about taste? or there is some benefits of direct return?
// variant 1
function (a, b) {
const c = a + b * 2;
return c;
}
function (a, b) {
return a + b * 2;
}
// variant 2
async function () {
const {data} = await fetch(api);
const c = {
...data,
hello: "world",
}
return c;
}
async function () {
const {data} = await fetch(api);
return {
...data,
hello: "world",
};
}
There is one plus of having more variables defined in function and more statements defined in it too. In this case you can add more breakpoints in function while debugging it. For example:
In this case we can check if b multiplication with 2 was successful or not. Otherwise if whole formula to be put as one return statement - we would not have the ability to do so. While this example is very primitive and not very reasonable for this case, however sometimes we have such huge and complex formulas that only step-by-step debugging of them may be useful to track bugs or accomplish business requirements.

Javascript functional programming - Should I write functions that force currying, or use _.curry when calling instead? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Example:
Version 1:
const foo = (arg1) => {
return (arg2) => {
return (arg3) => {
return arg1 + arg2 + arg3;
}
}
}
// called as part of a pipe:
const result = pipe(bar, foo(arg1)(arg2), baz);
Version 2:
const foo = (arg1, arg2, arg3) => {
return arg1 + arg2 + arg3;
}
// called as part of a pipe:
const result = pipe(bar, _curry(foo)(arg1)(arg2), baz);
The method implementation is much cleaner and more elegant in Version 2, however the call is a little uglier. Since method calls (hopefully) appear in more than one place in the codebase, I'm trying to decide which version has less drawbacks.
I hope I don't need to explain why I want to achieve using curried functions and passing single arguments. Please approach the question from a pro-functional programming standpoint.
Thanks in advance!
You can use the arguments object of the function in case you don't know how many arguments there could be like this:
function foo() {
var sum = 0;
for(var i = 0; i < arguments.length; i++)
sum += arguments[i];
return sum;
}
console.log(foo());
console.log(foo(1, 2, 3));
console.log(foo(5, 6, 3, 7, 1, 10));
And if you want a currying that is independent of the number of arguments without forcing it using _.curry, then use this:
function foo(a) {
var sum = 0;
var _ = function(a) {
if(a === undefined)
return sum;
else {
sum += a;
return _;
}
}
return _(a);
}
console.log(foo());
console.log(foo(1)(2)());
console.log(foo(1)(2)(7)(10)(5)());

Is there a way to check if an array holds more than one value? [closed]

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 7 years ago.
Improve this question
For example, what if I needed my code to have a certain set of numbers in an array list for something to happen? For example this array [1,3,4,5,9]. Is there any way I could check and see if an array contained all these integers at once and in the same order?
var arraySearch = function (subArray,array ) {
var i = -1;
return subArray.every(function (v) {
if(i != -1) {
i++;
return (array.indexOf(v) === i)
}
i = array.indexOf(v);
return i >= 0;
});
};
var arr = [1,3,4,5,9];
console.log(arraySearch([4,5],arr))
{1,3,4,5,9} is not an array. It's nothing valid in Javascript, for that matter.
myArray = [1,3,4,5,9] is an array. You can check the number of elements it contains with myArray.length.
Is there any way I could check and see if an array contained all these
integers at once and in the same order?
For this, you will have to provide some code of your own and show what you've tried first.
Fundamental
To check whether an array contain an element just once,
you may simply check if both indexOf and lastIndexOf yields exactly the same value and are greater then or equal zero.
var array = [1,2,3,3,3];
function isContainOnce(array,num){
return array.indexOf(num)>=0 && array.indexOf(num)==array.lastIndexOf(num)
}
// Try it
isContainOnce(array,3); // false
isContainOnce(array,10); // false
isContainOnce(array,1); // true
Now you can iteratively check the occurrence of such elements
function isContain(arr,sub){
var subArray = sub.slice();
var k = null;
while (subArray.length>0){
var s = subArray.shift(); // Take the first element to test
var i = arr.indexOf(s);
var j = arr.lastIndexOf(s);
if (i<0 || i!=j) return false; // Does not exist once
if (k && i-k!=1) return false; // Not in order
k = i;
}
return true;
}
To check whether [1,3,4,5,9,10,11,11] contains a sub array [1,3,4,5,9] with all elements in the same order:
isContain([1,3,4,5,9,10,11,11], [1,3,4,5,9]); // TRUE
Other cases
isContain([1,3,4,5,9,10,11,11], [5,9,10]); // TRUE
isContain([1,3,4,5,9,10,11,11], [2,3]); // FALSE
isContain([1,3,4,5,9,10,11,11], [10,11]); // FALSE because 11 occurs twice
If it's for an exact match:
yourArray.toString() === "1,3,4,5,9";
If the numbers you're searching for are a subset of the array, possibly with extra numbers in the middle, you have to loop through the elements.

how can you find the min number in this function in javascript [closed]

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
how can you find the min or max number in a function like this
{"a",5,"h",7,true,6,"h",7}. The solution must be applicable to other kinds of functions with the same characteristic.
I set min = arguments[0] but what if it's not a number?
you know i was reading about functions and I read about arguments objects,which contains an array of arguments.i tried this:
function argsMin() {
var i = 0;
var min=arguments[0];
for(i=0;i<arguments.length;i++) {
if(min>arguments[i]){
min=arguments[i];
}
}
return min;
}
document.write(argsMin(1124,562,-973,955));
now what if the first index is not a number.
Sweet and simple:`
var arr = ["a",5,"h",7,true,6,"h",7];
var min = Math.min.apply(null, arr.filter(function(el){
return typeof el == "number";
}));
//min = 5
And for older browser that do not support filter, use you can use polyfill (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Compatibility)
First for each element check if (typeof element== "number") and then check this to find min JavaScript: min & max Array values?
You can apply reduce function on the array to find min and max as followed.
min = array.reduce(function(x,y){if (typeof y === 'number' && (y<x)) return y; return x;}, Infinity)
max = array.reduce(function(x,y){if (typeof y === 'number' && (y>x)) return y; return x;}, -Infinity)
If there is no number in the array, min will contain Infinity and max will contain -Infinity
function minOfArray(array) {
return Math.min.apply(this, array.filter(function (a) { return !isNaN(a); }));
}
function maxOfArray(array) {
return Math.max.apply(this, array.filter(function (a) { return !isNaN(a); }));
}
Its actually really simple.
Just drop this inside of a loop:
Math.min(x, y);
Cycle through all of the elements and keep a variable lowest to hold the one that is lowest. Once all of the elements have been compared your lowest number will be held by the variable.
To determine if it is a number:
isFinite(String(foo).trim() || NaN)
Finally, look up "linear search" if going about this process confuses you.
Linear Search: http://en.wikipedia.org/wiki/Linear_search

Categories

Resources