timoxley / functional-javascript-workshop

A functional javascript workshop. No libraries required (i.e. no underscore), just ES5.
2.05k stars 438 forks source link

Exercise 8: Why slice? #150

Closed felixsanz closed 9 months ago

felixsanz commented 8 years ago

The solution implementation says:

function duckCount() {
  return Array.prototype.slice.call(arguments).filter(function(obj) {
    return Object.prototype.hasOwnProperty.call(obj, 'quack')
  }).length
}

But this is also valid:

function duckCount() {
  return Array.prototype.filter.call(arguments, function(item) {
    return Object.prototype.hasOwnProperty.call(item, 'quack')
  }).length
}

So... why using slice.call()? If you are already using .filter, why use another thing too? (which is also irrelevant)

CrossEye commented 8 years ago

That's a good idea.

I think there are many people who never consider operating directly on arguments without turning it immediately into an array, simply because it's often tricky to do so. Hence anything that works with arguments automatically starts with that Array.prototype.slice.call incantation.

But as you demonstrate, it's not necessary. Your solution is cleaner and more elegant.

shrynx commented 8 years ago

@felixsanz @CrossEye Even i found the slice bit weird (though obviously this solution is correct too). I implemented it with reduce.

function duckCount() {
    return Array.prototype.reduce.call(arguments,function(count, curr){
        return count + +(Object.prototype.hasOwnProperty.call(curr,'quack'))
    },0)
}