Skip to content

Commit

Permalink
update castArray implementation to use Array.from, etc
Browse files Browse the repository at this point in the history
Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
  • Loading branch information
boneskull committed Jul 30, 2020
1 parent fcbf503 commit 9df3cb8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
23 changes: 16 additions & 7 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -650,16 +650,25 @@ exports.isBrowser = function isBrowser() {
* Casts `value` to an array; useful for optionally accepting array parameters
*
* It follows these rules, depending on `value`. If `value` is...
* 1. An `Array`: return a copy
* 2. An `arguments` object: coerce to a proper Array and return it
* 3. Any _defined_ value: return a new Array containing the single value
* 4. `undefined`, return an empty Array
* 1. `undefined`: return an empty Array
* 2. `null`: return an array with a single `null` element
* 3. Any other object: return the value of `Array.from()` _if_ the object is iterable
* 4. otherwise: return an array with a single element, `value`
* @param {*} value - Something to cast to an Array
* @returns {*[]}
*/
exports.castArray = function castArray(value) {
if (Array.isArray(value) || type(value) === 'arguments') {
return Array.prototype.slice.call(value);
if (value === undefined) {
return [];
}
if (value === null) {
return [null];
}
if (
typeof value === 'object' &&
typeof value[Symbol.iterator] === 'function'
) {
return Array.from(value);
}
return typeof value !== 'undefined' ? [value] : [];
return [value];
};
6 changes: 6 additions & 0 deletions test/unit/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -784,5 +784,11 @@ describe('lib/utils', function() {
expect(utils.castArray('butts'), 'to equal', ['butts']);
});
});

describe('when provided null', function() {
it('should return an array containing a null value only', function() {
expect(utils.castArray(null), 'to equal', [null]);
});
});
});
});

0 comments on commit 9df3cb8

Please sign in to comment.