Paul Miller’s es6-shim gives you functionality that will be in ECMAScript 6 (code-named ECMAScript.next), on ECMAScript 5 engines. It was initially based on a project of mine, but adds much new functionality, Node.js compatibility, and (not least) tests.
Highlights
The following are a few highlights. Take a look at the tests to get more usage examples.- Strings
> "hello world".startsWith("hello") true > "hi".repeat(3) 'hihihi' - Object.getOwnPropertyDescriptors() – makes Object.create() more useful.
var copy = Object.create(Object.getPrototypeOf(orig), Object.getOwnPropertyDescriptors(orig)); var newFoo = Object.create(FooProto, Object.getOwnPropertyDescriptors({ instanceProp1: 123, instanceProp2: "abc" })); - Object.is() – an improved version of === (which will likely become an operator called is in ECMAScript 6).
> 0 === -0 true > Object.is(0, -0) false > NaN === NaN false > Object.is(NaN, NaN) true - Map – gives you a dictionary with arbitrary keys.
> var m = new Map(); undefined > m.set("1", "foo"); undefined > m.set(1, "bar"); undefined > m.get("1") 'foo' > m.get(1) 'bar'"1" and 1 are (coerced to) the same key with arrays. Note that each object is considered different from any other object. Hence, the following map entry cannot be easily retrieved:> m.set({}, "hello"); > m.get({}) // new object! undefined
Installation
You can either load es6-shim.js as a script in a browser or install it via npm on Node.js (requires at least version 0.6.5):
npm install es6-shim
Afterwards, you enable it in your project like this:
require("es6-shim");
And you can play with it on the Node.js REPL, with the option of enabling it by default [2].
Related posts
- ECMAScript.next: the “TXJS” update by Eich [what will be in ECMAScript 6, code-named ECMAScript.next]
- Execute code each time the Node.js REPL starts
4 comments:
The Map impl uses a linear search !?
yep, it does. I plan to make some optimizations, though.
Basically, js arrays / objects are hash maps themselves, so even if the "true" hash map would be implemented, it wouldn't be much more faster.
?Yes, so js array/object properties are faster than O(N), probably O(Log(N)) or O(1).
So an implementation on top of it can be faster than a linear search too.For non-string keys, maybe one problem is that it is not possible to have in JS something like java System.identityHashCode() to make a map based on object instance comparison (=== on keys), for any kind of object.(A trick that I have seen somewhere is to "inject" a generated UID in key instances.)
Post a Comment