ember.js icon indicating copy to clipboard operation
ember.js copied to clipboard

Enumberable reject does not behave as expected.

Open tyre opened this issue 10 years ago • 3 comments

I've made a Twiddle to demonstrate the behaviour of reject.

What is expected: reject returns an array of all the items for which the provided callback did not return a truthy value

What happens: reject returns an array of all of the items for which the provided callback returned a falsey value

This is inconsistent with every implementation of reject I can think of (e.g. Ruby, Underscore.js). While that itself is not a reason to change its behaviour, the behaviour explicitly does the opposite of what it says it does. Rather than rejecting items which pass a test, it keeps ones which fail.

tyre avatar Apr 06 '16 18:04 tyre

reject is supposed to filter from the array all values for which the callback is true. It should give you the inverse result of filter. This is both the specified and actual behavior. I've made a Twiddle which mirrors the example given in the Ruby docs to demonstrate the consistency.

Frankly, I don't like reject because it can be confusing; much in the same way that using Ruby's unless can be confusing. With reject you don't get the values that are "rejected", you get the values that remain after the rejected values are filtered out. I always recommend, for myself included, using filter and simply inverting the predicate. Much easier to reason about in my opinion.

pittst3r avatar Apr 07 '16 11:04 pittst3r

@tyre the docs do explain that reject returns the items where a falsey value is the result of the callback function. http://emberjs.com/api/classes/Ember.Array.html#method_reject

It appears the behavior is doing what the docs describe as well as the implementation and test as linked above by @robbiepitts

Are you suggesting a feature change for reject?

What is expected: reject returns an array of all the items for which the provided callback did not return a truthy value

What happens: reject returns an array of all of the items for which the provided callback returned a falsey value

Expected "callback did not return a truthy value" and Actual "callback returned a falsey value" are the same thing, no?

pixelhandler avatar Apr 08 '16 16:04 pixelhandler

This came out of a RecordArray problem where reject was returning totally unexpected results, but we can't seem to reproduce it, which means it was probably a predicate mistake on our end. This can be closed.

ndemonner avatar Apr 08 '16 16:04 ndemonner