Skip to content

Added '_.ensureArray' function - #816

Closed
krawaller wants to merge 1 commit into
jashkenas:masterfrom
krawaller:master
Closed

Added '_.ensureArray' function#816
krawaller wants to merge 1 commit into
jashkenas:masterfrom
krawaller:master

Conversation

@krawaller

Copy link
Copy Markdown

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

Copy link
Copy Markdown
Collaborator

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

@krawaller

Copy link
Copy Markdown
Author

[].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

Copy link
Copy Markdown
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.

@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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants