项目作者: hemanth

项目描述 :
stage-0 to stage-4 ECMAscript proposals.
高级语言:
项目地址: git://github.com/hemanth/es-next.git
创建时间: 2015-03-09T16:08:48Z
项目社区:https://github.com/hemanth/es-next

开源协议:MIT License

下载


stage-0 to stage-4 ECMAscript proposals.

TOC:

Stage 0:

Defensible Classes

Stage-0

  1. // const class
  2. const class Point {
  3. constructor(x, y) {
  4. public getX() { return x; }
  5. public getY() { return y; }
  6. }
  7. toString() {
  8. return `<${this.getX()}, ${this.getY()}>`;
  9. }
  10. }

Relationships

Stage-0

  1. x @ r // The object x is in the r relationship with what value?
  2. x @ r = y; // Store that x is in the r relationship with value y.

String.prototype.at

Stage-0

  1. 'abc𝌆def'.at(3)
  2. // → '𝌆'

Reflect.isCallable

Stage-0

  1. Reflect.isCallable(argument);

Reflect.isConstructor

Stage-0

  1. Reflect.isConstructor(argument)

Additional metaproperties

Stage-0

  1. function.callee; // function object that is currently being evaluated by the running execution context.
  1. function.count; // number of arguments pass to the function.
  1. function.arguments; // array containing the actual arguments passed to the function.

Function Bind Syntax

Stage-0

  1. // :: which performs this binding and method extraction.
  2. Promise.resolve(123).then(::console.log);

64-Bit Integer Operations

Stage-0

  1. // return the high 32 bit part of the 64 bit addition of (hi0, lo0) and (hi1, lo1)
  2. Math.iaddh(lo0, hi0, lo1, hi1);
  3. // return the high 32 bit part of the 64 bit subtraction of (hi0, lo0) and (hi1, lo1)
  4. Math.isubh(lo0, hi0, lo1, hi1);
  5. // return the high 32 bit part of the signed 64 bit product of the 32 bit numbers a and b
  6. Math.imulh(a, b);
  7. // return the high 32 bit part of the unsigned 64 bit product of the 32 bit numbers a and b
  8. Math.umulh(a, b);

Method Parameter Decorators

Stage-0

//decorators that operate on method and constructor parameters.

  1. class MyComponent {
  2. refresh(@lastRefreshTime timeStamp) { }
  3. }
  4. export function lastRefreshTime(...) {
  5. // at minimum, the arguments of this function should contain:
  6. // - reference to owner of the parameter (the method)
  7. // - parameter index
  8. // - parameter name
  9. // - is parameter a rest parameter?
  10. // store parameter metadata using the same storage mechanism
  11. // as the one used for methods
  12. }

Function Expression Decorators

Stage-0

  1. scheduleForFrequentReexecution(@memoize function(value) {
  2. value++
  3. });
  4. export function memoize(...) {
  5. // at minimum, the arguments of this function should contain:
  6. // - reference to the decorated function expression
  7. // - arguments passed into the memoize function (if any)
  8. // wrap the decorated function expression memoization implementation and return it
  9. }

Zones

Stage-0

  1. //a primitive for context propagation across multiple logically-connected async operations
  2. class Zone {
  3. constructor({ name, parent });
  4. name;
  5. get parent();
  6. fork({ name });
  7. run(callback);
  8. wrap(callback);
  9. static get current();
  10. }
  11. const loadZone = Zone.current.fork({ name: "loading zone" });
  12. window.onload = loadZone.wrap(e => { ... });

Object enumerables

Stage-0

  1. Object.enumerableKeys(obj); // Ordered list of keys.
  1. Object.enumerableValues(obj); // Ordered list of Values.
  1. Object.enumerableEntries(obj); //Ordered list of key value pairs.

Nested import declarations

Stage-0

  1. describe("fancy feature #5", () => {
  2. import { strictEqual } from "assert";
  3. it("should work on the client", () => {
  4. import { check } from "./client.js";
  5. strictEqual(check(), "client ok");
  6. });
  7. it("should work on the client", () => {
  8. import { check } from "./server.js";
  9. strictEqual(check(), "server ok");
  10. });
  11. it("should work on both client and server", () => {
  12. import { check } from "./both.js";
  13. strictEqual(check(), "both ok");
  14. });
  15. });

is{Type} APIs

Stage-0

  1. Builtin.is(Date, vm.runInNewContext('Date')); // false
  2. Builtin.typeOf([]); // 'Array'
  3. Builtin.typeOf(new ArrayBuffer()); // 'ArrayBuffer'
  4. Builtin.typeOf(async function foo() {});
  5. // So on.

Orthogonal Class Member Syntax

Stage-0

  1. //A kitchen sink example
  2. class Foo {
  3. //instance members
  4. own x=0, y=0; // two data properties
  5. own #secret; // a private field
  6. // initial value undefined
  7. own *[Symbol.iterator](){yield this.#secret}
  8. // a generator method
  9. own #callback(){} //a private instance method
  10. //class constructor members
  11. static #p=new Set(), q=Foo.#p;
  12. // a private field and a property
  13. // of the class constructor
  14. static get p(){return Foo.#p} //accessor method
  15. //prototype methods
  16. setCallback(f){this.#callback=f}
  17. constructor(s){
  18. this.#secret = s;
  19. }
  20. }

Pattern Matching Syntax

Stage-0

  1. let getLength = vector => match (vector) {
  2. { x, y, z }: Math.sqrt(x ** 2 + y ** 2 + z ** 2),
  3. { x, y }: Math.sqrt(x ** 2 + y ** 2),
  4. [...]: vector.length,
  5. else: {
  6. throw new Error("Unknown vector type");
  7. }
  8. }

Structured cloning and transfer

Stage-0

  1. StructuredClone(input, transferList, targetRealm)

WHATWG URL

Stage-0

  1. const base = new URL('http://example.org/foo');
  2. const url = new URL('bar', base);

Stage 1:

export v from “mod”; statements

Stage-1

  1. export v, {x, y as w} from "mod";
  2. export v, * as ns from "mod";

Observable

Stage-1

  1. // Observable as a Constructor:
  2. function listen(element, eventName) {
  3. return new Observable(observer => {
  4. // Create an event handler which sends data to the sink
  5. let handler = event => observer.next(event);
  6. // Attach the event handler
  7. element.addEventListener(eventName, handler, true);
  8. // Return a function which will cancel the event stream
  9. return () => {
  10. // Detach the event handler from the element
  11. element.removeEventListener(eventName, handler, true);
  12. };
  13. });
  14. }
  15. // Observable.of creates an Observable of the values provided as arguments
  16. Observable.of("R", "G", "B").subscribe({
  17. next(color) {
  18. console.log(color);
  19. }
  20. });
  21. // Observable.from converts its argument to an Observable.
  22. Observable.from(["R", "G", "B"]).subscribe({
  23. next(color) {
  24. console.log(color);
  25. }
  26. });

String.prototype.matchAll

Stage-1

  1. var str = 'Hello world!!!';
  2. var regexp = /(\w+)\W*/g;
  3. console.log(str.matchAll(regexp));
  4. /*
  5. [
  6. {
  7. 0: "Hello ",
  8. 1: "Hello"
  9. index: 0,
  10. input: "Hello world!!!"
  11. },
  12. {
  13. 0: "world!!!",
  14. 1: "world"
  15. index: 6,
  16. input: "Hello world!!!"
  17. }
  18. ]
  19. */

WeakRefs

Stage-1

  1. // Make a new weak reference.
  2. // The target is a strong pointer to the object that will be pointed
  3. // at weakly by the result.
  4. // The executor is an optional argument that will be invoked after the
  5. // target becomes unreachable.
  6. // The holdings is an optional argument that will be provided to the
  7. // executor when it is invoked for target.
  8. makeWeakRef(target, executor, holdings);

Frozen Realms

Stage-1

  1. class Realm {
  2. // From the prior Realm API proposal
  3. const global -> object // access this realm's global object
  4. eval(stringable) -> any // do an indirect eval in this realm
  5. // We expect the rest of earlier proposal to be re-proposed eventually in
  6. // some form, but do not rely here on any of the remainder.
  7. // New with this proposal
  8. static immutableRoot() -> Realm // transitively immutable realm
  9. spawn(endowments) -> Realm // lightweight child realm
  10. }

Math Extensions

Stage-1

  1. // Possible ones:
  2. Math.map
  3. Math.scale
  4. Math.remap
  5. Math.clamp
  6. Math.constrain
  7. Math.toDegrees(double angrad)
  8. Math.toRadians(double angdeg)

of and from on collection constructors

Stage-1

  1. Map.of( ...items );
  2. Map.from( ...items );
  3. Set.of( ...items );
  4. Set.from( ...items );
  5. WeakMap.of( ...items );
  6. WeakMap.from( ...items );
  7. WeakSet.of( ...items );
  8. WeakSet.from( ...items );

Generator arrow functions.

Stage-1

  1. let cat = *() => { yield 'meow'; }

Date.parse fallback semantics

Stage-1

  1. // New grammar should be used as the "fallback"
  2. // when date strings do not conform to the
  3. // regular Date Time String Format.

Generator arrow functions (=>*)

Stage-1

  1. // current
  2. x => x * x;
  3. (...) => { statements }
  4. (...) => ( expr )
  5. // proposed generator arrows...
  6. // Irregular
  7. () =*>
  8. // Hostile to ! (async function)
  9. () => * { ...yield... }
  10. // Not good
  11. () => * (yield a, yield b)
  12. // Ok if 1 token
  13. x *=> x * x;
  14. // Bad (ASI)
  15. *() => ...
  16. // Hostile to !
  17. (x) =* {...}

Promise.try

Stage-1

  1. // Promise.try(function() fn) -> Promise

of and from on collection

Stage-1

  1. CollectionCreate ( C, source [ , mapfn [ , thisArg ] ] )
  2. Map.of ( ...items )
  3. Set.of ( ...items )
  4. WeakMap.of ( ...items )
  5. WeakSet.of ( ...items )
  6. Map.from ( source [ , mapFn [ , thisArg ] ] )
  7. Set.from ( source [ , mapFn [ , thisArg ] ] )
  8. WeakMap.from ( source [ , mapFn [ , thisArg ] ] )
  9. WeakSet.from ( source [ , mapFn [ , thisArg ] ] )

Optional Chaining

Stage-1

  1. obj?.prop // optional property access
  2. obj?.[expr] // ditto
  3. func?.(...args) // optional function or method call
  4. new C?.(...args) // optional constructor invocation

Math.signbit: IEEE-754 sign bit

Stage-1

  1. Math.signbit(x);
  2. /*
  3. Returns whether the sign bit of x is set.
  4. If n is NaN, the result is false.
  5. If n is -0, the result is true.
  6. If n is negative, the result is true.
  7. Otherwise, the result is false.
  8. */

Error Stacks

Stage-1

  1. Error.prototype.stack;
  2. System.getStack;
  3. System.getStackString;
  4. Object.getOwnPropertyDescriptor(new Error(), 'stack');
  5. Object.getOwnPropertyDescriptor(Error.prototype, 'stack');

do expressions

Stage-1

  1. let x = do {
  2. let tmp = f();
  3. tmp * tmp + 1
  4. };
  5. let x = do {
  6. if (foo()) { f() }
  7. else if (bar()) { g() }
  8. else { h() }
  9. };

Realms

Stage-1

  1. let realm = new Realm();
  2. let outerGlobal = window;
  3. let innerGlobal = realm.global;
  4. let f = realm.evalScript("(function() { return 17 })");
  5. f() === 17 // true
  6. Reflect.getPrototypeOf(f) === outerGlobal.Function.prototype // false
  7. Reflect.getPrototypeOf(f) === innerGlobal.Function.prototype // true
  8. class EmptyRealm extends Realm {
  9. constructor(...args) { super(...args); }
  10. init() { /* do nothing */ }
  11. }
  12. class FakeWindow extends Realm {
  13. init() {
  14. super.init(); // install the standard primordials
  15. let global = this.global;
  16. global.document = new FakeDocument(...);
  17. global.alert = new Proxy(fakeAlert, { ... });
  18. ...
  19. }
  20. }

Stage 2:

Template Literal Revision

Stage-2

  1. // The proposal is about fixing those Illegal token errors, avoid restrictions on escape sequences.
  2. let document = latex`
  3. \newcommand{\fun}{\textbf{Fun!}} // works just fine
  4. \newcommand{\unicode}{\textbf{Unicode!}} // Illegal token!
  5. \newcommand{\xerxes}{\textbf{King!}} // Illegal token!
  6. Breve over the h goes \u{h}ere // Illegal token!

function.sent Meta Property

Stage-2

  1. // Avoid ingnoring the first `next` call.
  2. function *adder(total=0) {
  3. let increment=1;
  4. do {
  5. switch (request = function.sent){
  6. case undefined: break;
  7. case "done": return total;
  8. default: increment = Number(request);
  9. }
  10. yield total += increment;
  11. } while (true)
  12. }
  13. let tally = adder();
  14. tally.next(0.1); // argument no longer ignored
  15. tally.next(0.1);
  16. tally.next(0.1);
  17. let last=tally.next("done");
  18. console.log(last.value); //0.3

Class Property Declarations

Stage-2

  1. // Class instance field
  2. class MyClass {
  3. myProp = 42;
  4. constructor() {
  5. console.log(this.myProp); // Prints '42'
  6. }
  7. }
  8. // Static property
  9. class MyClass {
  10. static myStaticProp = 42;
  11. constructor() {
  12. console.log(MyClass.myStaticProp); // Prints '42'
  13. }
  14. }
  1. // Class Static Properties
  2. class MyClass {
  3. static myStaticProp = 42;
  4. constructor() {
  5. console.log(MyClass.myStaticProp); // Prints '42'
  6. }
  7. }

Class and Property Decorators

Stage-2

  1. class C {
  2. @writable(false)
  3. method() { }
  4. }
  5. function writable(value) {
  6. return function (target, key, descriptor) {
  7. descriptor.writable = value;
  8. return descriptor;
  9. }
  10. }

String.prototype.{trimStart,trimEnd}

Stage-2

  1. " Hey JS!".trimStart(); // "Hey JS!"
  2. " Hey JS! ".trimEnd();// " Hey JS!"
  3. // P.S: trimLeft/trimRight are aliases.

Legacy RegExp features

Stage-2

  1. RegExpAlloc( newTarget );
  2. RegExpBuiltInExec( R, S );
  3. RegExp.input;
  4. RegExp.prototype.compile( pattern, flags ); // modifications

Intl.Segmenter: Unicode segmentation

Stage-2

  1. // Create a segmenter in your locale
  2. let segmenter = Intl.Segmenter("fr", {type: "word"});
  3. // Get an iterator over a string
  4. let iterator = segmenter.segment("Ceci n'est pas une pipe");
  5. // Iterate over it!
  6. for (let {segment, breakType} of iterator) {
  7. console.log(`segment: ${segment} breakType: ${breakType}`);
  8. break;
  9. }
  10. // logs the following to the console:
  11. // index: Ceci breakType: letter

export * as ns from “mod”; statements

Stage-2

  1. export * as ns from "mod"; // Exporting the ModuleNameSpace object as a named export.

Stage 3:

global

Stage-3

  1. // global to rule them all.
  2. var getGlobal = function () {
  3. // the only reliable means to get the global object is
  4. // `Function('return this')()`
  5. // However, this causes CSP violations in Chrome apps.
  6. if (typeof self !== 'undefined') { return self; }
  7. if (typeof window !== 'undefined') { return window; }
  8. if (typeof global !== 'undefined') { return global; }
  9. throw new Error('unable to locate global object');
  10. };

Rest and Spread properties

Stage-3

  1. let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; // Rest.
  2. let n = { x, y, ...z }; // Spread.

Async-iteration

Stage-3

  1. asyncIterator
  2. .next()
  3. .then(({ value, done }) => /* ... */);

Function.prototype.toString revision

Stage-3

  1. // String's parse must contains the same
  2. // function body and parameter list as the original.
  3. O.gOPD({ get a(){} }, "a").get // "function a(){}"
  4. O.gOPD({ set a(b){} }, "a").set // "function a(b){}"

SIMD APIs

Stage-3

  1. /*a meta-variable ranging over all SIMD types:
  2. Float32x4, Int32x4, Int16x8 Int8x16, Uint32x4,
  3. Uint16x8, Uint8x16, Bool32x4, Bool16x8 and Bool8x16. */

Lifting Template Literal Restriction

Stage-3

  1. function tag(strs) {
  2. strs[0] === undefined
  3. strs.raw[0] === "\\unicode and \\u{55}";
  4. }
  5. tag`\unicode and \u{55}`
  6. let bad = `bad escape sequence: \unicode`; // throws early error

Shared memory and atomics

Stage-3

  1. var sab = new SharedArrayBuffer(1024); // 1KiB shared memory
  2. w.postMessage(sab, [sab])
  3. // In the worker:
  4. var sab;
  5. onmessage = function (ev) {
  6. sab = ev.data; // 1KiB shared memory, the same memory as in the parent
  7. }

global

stage 3

  1. typeof global; // object, helps in writing a portable code.

import()

stage 3

  1. import(`./language-packs/${navigator.language}.js`) // import(specifier)

RegExp Lookbehind Assertions

Stage-3

  1. const str = '1947';
  2. // (?<=(\d+)(\d+))$/ => (947) and (1)
  3. // Greediness proceeds from right to left
  4. // match[1] => 947 and match[2] => 1
  5. // Numbering capture groups
  6. // /(?<=\1(.))/
  7. // Referring to capture groups
  8. // /(?<!.)/
  9. // Negative assertions

Unicode property escapes in RE

Stage-3

  1. const regexGreekSymbol = /\p{Script=Greek}/u;
  2. regexGreekSymbol.test('π');

RegExp Named Capture Groups

Stage-3

  1. let {one, two} = /^(?<one>.*):(?<two>.*)$/u.exec('foo:bar');
  2. console.log(`one: ${one}, two: ${two}`); // prints one: foo, two: bar

s (dotAll) flag for regular expressions

Stage-3

  1. const re = /foo.bar/s; // Or, `const re = new RegExp('foo.bar', 's');`.
  2. re.test('foo\nbar');
  3. // → true
  4. re.dotAll
  5. // → true
  6. re.flags
  7. // → 's'
  8. /foo.bar/s.test('foo\nbar');
  9. // → true

Asynchronous Iterators

Stage-3

  1. asyncIterator.next().then(result => console.log(result.value));
  2. for await (let line of readLines(filePath)) {
  3. print(line);
  4. }
  5. async function *readLines(path) {
  6. let file = await fileOpen(path);
  7. try {
  8. while (!file.EOF)
  9. yield file.readLine();
  10. } finally {
  11. await file.close();
  12. }
  13. }

Promise.prototype.finally

Stage-3

  1. somePromise()
  2. .then(() => {})
  3. .catch(() => {})
  4. .finally(() => {})

Class Fields

Stage-3

  1. class Point {
  2. #x = 0; // private fields start with #
  3. myProp = 42; // public field
  4. constructor() {
  5. this.#x; // 0
  6. this.myProp; // 0
  7. }
  8. }