ES6 Array Extras
Correct implementations for Array.of
and Array.from
.
See: Original proposal
Getting Started
Install the package with: npm install es6-array-extras
Documentation
Array.of( ...items )
Array.of
provides a constructor that, unlike Array
, does not have the special case for new Array(42)
, which presets length (and hints to implementations to preallocate) but leaves holes in [0, length ).
One of the main goals of ES6 is to become a better language for library writers and code generators.
For compilation targets, ES/JS can't assume that implementations will always know what its factories are expected to construct:
Imagine the following piece of code is used in a VM (think Dart->JS, LLJS->JS)
var o = { return rest ;} factory variable arity args ;
If factory is Array and only one numeric arg is given, inline like this:
var o = { return rest ;} Array 10 ;
The result of o
will be an array with 10 empty indexes, as if it were called like:
10;// [ , , , , , , , , , , ]
If you replace that by using Array.of()
, you avoid this "gotcha":
Array;// [ 10 ]
Basic usage matches existing Array
constructor:
1 2 3 4 ;// [ 1, 2, 3, 4 ] Array;// [ 1, 2, 3, 4 ]
Array.from( arrayLike )
Converts a single argument that is an array-like object or list (eg. arguments, NodeList, DOMTokenList (used by classList), NamedNodeMap (used by attributes property)) into a new Array() and returns it;
var divs = document;Array;// [ <div class="some classes" data-info="12"></div>, <div data-info="10"></div> ]Array;// <div class="some classes" data-info="12"></div>// <div data-info="10"></div>Array;// [ <div class="some classes" data-info="12"></div> ]Array;// 22Array// ["some", "classes"]
Contributing
All contributions must adhere to the Idiomatic.js Style Guide, by maintaining the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using grunt.
License
Copyright (c) 2012 Rick Waldron Licensed under the MIT license.