Added '_.ensureArray' function #816

Closed
wants to merge 1 commit into
from

Conversation

Projects
None yet
3 participants
@krawaller

This pull request adds a _.ensureArray utility function, which we frequently found ourselves mixin into underscore. As the name implies, it helps when you want to feed a perhaps-array value into an API that expects an array:

// arrays are passed straight through
_.ensureArray([1,2,3]); // => [1,2,3]

// non-array truthy values are wrapped in an array
_.ensureArray({a:1,b:2}); // => [{a:1,b:2}]
_.ensureArray("foo"); // => ["foo"]
_.ensureArray(432); // => [432]

// falsy values result in an empty array
_.ensureArray(null); // => []

Semantically we are perhaps treading a bit too far into the land of _.toArray here, but the functions behave very differently since toArray always treats the argument as a collection. For the above use cases, here is what toArray returns:

_.toArray([1,2,3]); // => cloned array [1,2,3]
_.toArray({a:1,b:2}); // => [1,2]
_.toArray("foo"); // => ["f","o","o"]
_.toArray(432); // => []

Only for falsy values do the two functions act the same.

@michaelficarra

This comment has been minimized.

Show comment
Hide comment
@michaelficarra

michaelficarra Oct 7, 2012

Collaborator

[].concat(X) is shorter and doesn't require underscore.

Collaborator

michaelficarra commented Oct 7, 2012

[].concat(X) is shorter and doesn't require underscore.

@krawaller

This comment has been minimized.

Show comment
Hide comment
@krawaller

krawaller Oct 7, 2012

[].concat(x) comes frustratingly close to solve the use case, but since [].concat(undefinedvar) === [undefined] it isn't usable. If the value is undefined we don't want to make the concatenation, and thus we have to do the code branching that _.ensureArray sets out to eliminate.

[].concat(x) comes frustratingly close to solve the use case, but since [].concat(undefinedvar) === [undefined] it isn't usable. If the value is undefined we don't want to make the concatenation, and thus we have to do the code branching that _.ensureArray sets out to eliminate.

@jashkenas

This comment has been minimized.

Show comment
Hide comment
@jashkenas

jashkenas Oct 20, 2012

Owner

Interesting, but way too special-case for Underscore. There are many situations where an API expects a particular type of object (that may or may not be coerceable from your input) ... and Arrays aren't the only type in town.

Owner

jashkenas commented Oct 20, 2012

Interesting, but way too special-case for Underscore. There are many situations where an API expects a particular type of object (that may or may not be coerceable from your input) ... and Arrays aren't the only type in town.

@jashkenas jashkenas closed this Oct 20, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment