var _ = {};
This function is very similar to the first function, but instead it returns the last items in an array. For example, if you feed it 5 as an argument, you will get the last 5 items in the array. If 0 is fed to it, then an empty array will be returned.
This is probably the most elegant way to write it:
_.last = function(array, n) {
return n === undefined ? array[array.length -1] : array.slice(Math.max(0,array.length - n));
}
and here's a more simplified way to understand it easier:
_.last = function(array, n){
if ( n === undefined){
return array.length[-1];
}
if (n === 0){
return [];
}
else{
return array.slice(-n);
}
}
The first examples checks to see if n is undefined and if so, returns the length of the array -1. Remember, the .length will return how many items are in the array starting with the number 1, but the index in the array starts with 0. That's why you have to minus 1 to get the index number. If n does not equal undefined then the function will return the value from array.slice, which calls Math.max, which will take the greater of either 0 or array.length -n. You might need to play with this one a bit before you understand exactly how it works, but in a nutshell:
Say this is the array = [1,2,3];
array.length = 3
array[array.length] = will return nothing at all. This is because array.length = 3, and array[3] does not exist. There is an array[0], array[1], and an array[2], but no array[3] in the above array.
However,
array[array.length -1] will equal 3
So,
if you say :
array.slice(array.length -n);
this will appear to work. if n is 1 then you will receive array.slice(array.length -1), which will equal 3. This is because array.length -1 is 2 and 3 is at index 2 in the array. Therefore slice starts with the number 3 and copies everything else after it. Since 3 is the last one in the array, it just return three.
Here's the problem. array.slice(array.length -2) returns 2 and 3.
array.slice(array.length -3) returns 1,2 and 3.
array.slice(array.length -4) returns 3. And this is our problem.
If the n argument fed to _.last is greater than the number of items in the array, the entire array should be returned. However, array.length -4, in this example, = -1, and array.slice(-1) equals 3.
This is why Math.max is used. What's sliced is given two options. If n is bigger than 0, then array.slice(array.length -n ) is used, otherwise, array.slice(0) is used. array.slice(0) will return the entire array.
But I like I said, you'll probably need to play around with that one a bit.
No comments:
Post a Comment