[
  {
    "path": "License.md",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014 Luke Hoban\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# ECMAScript 6 <sup>[git.io/es6features](http://git.io/es6features)</sup>\n\n## Introduction\nECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard.  ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is [underway now](http://kangax.github.io/es5-compat-table/es6/).\n\nSee the [ES6 standard](http://www.ecma-international.org/ecma-262/6.0/) for full specification of the ECMAScript 6 language.\n\nES6 includes the following new features:\n- [arrows](#arrows)\n- [classes](#classes)\n- [enhanced object literals](#enhanced-object-literals)\n- [template strings](#template-strings)\n- [destructuring](#destructuring)\n- [default + rest + spread](#default--rest--spread)\n- [let + const](#let--const)\n- [iterators + for..of](#iterators--forof)\n- [generators](#generators)\n- [unicode](#unicode)\n- [modules](#modules)\n- [module loaders](#module-loaders)\n- [map + set + weakmap + weakset](#map--set--weakmap--weakset)\n- [proxies](#proxies)\n- [symbols](#symbols)\n- [subclassable built-ins](#subclassable-built-ins)\n- [promises](#promises)\n- [math + number + string + array + object APIs](#math--number--string--array--object-apis)\n- [binary and octal literals](#binary-and-octal-literals)\n- [reflect api](#reflect-api)\n- [tail calls](#tail-calls)\n\n## ECMAScript 6 Features\n\n### Arrows\nArrows are a function shorthand using the `=>` syntax.  They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript.  They support both statement block bodies as well as expression bodies which return the value of the expression.  Unlike functions, arrows share the same lexical `this` as their surrounding code.\n\n```JavaScript\n// Expression bodies\nvar odds = evens.map(v => v + 1);\nvar nums = evens.map((v, i) => v + i);\nvar pairs = evens.map(v => ({even: v, odd: v + 1}));\n\n// Statement bodies\nnums.forEach(v => {\n  if (v % 5 === 0)\n    fives.push(v);\n});\n\n// Lexical this\nvar bob = {\n  _name: \"Bob\",\n  _friends: [],\n  printFriends() {\n    this._friends.forEach(f =>\n      console.log(this._name + \" knows \" + f));\n  }\n}\n```\n\nMore info: [MDN Arrow Functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n\n### Classes\nES6 classes are a simple sugar over the prototype-based OO pattern.  Having a single convenient declarative form makes class patterns easier to use, and encourages interoperability.  Classes support prototype-based inheritance, super calls, instance and static methods and constructors.\n\n```JavaScript\nclass SkinnedMesh extends THREE.Mesh {\n  constructor(geometry, materials) {\n    super(geometry, materials);\n\n    this.idMatrix = SkinnedMesh.defaultMatrix();\n    this.bones = [];\n    this.boneMatrices = [];\n    //...\n  }\n  update(camera) {\n    //...\n    super.update();\n  }\n  get boneCount() {\n    return this.bones.length;\n  }\n  set matrixType(matrixType) {\n    this.idMatrix = SkinnedMesh[matrixType]();\n  }\n  static defaultMatrix() {\n    return new THREE.Matrix4();\n  }\n}\n```\n\nMore info: [MDN Classes](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes)\n\n### Enhanced Object Literals\nObject literals are extended to support setting the prototype at construction, shorthand for `foo: foo` assignments, defining methods, making super calls, and computing property names with expressions.  Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.\n\n```JavaScript\nvar obj = {\n    // __proto__\n    __proto__: theProtoObj,\n    // Shorthand for ‘handler: handler’\n    handler,\n    // Methods\n    toString() {\n     // Super calls\n     return \"d \" + super.toString();\n    },\n    // Computed (dynamic) property names\n    [ 'prop_' + (() => 42)() ]: 42\n};\n```\n\nMore info: [MDN Grammar and types: Object literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Object_literals)\n\n### Template Strings\nTemplate strings provide syntactic sugar for constructing strings.  This is similar to string interpolation features in Perl, Python and more.  Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.\n\n```JavaScript\n// Basic literal string creation\n`In JavaScript '\\n' is a line-feed.`\n\n// Multiline strings\n`In JavaScript this is\n not legal.`\n\n// String interpolation\nvar name = \"Bob\", time = \"today\";\n`Hello ${name}, how are you ${time}?`\n\n// Construct an HTTP request prefix is used to interpret the replacements and construction\nPOST`http://foo.org/bar?a=${a}&b=${b}\n     Content-Type: application/json\n     X-Credentials: ${credentials}\n     { \"foo\": ${foo},\n       \"bar\": ${bar}}`(myOnReadyStateChangeHandler);\n```\n\nMore info: [MDN Template Strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings)\n\n### Destructuring\nDestructuring allows binding using pattern matching, with support for matching arrays and objects.  Destructuring is fail-soft, similar to standard object lookup `foo[\"bar\"]`, producing `undefined` values when not found.\n\n```JavaScript\n// list matching\nvar [a, , b] = [1,2,3];\n\n// object matching\nvar { op: a, lhs: { op: b }, rhs: c }\n       = getASTNode()\n\n// object matching shorthand\n// binds `op`, `lhs` and `rhs` in scope\nvar {op, lhs, rhs} = getASTNode()\n\n// Can be used in parameter position\nfunction g({name: x}) {\n  console.log(x);\n}\ng({name: 5})\n\n// Fail-soft destructuring\nvar [a] = [];\na === undefined;\n\n// Fail-soft destructuring with defaults\nvar [a = 1] = [];\na === 1;\n```\n\nMore info: [MDN Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)\n\n### Default + Rest + Spread\nCallee-evaluated default parameter values.  Turn an array into consecutive arguments in a function call.  Bind trailing parameters to an array.  Rest replaces the need for `arguments` and addresses common cases more directly.\n\n```JavaScript\nfunction f(x, y=12) {\n  // y is 12 if not passed (or passed as undefined)\n  return x + y;\n}\nf(3) == 15\n```\n```JavaScript\nfunction f(x, ...y) {\n  // y is an Array\n  return x * y.length;\n}\nf(3, \"hello\", true) == 6\n```\n```JavaScript\nfunction f(x, y, z) {\n  return x + y + z;\n}\n// Pass each elem of array as argument\nf(...[1,2,3]) == 6\n```\n\nMore MDN info: [Default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), [Rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [Spread Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator)\n\n### Let + Const\nBlock-scoped binding constructs.  `let` is the new `var`.  `const` is single-assignment.  Static restrictions prevent use before assignment.\n\n\n```JavaScript\nfunction f() {\n  {\n    let x;\n    {\n      // okay, block scoped name\n      const x = \"sneaky\";\n      // error, const\n      x = \"foo\";\n    }\n    // error, already declared in block\n    let x = \"inner\";\n  }\n}\n```\n\nMore MDN info: [let statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), [const statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n\n### Iterators + For..Of\nIterator objects enable custom iteration like CLR IEnumerable or Java Iterable.  Generalize `for..in` to custom iterator-based iteration with `for..of`.  Don’t require realizing an array, enabling lazy design patterns like LINQ.\n\n```JavaScript\nlet fibonacci = {\n  [Symbol.iterator]() {\n    let pre = 0, cur = 1;\n    return {\n      next() {\n        [pre, cur] = [cur, pre + cur];\n        return { done: false, value: cur }\n      }\n    }\n  }\n}\n\nfor (var n of fibonacci) {\n  // truncate the sequence at 1000\n  if (n > 1000)\n    break;\n  console.log(n);\n}\n```\n\nIteration is based on these duck-typed interfaces (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):\n```TypeScript\ninterface IteratorResult {\n  done: boolean;\n  value: any;\n}\ninterface Iterator {\n  next(): IteratorResult;\n}\ninterface Iterable {\n  [Symbol.iterator](): Iterator\n}\n```\n\nMore info: [MDN for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n\n### Generators\nGenerators simplify iterator-authoring using `function*` and `yield`.  A function declared as function* returns a Generator instance.  Generators are subtypes of iterators which include additional  `next` and `throw`.  These enable values to flow back into the generator, so `yield` is an expression form which returns a value (or throws).\n\nNote: Can also be used to enable ‘await’-like async programming, see also ES7 `await` proposal.\n\n```JavaScript\nvar fibonacci = {\n  [Symbol.iterator]: function*() {\n    var pre = 0, cur = 1;\n    for (;;) {\n      var temp = pre;\n      pre = cur;\n      cur += temp;\n      yield cur;\n    }\n  }\n}\n\nfor (var n of fibonacci) {\n  // truncate the sequence at 1000\n  if (n > 1000)\n    break;\n  console.log(n);\n}\n```\n\nThe generator interface is (using [TypeScript](http://typescriptlang.org) type syntax for exposition only):\n\n```TypeScript\ninterface Generator extends Iterator {\n    next(value?: any): IteratorResult;\n    throw(exception: any);\n}\n```\n\nMore info: [MDN Iteration protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)\n\n### Unicode\nNon-breaking additions to support full Unicode, including new Unicode literal form in strings and new RegExp `u` mode to handle code points, as well as new APIs to process strings at the 21bit code points level.  These additions support building global apps in JavaScript.\n\n```JavaScript\n// same as ES5.1\n\"𠮷\".length == 2\n\n// new RegExp behaviour, opt-in ‘u’\n\"𠮷\".match(/./u)[0].length == 2\n\n// new form\n\"\\u{20BB7}\"==\"𠮷\"==\"\\uD842\\uDFB7\"\n\n// new String ops\n\"𠮷\".codePointAt(0) == 0x20BB7\n\n// for-of iterates code points\nfor(var c of \"𠮷\") {\n  console.log(c);\n}\n```\n\nMore info: [MDN RegExp.prototype.unicode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode)\n\n### Modules\nLanguage-level support for modules for component definition.  Codifies patterns from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour defined by a host-defined default loader.  Implicitly async model – no code executes until requested modules are available and processed.\n\n```JavaScript\n// lib/math.js\nexport function sum(x, y) {\n  return x + y;\n}\nexport var pi = 3.141593;\n```\n```JavaScript\n// app.js\nimport * as math from \"lib/math\";\nalert(\"2π = \" + math.sum(math.pi, math.pi));\n```\n```JavaScript\n// otherApp.js\nimport {sum, pi} from \"lib/math\";\nalert(\"2π = \" + sum(pi, pi));\n```\n\nSome additional features include `export default` and `export *`:\n\n```JavaScript\n// lib/mathplusplus.js\nexport * from \"lib/math\";\nexport var e = 2.71828182846;\nexport default function(x) {\n    return Math.log(x);\n}\n```\n```JavaScript\n// app.js\nimport ln, {pi, e} from \"lib/mathplusplus\";\nalert(\"2π = \" + ln(e)*pi*2);\n```\n\nMore MDN info: [import statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import), [export statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n\n### Module Loaders\nModule loaders support:\n- Dynamic loading\n- State isolation\n- Global namespace isolation\n- Compilation hooks\n- Nested virtualization\n\nThe default module loader can be configured, and new loaders can be constructed to evaluate and load code in isolated or constrained contexts.\n\n```JavaScript\n// Dynamic loading – ‘System’ is default loader\nSystem.import('lib/math').then(function(m) {\n  alert(\"2π = \" + m.sum(m.pi, m.pi));\n});\n\n// Create execution sandboxes – new Loaders\nvar loader = new Loader({\n  global: fixup(window) // replace ‘console.log’\n});\nloader.eval(\"console.log('hello world!');\");\n\n// Directly manipulate module cache\nSystem.get('jquery');\nSystem.set('jquery', Module({$: $})); // WARNING: not yet finalized\n```\n\n### Map + Set + WeakMap + WeakSet\nEfficient data structures for common algorithms.  WeakMaps provides leak-free object-key’d side tables.\n\n```JavaScript\n// Sets\nvar s = new Set();\ns.add(\"hello\").add(\"goodbye\").add(\"hello\");\ns.size === 2;\ns.has(\"hello\") === true;\n\n// Maps\nvar m = new Map();\nm.set(\"hello\", 42);\nm.set(s, 34);\nm.get(s) == 34;\n\n// Weak Maps\nvar wm = new WeakMap();\nwm.set(s, { extra: 42 });\nwm.size === undefined\n\n// Weak Sets\nvar ws = new WeakSet();\nws.add({ data: 42 });\n// Because the added object has no other references, it will not be held in the set\n```\n\nMore MDN info: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap), [WeakSet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet)\n\n### Proxies\nProxies enable creation of objects with the full range of behaviors available to host objects.  Can be used for interception, object virtualization, logging/profiling, etc.\n\n```JavaScript\n// Proxying a normal object\nvar target = {};\nvar handler = {\n  get: function (receiver, name) {\n    return `Hello, ${name}!`;\n  }\n};\n\nvar p = new Proxy(target, handler);\np.world === 'Hello, world!';\n```\n\n```JavaScript\n// Proxying a function object\nvar target = function () { return 'I am the target'; };\nvar handler = {\n  apply: function (receiver, ...args) {\n    return 'I am the proxy';\n  }\n};\n\nvar p = new Proxy(target, handler);\np() === 'I am the proxy';\n```\n\nThere are traps available for all of the runtime-level meta-operations:\n\n```JavaScript\nvar handler =\n{\n  get:...,\n  set:...,\n  has:...,\n  deleteProperty:...,\n  apply:...,\n  construct:...,\n  getOwnPropertyDescriptor:...,\n  defineProperty:...,\n  getPrototypeOf:...,\n  setPrototypeOf:...,\n  enumerate:...,\n  ownKeys:...,\n  preventExtensions:...,\n  isExtensible:...\n}\n```\n\nMore info: [MDN Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)\n\n### Symbols\nSymbols enable access control for object state.  Symbols allow properties to be keyed by either `string` (as in ES5) or `symbol`.  Symbols are a new primitive type. Optional `description` parameter used in debugging - but is not part of identity.  Symbols are unique (like gensym), but not private since they are exposed via reflection features like `Object.getOwnPropertySymbols`.\n\n\n```JavaScript\nvar MyClass = (function() {\n\n  // module scoped symbol\n  var key = Symbol(\"key\");\n\n  function MyClass(privateData) {\n    this[key] = privateData;\n  }\n\n  MyClass.prototype = {\n    doStuff: function() {\n      ... this[key] ...\n    }\n  };\n\n  return MyClass;\n})();\n\nvar c = new MyClass(\"hello\")\nc[\"key\"] === undefined\n```\n\nMore info: [MDN Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)\n\n### Subclassable Built-ins\nIn ES6, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed.\n\nObject construction for a function named `Ctor` now uses two-phases (both virtually dispatched):\n- Call `Ctor[@@create]` to allocate the object, installing any special behavior\n- Invoke constructor on new instance to initialize\n\nThe known `@@create` symbol is available via `Symbol.create`.  Built-ins now expose their `@@create` explicitly.\n\n```JavaScript\n// Pseudo-code of Array\nclass Array {\n    constructor(...args) { /* ... */ }\n    static [Symbol.create]() {\n        // Install special [[DefineOwnProperty]]\n        // to magically update 'length'\n    }\n}\n\n// User code of Array subclass\nclass MyArray extends Array {\n    constructor(...args) { super(...args); }\n}\n\n// Two-phase 'new':\n// 1) Call @@create to allocate object\n// 2) Invoke constructor on new instance\nvar arr = new MyArray();\narr[1] = 12;\narr.length == 2\n```\n\n### Math + Number + String + Array + Object APIs\nMany new library additions, including core Math libraries, Array conversion helpers, String helpers, and Object.assign for copying.\n\n```JavaScript\nNumber.EPSILON\nNumber.isInteger(Infinity) // false\nNumber.isNaN(\"NaN\") // false\n\nMath.acosh(3) // 1.762747174039086\nMath.hypot(3, 4) // 5\nMath.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2\n\n\"abcde\".includes(\"cd\") // true\n\"abc\".repeat(3) // \"abcabcabc\"\n\nArray.from(document.querySelectorAll('*')) // Returns a real Array\nArray.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior\n[0, 0, 0].fill(7, 1) // [0,7,7]\n[1, 2, 3].find(x => x == 3) // 3\n[1, 2, 3].findIndex(x => x == 2) // 1\n[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]\n[\"a\", \"b\", \"c\"].entries() // iterator [0, \"a\"], [1,\"b\"], [2,\"c\"]\n[\"a\", \"b\", \"c\"].keys() // iterator 0, 1, 2\n[\"a\", \"b\", \"c\"].values() // iterator \"a\", \"b\", \"c\"\n\nObject.assign(Point, { origin: new Point(0,0) })\n```\n\nMore MDN info: [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), [Math](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math), [Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from), [Array.of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of), [Array.prototype.copyWithin](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin), [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n\n### Binary and Octal Literals\nTwo new numeric literal forms are added for binary (`b`) and octal (`o`).\n\n```JavaScript\n0b111110111 === 503 // true\n0o767 === 503 // true\n```\n\n### Promises\nPromises are a library for asynchronous programming.  Promises are a first class representation of a value that may be made available in the future.  Promises are used in many existing JavaScript libraries.\n\n```JavaScript\nfunction timeout(duration = 0) {\n    return new Promise((resolve, reject) => {\n        setTimeout(resolve, duration);\n    })\n}\n\nvar p = timeout(1000).then(() => {\n    return timeout(2000);\n}).then(() => {\n    throw new Error(\"hmm\");\n}).catch(err => {\n    return Promise.all([timeout(100), timeout(200)]);\n})\n```\n\nMore info: [MDN Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n\n### Reflect API\nFull reflection API exposing the runtime-level meta-operations on objects.  This is effectively the inverse of the Proxy API, and allows making calls corresponding to the same meta-operations as the proxy traps.  Especially useful for implementing proxies.\n\n```JavaScript\n// No sample yet\n```\n\nMore info: [MDN Reflect](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect)\n\n### Tail Calls\nCalls in tail-position are guaranteed to not grow the stack unboundedly.  Makes recursive algorithms safe in the face of unbounded inputs.\n\n```JavaScript\nfunction factorial(n, acc = 1) {\n    'use strict';\n    if (n <= 1) return acc;\n    return factorial(n - 1, n * acc);\n}\n\n// Stack overflow in most implementations today,\n// but safe on arbitrary inputs in ES6\nfactorial(100000)\n```\n"
  }
]