Giter Site home page Giter Site logo

es6-collections's Introduction

ES6 Harmony Collections build status

browser support

Deprecated

This is a very old polyfill which served old browser decently for the last 4+ years. I am not actively maintaining this project but I would eventually accept PRs if you really need to use it.

Please have a look at better alternatives such ES-Shims


The aim of this repository is to provide an unobtrusive, performances oriented shim for ES6 collections such WeakMap, Map, and Set.

These global functions are already available in Firefox Nightly and Chrome Dev channel through Enable Experimental JavaScript in chrome://flags/ section.

Features

  • compatible with all browsers and both node.js (npm install es6-collections) and Rhino
  • 100% unobtrusive with any environment. If implemented in node V8 it exports native constructors rather than shims
  • size and performances oriented polyfill. It does not matter if the WeakMap is not perfect, it's just fast and not much more memory leaks prone than other shims. If you don't rely on magic, simply remember to weakmap.delete(referedObject) when referedObject is not needed anymore.
  • for browsers, it fits in less than 1Kb once minzipped ... the smallest shim out there so far
  • 100% of code coverage
  • completely private shared behavior in order to easily maintain and update three collections at once

New On Version 0.3.0

  • API updated to the MDN docs
  • tests are replaced with mocha and testling, which gets testling table and better testing possibilities
  • polyfills for old browsers moved out to autopolyfiller
  • used prototypical shared methods approach since it demonstrates times better results - test on jsperf

New On Version 0.2.0

  • removed both keys and values properties since these are not in specs anymore
  • improved checks in order to do not fail with NaN or -0 and +0 as specified via specs
  • native Array.prototype.indexOf used when key/value to retrieve is not NaN or -0 and +0 (performances regardless checks)
  • updated tests including all methods behaviors plus (Map|Set)#size() test for Mozilla only

The WeakMap Is Not Weak ... And Why

  • first of all, ES6 Collections is not about WeakMap only ... most likely is about Map ... anyway ...
  • O(n) against O(1) to link keyObject and value is a no-go for different reasons:
    • the random property attached to the object will be easily discoverable via for/in loop in all non ES5 capable engines, obtrusive
    • even in ES5 capable browser, to make the random property not discoverable we need to wrap native Object.defineProperty, Object.defineProperties, Object.create, Object.getOwnPropertyNames, plus eventually Proxy, which means the whole application will be O(n) times slower for everything, not Map or WeakMap only
    • there are situations where a random property cannot be attached, as example in Internet Explorer some object exposed in JavaScript may not accept runtime attached properties. The purpose of this shim is to be as cross platform as possible and as safe as possible while others polyfills are able to break, just as example, objects defined via VB Classes
  • it's simply not possible to create 100% WeakMap in ES5 only, the aim of this polyfill is to bring a 1:1 unobtrusive and reliable API rather than 1:1 implementation
  • if you think WeakMap, never existed until now, is the only thing you need, you may consider the first proposed alternative and simply walk away from this page
  • a polyfill aim is to bring a reliable API until the browser supports it and you can simply remove the polyfill dependency. The perfect implementation may be unnecessary, in this case obtrusive, or simply YAGNI

Alternatives

  • the bigger and rich in dependencies WeakMap shim from Mark S. Miller, the best attempt to avoid undesired memory leaks. Bear in mind some leak is still possible plus Object natives are wrapped plus it brings WeakMap only
  • the unfortunately and so far slower and heavier, memory usage speaking, alternative from Benvie Harmony Collections Shim
  • differently implemented Map and Set (no WeakMap) from Paul Millr, together with few others ES6 prototypes
  • another attempt based on valueOf to avoid IE enumerability, still problematic with unknown objects but less leaks prone from Gozala

Tests

Just type $ mocha or $ npm test from the project’s folder in terminal.

Build

$ npm build to build browser version of bundle.

License

es6-collections and the rest of the project is under Mit Style License

Copyright (C) 2011 by Andrea Giammarchi, @WebReflection

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

es6-collections's People

Contributors

afandria avatar blakmatrix avatar dy avatar infinity0 avatar kyo-ago avatar louisremi avatar mattdsteele avatar mdvorscak avatar tomecko avatar webreflection avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

es6-collections's Issues

Map not working with NaN keys

Try this on IE10:

var map = new Map();
map.set('d', 2);
map.set('e', 3);
map.set('f', 4);
map.set(NaN, 'Not number');    // overwrites f => 4
console.log(map.get('f'));          // outputs: 'Not number'

It seems that NaN key will overwrite the last key on the list, because set() thinks that NaN is in the list.

Related:

var map = new Map();
map.set('a', 1);
console.log(map.has(NaN));    // outputs: true

Add git tags

Releases should not only be pushed to npm but also be tagged accordingly.

Error in IE11

Including the polyfill in IE11 throws an error:

if (typeof Map == 'undefined' || !(new Map).values().next) //Object doesn't support property or method values

The same issue occurs with Set.

ie11 collection polyfill error

Map.clear() bug.

_keys variable is not initialized after running clear method .

var m = new Map();
m.set("a", 1);
m.set("b", 2);
m.clear();
//{_itp: Array[0], _keys: Array[2], _values: Array[0], objectOnly: undefined, size: 0}

