Code Monkey home page Code Monkey logo

es6-shim's Introduction

ES6 Shim Version Badge

Provides compatibility shims so that legacy JavaScript engines behave as closely as possible to ECMAScript 6 (Harmony).

github actions coverage License Downloads

npm badge

HTML version of the final ECMAScript 6 spec

Installation

If you want to use it in browser:

  • Just include es6-shim before your scripts.
  • Include es5-shim especially if your browser doesn't support ECMAScript 5 - but every JS engine requires the es5-shim to correct broken implementations, so it's strongly recommended to always include it. Additionally, es5-shim should be loaded before es6-shim.

For node.js, io.js, or any npm-managed workflow (this is the recommended method):

npm install es6-shim

Alternative methods:

  • component install paulmillr/es6-shim if you’re using component(1).
  • bower install es6-shim if you’re using Bower.

In both browser and node you may also want to include unorm; see the String.prototype.normalize section for details.

Safe shims

Math functions’ accuracy is 1e-11.

  • Reflect

  • Symbol (only if it already exists)

    • match (and corresponding String#match, String#startsWith, String#endsWith, String#includes, RegExp support)
    • replace (and corresponding String#replace support)
    • search (and corresponding String#search support)
    • split (and corresponding String#split support)

Well-known symbols will only be provided if the engine already has Symbol support.

  • String.prototype Annex B HTML methods (a standalone shim is also available)
    • anchor()
    • big()
    • blink()
    • bold()
    • fixed()
    • fontcolor()
    • fontsize()
    • italics()
    • link()
    • small()
    • strike()
    • sub()
    • sup()

These methods are part of "Annex B", which means that although they are a defacto standard, you shouldn't use them. None the less, the es6-shim provides them and normalizes their behavior across browsers.

Subclassing

The Map, Set, and Promise implementations are subclassable. You should use the following pattern to create a subclass in ES5 which will continue to work in ES6:

require('es6-shim');

function MyPromise(exec) {
  var promise = new Promise(exec);
  Object.setPrototypeOf(promise, MyPromise.prototype);
  // ...
  return promise;
}
Object.setPrototypeOf(MyPromise, Promise);
MyPromise.prototype = Object.create(Promise.prototype, {
  constructor: { value: MyPromise }
});

String.prototype.normalize

Including a proper shim for String.prototype.normalize would increase the size of this library by a factor of more than 4. So instead we recommend that you install the unorm package alongside es6-shim if you need String.prototype.normalize. See #134 for more discussion.

WeakMap shim

It is not possible to implement WeakMap in pure javascript. The es6-collections implementation doesn't hold values strongly, which is critical for the collection. es6-shim decided to not include an incorrect shim.

WeakMap has very unusual use-cases, so you probably won't need it at all (use simple Map instead).

Getting started

require('es6-shim');
var assert = require('assert');

assert.equal(true, 'abc'.startsWith('a'));
assert.equal(false, 'abc'.endsWith('a'));
assert.equal(true, 'john alice'.includes('john'));
assert.equal('123'.repeat(2), '123123');

assert.equal(false, NaN === NaN);
assert.equal(true, Object.is(NaN, NaN));
assert.equal(true, -0 === 0);
assert.equal(false, Object.is(-0, 0));

var result = Object.assign({ a: 1 }, { b: 2 });
assert.deepEqual(result, { a: 1, b: 2 });

assert.equal(true, isNaN('a'));
assert.equal(false, Number.isNaN('a'));
assert.equal(true, Number.isNaN(NaN));

assert.equal(true, isFinite('123'));
assert.equal(false, Number.isFinite('123'));
assert.equal(false, Number.isFinite(Infinity));

// Tests if value is a number, finite,
// >= -9007199254740992 && <= 9007199254740992 and floor(value) === value
assert.equal(false, Number.isInteger(2.4));

assert.equal(1, Math.sign(400));
assert.equal(0, Math.sign(0));
assert.equal(-1, Math.sign(-400));

var found = [5, 10, 15, 10].find(function (item) { return item / 2 === 5; });
assert.equal(10, found);

var foundIndex = [5, 10, 15, 10].findIndex(function (item) { return item / 2 === 5; });
assert.equal(1, foundIndex);

// Replacement for `{}` key-value storage.
// Keys can be anything.
var map = new Map([['Bob', 42], ['Foo', 'bar']]);
map.set('John', 25);
map.set('Alice', 400);
map.set(['meh'], 555);
assert.equal(undefined, map.get(['meh'])); // undefined because you need to use exactly the same object.
map.delete('Alice');
map.keys();
map.values();
assert.equal(4, map.size);

// Useful for storing unique items.
var set = new Set([0, 1]);
set.add(2);
set.add(5);
assert.equal(true, set.has(0));
assert.equal(true, set.has(1));
assert.equal(true, set.has(2));
assert.equal(false, set.has(4));
assert.equal(true, set.has(5));
set.delete(5);
assert.equal(false, set.has(5));

// Promises, see
// http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript
// https://github.com/petkaantonov/bluebird/#what-are-promises-and-why-should-i-use-them
Promise.resolve(5).then(function (value) {
  assert.equal(value, 5);
  if (value) throw new Error('whoops!');
  // do some stuff
  return anotherPromise();
}).catch(function (e) {
  assert.equal(e.message, 'whoops!');
  assert.equal(true, e instanceof Error);
  // any errors thrown asynchronously end up here
});

Caveats

  • Object.setPrototypeOf / Reflect.setPrototypeOf
    • Note that null objects (Object.create(null), eg, an object with null as its [[Prototype]]) can not have their [[Prototype]] changed except via a native Object.setPrototypeOf.
  • Well-known Symbols
    • In order to make them work cross-realm, these are created with the global Symbol registry via Symbol.for. This does not violate the spec, but it does mean that Symbol.for('Symbol.search') === Symbol.search will be true, which it would not by default in a fresh compliant realm.

The project was initially based on es6-shim by Axel Rauschmayer.

es6-shim's People

Contributors

benjoffe avatar cscott avatar daniel-hug avatar david-risney avatar dekajp avatar dylanlukes avatar flyyang avatar forbeslindesay avatar gnh1201 avatar hemanth avatar kvantetore avatar ljharb avatar mathiasbynens avatar mikemcelroy avatar ndhoule avatar ngsankha avatar nowaker avatar nuxodin avatar orald avatar outcoldman avatar paulmillr avatar pkozlowski-opensource avatar prayagverma avatar readmecritic avatar rwaldron avatar smikes avatar subzey avatar victorystick avatar xotic750 avatar yaffle 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  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

es6-shim's Issues

Providing a minified version

Is it possible to provide a minified version as well, that way I can just bower to install the minified version.

Node.js --harmony implementation differs from es6-shim implementation

The Node.js implementation in harmony mode of Map and Set offers no way to iterate over the items (at current stage, 0.8.15) so if I accidentally use it with the es6-shim enabled it will break if I run the same code in --harmony mode.

This difference just made my life more difficult, I think it would help other devs too if it was made sure to not occur.

WeakMap as es6-sham?

Would you take a patch to add imperfectly shimmable features (a la WeakMap) in an es6-sham.js module? This is how Kris Kowal's refactored es5-shim and it makes a lot of sense. I understand why you don't want it in es6-shim proper but WeakMap is very shimmable regardless.

String#startsWith/endsWith can be improved

current:

    startsWith: function(substring) {
      return this.indexOf(substring) === 0;
    },

    endsWith: function(substring) {
      var substr = String(substring);
      var index = this.lastIndexOf(substr)
      return index >= 0 && index === this.length - substr.length;
    },

suggestion:

    startsWith: function(substring) {
      return this.lastIndexOf(substring, 0) === 0;
    },

    endsWith: function(substring) {
      substring = String(substring);
      var d = this.length - substring.length;
      return d >= 0 && this.indexOf(substring, d) === d;
    },

text/Index.html

Browsing the code of test/index.html

saw these links -
script src="../node_modules/mocha/mocha.js"
script src="../node_modules/chai/chai.js"
script src="../node_modules/es5-shim/es5-shim.min.js"
script src="../es6-shim.js"

but Node_modules are not there in main source folder ? Not sure if this is a problem ?

Incompatible with IE 9

According to testling, es6-shim isn't working on IE 9. The es5-shim works there, so in theory we should work on IE 9, too.

Firefox 24 implements Map, but misses forEach on the prototype

Despite loading the ES6 shim, FF's Map prototype is not aligned with the shim's Map prototype--at the very least, it's missing forEach.

es6 shim's defineProperties method looks correct to me, but I have not had time to properly debug it or even determine if that is the actual problem.

Adapt V8 collection tests

This should be adapted & rewritten for es6-shim.

Also it doesn't seem to test weak map gc properly. I don't know how to do this automatically.

Number.MIN_VALUE on iPad (iOS 6)

seems,
denormalized number are not supported on iPad, so
and Number.MIN_VALUE is buggy ( === 0)

because of this, many tests from #85 fails on iPad

according to ES6 (not ES5!) spec, http://people.mozilla.org/~jorendorff/es6-draft.html#sec-15.7.3.3

In the IEEE-764 double precision binary representation, the smallest possible value is a denormalized number. If an implementation does not support denormalized values, the value of Number.MIN_VALUE must be the smallest non-zero positive value that can actually be represented by the implementation.

so, can you shim Number.MIN_VALUE ?
seems, not, because it is not configurable...

but other value should be used for tests:

var MIN_VALUE = Number.MIN_VALUE === 0 ? 2.2250738585072014e-308 : Number.MIN_VALUE; // smallest normalized value

Custom builds

Would be really nice to have lodash-like custom builds, I guess. Some people need only 1-3 functions from here.

Map.prototype.keys is not a function

According to the EcmaScript6 draft specification (as well as examples on various random websites), Map.prototype.keys is a function that takes no arguments and returns an array; when using this "shim" keys is instead a field of a map that directly stores the array. The result means that coding against this shim will not actually be compatible with an official implementation of Map.

Doesn't work in ES3

Object.defineProperty isn't shimmable in ES3, which makes the entire ES6 shim only usable in an ES5 environment.

Any shimmable parts of ES6 that do not rely on unshimmable parts of ES5 should use ES3-compatible syntax, to maximize its browser compatibility. If there are shimmable parts of ES6 that require a true ES5 environment, ideally those would be in a separate component/file.

Map

NOTE Each key is visited only once with the value that is current at the time of the visit. If the value associated with a
key is modified after it has been visited, it is not re-visited. Keys that are deleted after the call to forEach begins and
before being visited are not visited. New keys added, after the call to forEach begins are visited.

fails on Internet Explorer 8

Shim doesn't work on my Internet Explorer 8 - 8.0.6001.18702IS on Windows XP.
The error message translated into English would be "Object doesn't have such property or method".
Looks like Object.keys is undefined here.

>>Object.keys
undefined

es6-shim

I'm using the latest version, directly from master.

Let me know if you need more information. I'll be happy to provide it.

Math.expm1

test cases:

Math.expm1(-38) should be -1,
current result is -183115516321770.7

Math.expm1(709) should be near 8.218407461554972e+307,
current result is 8.484265749165578e+76

Array.of() is incorrectly implemented.

The implementation given is actually a casual version of Array.from and the tests you wrote are also incorrectly testing Array.of as though it were Array.from

Example of correct behaviour:

Array.of( 1, 2, 3 );
//  [ 1, 2, 3 ];

There are tests that assert:

Array.of( arguments ) === [];

... which is incorrect. That would be correct for Array.from( arguments ); Array.of( arguments ) should actually return [ arguments ];

Tests failing on Firefox

The following assertions for Map fail in Firefox:

expect(map.keys).to.be.an.instanceof(Function);
expect(map.values).to.be.an.instanceof(Function);

map.keys/map.values appear to be undefined

The following assertion for Set fails in Firefox:

expect(set.size).to.equal(2);

set.size appears to be a function rather than a number.

P.S. this is the cause of the red cross in #32

Tests don't work in cloud due to global expect

I think that worrying about index.html for tests is a problem. It forces, in particular, relying on a global "expect" to be set (that test_helpers sets for command-line). It makes testling tests fail, and I can only assume jepso tests as well.

I think that it would be better to eliminate the HTML entirely, or at least, use browserify to output all the JS for the html file (and store it in the repo if necessary). That way, the tests could be tweaked to only work in a node environment, but the html file would still be usable if someone wanted it (although I'm not sure why they would).

Thoughts?

Add more stuff

  • Object.assign
  • Object.mixin
  • Array.from mapfn arg
  • Array#find
  • Array#findIndex
  • String#normalize
  • String#raw
  • String.fromCodePoint tests
  • String#codePointAt tests
  • Array#keys, Array#values, Array#entries

Math.log10

Math.log10(1e15) is 14.999999999999996 in Chrome 19

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.