2

I am working on an exercise in learning JavaScript, and cannot figure out why my code is failing a test evaluation. And yes, I realize that I am redundantly (and messily) re-defining Underscore.js _.last. That is the purpose of the exercise.

_.last = function(array, n) {
  if (n === 0) {
    return [];
  }
  else {
    return n === undefined ? array.slice(-1) : array.slice(-n);
  };
}'

These are the results I get when running:

_.last([1,2,3], 2)
[2, 3]
_.last([1,2,3], 5)
[1, 2, 3]
_.last([1,2,3], 0)
[]
_.last([1,2,3])
[3]

The very last call _.last([1,2,3]) is the one failing this evaluation:

expect(_.last([1,2,3])).to.equal(3)

Can anyone tell why this expect is returning false? What am I overlooking

Thank you in advance.

EDIT: solved. else edited to return value if n===undefined rather than returning a single-value array:

return n === undefined ? array[array.length-1] : array.slice(-n);
3
  • So you're expecting it to return 3, but receive an array with the entry 3. i.d. [3]? Commented May 19, 2015 at 18:08
  • 2
    I'm going to assume it's because [ 3 ] !== 3 Commented May 19, 2015 at 18:08
  • Ah, ok, that makes sense. I was actually wondering if that might be the case. Thanks :) Commented May 19, 2015 at 18:12

2 Answers 2

1

Array.prototype.slice returns an array. And if you compare an array and a number, they will be different.

Instead, consider doing the same underscore does:

if (n == null /*|| guard*/) return array[array.length - 1];
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly! I had checked out the underscore docs, and the || guard was throwing me off. Thanks!
Also, you and @taxicala answered too quickly. I can't mark this as solved for another 4 minutes. :P
0

Quoting array.slice description:

The slice() method returns the selected elements in an array, as a new array object.

Basically, your code is ok, and your test is not:

You should change:

expect(_.last([1,2,3])).to.equal(3)

to:

expect(_.last([1,2,3])).to.equal([3])

More info here http://www.w3schools.com/jsref/jsref_slice_array.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.