size is a property not a function

According to MDN, size is a property not a function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set (same for Map, etc)

es6-shim implements this correctly, but es6-collections does not:

> require("es6-collections");
{}
> var a = new Set([1,2,3]);
undefined
> a.size
[Function: sharedSize]
> a.size()
3
> require("es6-shim");
{}
> var a = new Set([1,2,3]);
undefined
> a.size()
TypeError: Property 'size' of object #<Set> is not a function
    at repl:1:4
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)
> a.size
3

Browser support

Hi,

Just wondering what versions of Internet Explorer this library supports.

Thanks

shim es6-collections on IE11

IE11 has map/set, but they are pretty crippled (set/add don't return the map/set, the constructor does nothing when you pass an iterable, etc).

I would like to simply replace the build-in versions in IE11 by this ones. Maybe you can run a feature check (ex: if Set exists, do an .add over it and check that method returns the same Set. Also, pass an array with one value on the ctor and check that that value is indeed on the Set).

use of non standard properties in the test unit, versus `Array.from()`

from an es6 point of view, the following line is not correct as _values is a private property
https://github.com/WebReflection/es6-collections/blob/master/test/index.js#L284

So instead of doing

assert(JSON.stringify(o._values) === JSON.stringify([1, 3, 0]));

it should rather use Array.from (es6, so requires a polyfill on some browser), that allows to create a new Array instance from an array-like or iterable object. :

assert(JSON.stringify(Array.from(o.values())) === JSON.stringify([1, 3, 0]));

but then, the problem then is that Array.from does not work with the "fake" operator returned by o.values().

any chance you could look at it ?

Partial browser support prevents the polyfill

Chrome 36 implements WeakMap, but not Map or Set. The entire polyfill doesn't run because of the initial check: "WeakMap" in this which passes.

Suggest simply changing the initial check to:

"WeakMap" in this && "Set" in this && "Map" in this || ...

Everything else should work, as you're already checking ... = window.Map || Map during assignment.

Memory leaks

There’s described exactly the way by which current es6-collections are implemented: MDN weakmap. It points that if object is being removed, weak map keeps reference on it, and that causes leaks.
I think that maybe it’s reasonable to use obtrusive polymer-weakmap approach instead.

keys and values are still in specs

I have just checked draft from 18th of July and these two are still in there, so why you have removed them ?

23.1.3.8 Map.prototype.keys ( )
The following steps are taken:
1.  Let M  be the  this  value.
2.  Return the result of calling the CreateMapIterator abstract operation with arguments  M  and "key".

23.1.3.11 Map.prototype.values ( ) 
The following steps are taken:
1.  Let M  be the  this  value.
2.  Return the result of calling the CreateMapIterator abstract operation with arguments  M  and "value".

Various issues with using Object.is

Unfortunately, Object.is doesn't exist on PhantomJS nor IE or Safari, leading to runtime errors:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Browser_compatibility

It's also not correct according to the semantics of ES6 collections:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality
vs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description

It would be better to define a function like:

is = function(a,b) { return isNaN(a)? isNaN(b): a === b; }

es6-collections implementation should be used in Safari 7.1/8

Safari 7.1 and 8 have native support for Set and Map, so es6-collections isn't used in those browsers. The Safari implementation, however, is seriously crippled because the Iterator returned by the keys, values and entries functions does not support next(). Because these are common functions, the native implementation can not be used reliably:

m = new Map();
m.set(1, "test");
m.set("2", false);
it = m.values(); // returns Map Iterator
it.next(); // TypeError: undefined is not a function

In this case, the es6-collections implementation should be used over the native one, or at least the option to force it should be present.

Key equality

other point we identified that is different from the latest es6 spec, is that Map#set expects 0 and -0 keys to be unique, which was only valid in an earlier version of the standard

@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality

In earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26) (bug 952870) and a recent nightly Chrome.

WeakSet support?

As far there's no WeakSet in the build.
I hoped to polyfill it in lifecycle-events, but found with surprise that it's not covered.
I had to read docs more carefully, but still ).

For now I use stupid workaround:

var WeakSet = typeof WeakSet === 'undefined' ? Set : WeakSet;

Use Object.defineProperties for WeakMap?

WeakMap is not completely polyfillable but its core feature is that data can be garbage collected once an object is collected. Implementing this feature should be possible by using a non-enumerable rare key (e.g. a random large string) to which UID of a specific WeakMap would be appended.

Am I missing sth?

Not working in IE11/10/9 with aurelia

Hi,

I'm not sure if this is the right place, but here goes..

I'm running Aurelia beta 1 and have added

github:webreflection/es6-collections@master and github:polymer/mutationobservers.
also added script references in index.html..

But when I run i IE, I get several errors ..

Out of stack space
Evaluating http://localhost/Webfragt2.Webclient/jspm_packages/npm/[email protected]/modules/es6.map.js

Potentially unhandled rejection [2] Error: Expected object
Error loading http://localhost/Webfragt2.Webclient/jspm_packages/npm/[email protected]/modules/es6.map.js
Unhandled promise rejection Error: Out of stack space
Error loading http://localhost/Webfragt2.Webclient/jspm_packages/npm/[email protected]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.