Reputation: 9066
I have some confusion regarding how reduce operation takes place on a string .First a new Str instance is created and sends desired string as a parameter.
Then using split method it splits into an array of string.A reduceIt method takes the array and execute a reduce operation which returns the array element which has height length.
It works fine with a two element array.But if there is more than two elements it returns NAN.
Why it returns NAN for array having more than two elements??
function Str(text){
this.text=text.split('\n');
}
Str.prototype.reduceIt = function() {
return this.text.reduce(function(first,last,index,arr) {
return Math.max(first.length,last.length);
});
};
var t=new Str('i am a boy\n she loves cats\n a goat ate my flower garden ');
console.log(t.reduceIt());
Upvotes: 1
Views: 7389
Reputation: 147403
Some good answers already. :-)
The simple way to fix your problem is to supply an initial value of 0, then compare the returned value with the length of the new string, so:
Str.prototype.reduceIt = function() {
return this.text.reduce(function(first,last,index,arr) {
// Compare current value (first) with length of string
return Math.max(first,last.length);
}, 0); // supply 0 as the initial value
};
It might make things clearer to rename first to maxSoFar and last to currentString.
Upvotes: 2
Reputation: 141829
The first time the callback is called first
is a string (the first element in the array), and your function makes sense when first
and last
are both strings, so it works when the callback is only called once (the array has at most 2 elements).
The second time it is called it is the result of the previous call, a number
. When you call first.length
on a number you get undefined
and when you call Math.max
on that you get NaN
.
If you want to find the length of the longest string in your array, you could use:
Math.max.apply(Math, this.text.map(function (str) { return str.length; }));
Upvotes: 3
Reputation: 66334
Why it returns NAN for array having more than two elements??
Because number.length
is undefined, let's name your function foo
and follow how it's invoked
foo(0, "i am a boy")
gives NaN
foo(NaN, " she loves cats")
gives NaN
foo(NaN, " a goat ate my flower garden ")
gives NaN
Giving a final result of NaN
.
This happens because number.length
is undefined and Math.max(undefined, x)
is NaN
It looks like you wanted to write a function which only takes the length of the second arg
function foo(a, b) {
return Math.max(a, b.length);
}
In this case, you'll get
foo(0, "i am a boy")
gives 10
foo(10, " she loves cats")
gives 15
foo(15, " a goat ate my flower garden ")
gives 29
Giving a final result of 29
.
Upvotes: 1