mathiasbynens / array.from Goto Github PK
View Code? Open in Web Editor NEWA robust & optimized ES3-compatible polyfill for the `Array.from` method in ECMAScript 6.
Home Page: https://mths.be/array-from
License: MIT License
A robust & optimized ES3-compatible polyfill for the `Array.from` method in ECMAScript 6.
Home Page: https://mths.be/array-from
License: MIT License
I have incorporated this polyfill into the FT polyfill service, because you have some good tests and it gave me a good example to try and build a test framework around for all our polyfills. But having ported your tests to mocha/expect, they are failing in IE6-8. The whole suite passes in Chrome, Firefox and Safari.
You can run the tests in a browser here (ideally use IE 6, 7 and 8 - I'm running them using the modern.ie VMs):
http://ft-polyfill-service-qa.herokuapp.com/v1/test/tests?feature=Array.from
So my question is: is your polyfill incomplete in IE < 9, or have I made a mistake in porting the tests (or in the test framework, I suppose)?
In your documentation, I find the following info :
In a browser:
Via npm:
npm install array.fromExample
var from = require('array.from'); var assert = require('assert'); assert.deepEqual(from('abc'), ['a', 'b', 'c']);...
I find this confusing.
Are you saying I can only use your polyfill in an environment with support for CommonJS style modules?
What about projects that don't use modular JavaScript or projects that use AMD modules?
Basically, how can I include your polyfill in projects that don't use a Node.js / NPM based build process?
It would be great to have @rwaldron review this, as he’s been championing both Array.from
and Array.of
(plus he wrote the spec proposal). Rick, are you up for it?
Array.from
: http://mths.be/array-fromArray.of
: http://mths.be/array-ofIn particular, I’m wondering:
I installed and import 'array.from';
but
Object doesn't support property or method 'from'
error.
can you make this code work well, array.from works well in my new version chrome, but lower version browser can't support array.from, the shim should support it
var m = new Map();
m.set('strKey1',"strValue1");
m.set('strKey2',"strValue2");
m.set(function(){},"funcValue1");
m.set(function(){console.log("funcKey2")}, function(){console.log("funcValue2")});
console.log("The result is: ", Array.from(m.keys()));
console.log("The result is: ", Array.from(m.values()));
import arrayFrom from 'array.from';
arrayFrom(FileList) instanceof Array; // false
Array.from(FileList) instanceof Array; // true
I tried to implement it, but adding a switch
for FileList
increases the cyclomatic complexity of the from
function beyond 12. There's also no easy way of mocking FileList
for the tests, as your tests don't have jsdom
integrated, and I'm quite sure jsdom
doesn't support FileList
anyway.
We could use something like Karma, but adding that just for a FileList
test seems a little overkill.
Ideas?
We need a version bump, a new git tag, and a publish to npm :-) Perhaps to v1.0.0
, so semver has meaning?
Hey,
I don't see this case in the spec (https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from). It seems like ArrayCreate(len) (Step 14a in Array.from
) should throw a RangeError
(as it will fail the assertion) on values less than 0. (This is the behaviour seen in Firefox 32 where this is implemented natively).
Am I right in thinking this and that this test should test whether a RangeError is thrown on negative lengths?
Sam
I'm not sure how you were testing in Safari after those PRs, but things were decidedly not passing - they are now, at least.
With the latest changes - your PRs and my later tweaks/fixes - everything passes in all versions of Safari, as well as latest Chrome. However, the iterator tests do not pass in Firefox.
We can't release with these changes until all versions of Safari, Firefox, Chrome, IE, and Edge pass all tests.
The way I test is npm install -g testling
and testling -u
- then running that URL in the relevant browser. Let's get this figured out!
isConstructor
should not execute the constructor function, but that can't be fixed without ES6 Proxies. 😞in
operator needs to be used. Test case:Array.from({__proto__: {0: "abc", length: 1}})[0] === "abc";
Object.defineProperty()
to avoid executing setters. Test case:Object.defineProperty(Array.prototype, "0", {
set: function(x) { throw "set:" + x }
});
Array.from({length: 1, 0: "abc"}); // should not throw
A.length = len
requires strict-mode semantics. Test case:Array.from.call(function(){ return Object.freeze({}); }, {}); // should throw
The latest code in master
, mathiasbynens/Array.from#dc211b013ffe2e0877e4e4ea05cd652e8b7e4943
fails to run in Karma driving PhantomJS or Chrome (scripts processed through karma-webpack
).
The latest release [email protected]
(doesn't rely on system.global
) works just fine.
Here is a barebones project that demonstrates the issue, https://github.com/MadLittleMods/system-global-phantomjs-test
npm run karma
> [email protected] karma C:\Users\MLM\Libraries\Code\javascript\system-global-phantomjs-test
> karma start karma.config.js --single-run
(node:16968) DeprecationWarning: loaderUtils.parseQuery() received a non-string value which can be problematic, see https://github.com/webpack/loader-utils/issues/56
parseQuery() will be replaced with getOptions() in the next major version of loader-utils.
21 02 2017 01:20:56.576:INFO [karma]: Karma v1.5.0 server started at http://0.0.0.0:9876/
21 02 2017 01:20:56.578:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
21 02 2017 01:20:56.624:INFO [launcher]: Starting browser PhantomJS
21 02 2017 01:20:59.527:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket A_2Jk42DEvtvVrOYAAAA with id 14696421
PhantomJS 2.1.1 (Windows 8 0.0.0) ERROR
SyntaxError: Unexpected token '.'
at webpack:///~/array.from/~/system.global/shim.js:22:0 <- src/entry2.js:9629
The sourcemap line numbers appear to be a bit off and looking at node_modules\system.global\shim.js
(22 lines total) doesn't show anything out of the ordinary.
This doesn't appear to be just a system.global
issue on it's own because using system.global
directly (see entry1.js
in the project), doesn't throw the error.
entry2.js
fails in Karma PhantomJS/Chrome. note: does work just fine in node v6.7.0, node src/entry2.js
A few bugs have been fixed on master since this package was last published to npm, and I ran into one of them today via an upstream dependency. When you get the chance, can you publish a new release to npm?
Using systemjs:
'array.from': 'node_modules/array.from'
In my .ts file:
import 'array.from';
Array.from({...})
Returns this error...
Property 'from' does not exist on type 'ArrayConstructor'.
How to use with 'import' in browser
Latest code (after git clone
and npm install
in the directory)
> require('array.from')
Error: Cannot find module 'is-callable'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/tmp/node_modules/array.from/implementation.js:7:18)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
This line
https://github.com/mathiasbynens/Array.from/blob/master/polyfill.js#L18
seems to run fine on Chrome, thus the Polyfill gets added even though Array.from already exsists as a native implementation...?
Array.from([], undefined);
returns empty array instead of error []
As reported by @medikoo here: 0e41b31#commitcomment-6175170
I'm working on a new library and I need a way to split a string by character into an array, considering Astral symbols. I was expecting this library to work, as it claims to be equivalent to ES6. But, it's not:
https://tonicdev.com/57ac7398a55ecf1200fa1a05/57ac7398a55ecf1200fa1a06
Real Array.from
recognises Astral symbols fine while this library does not. Am I missing something here?
Hi,
I believe this current implementation does not work for ES6 Sets. For example:
Array.from(new Set([1,2])) // returns [] with the shim but [1,2] on my setup with the native Array.from
The source of problem seems to be demonstrated by the following:
a = Object(new Set([1,2]))
a.length // returns undefined
Currently, this polyfill possibly does not work with Symbol.iterator polyfill, and does not work with Symbol.iterator polyfill on legacy Firefox that use @@iterator
. If we want to fix those points, we need the large fix. Can I do that fix?
Thank you for this polyfill. One question: created arrays appear to be read only, as assigning results in "TypeError: Cannot assign to read only property" in strict mode. For example:
'use strict';
var a = Array.from([1, 2, 3]);
a[1] = 7;
Adding a writable:true to the defineProperty descriptor on line 68 solved it for me. Just wondering if this was intentional, or am I missing something?
Tested in Chromium 27, and compared with the native implementation in Firefox 36.
The polyfill splits each unicode character(astral symbol) into their surrogate pairs while the native implementation keeps them intact.
var arrayFrom = require('array.from');
// ["🖐", "🏿"]
const nativeResult = Array.from('🖐🏿');
// ["�", "�", "�", "�"]
const polyfillResult = arrayFrom('🖐🏿');
console.log(nativeResult, polyfillResult);
https://runkit.com/madlittlemods/58aaa693808777001350cf41
Relevant issues,
Array.from({ '0': 1, '2': 2, 'length': 3 })
should not return a sparse arrayDiscussed in http://esdiscuss.org/topic/array-from-and-sparse-arrays.
Array.from([1,,2])
returns a non-sparse array (because it uses the iterator case, see bug 2416), but Array.from({0: 1, 2: 2, length: 3 })
returns a sparse array (because it uses the ‘array-like’ case).
It was suggested that the two cases should be made consistent. Since “holes
are evil”, the array-like case should lose the kPresent
test in step 17b etc.
IsIterable
is not definedIt will be defined in the rev23. Once that happens, #4 can be fixed.
Since these polyfills were initially meant for ES5 and ES3 environments I didn’t implement support for ES6 iterators – any engines that support iterators probably support Array.from
as well, right?
Well, just in case there is one that won’t, it would be nice to support iterators anyway, if only for this use case:
Array.from('foo\uD834\uDF06bar') // assuming ES6 StringIterator support
// [ 'f', 'o', 'o', '\uD834\uDF06', 'b', 'a', 'r' ]
My IE6/7/8 VMs are having an issue at the moment, could only get tests running for IE 9/10/11.
Failing:
Passing:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.