0.1.1 • Published 4 years ago

core-js-with-latest-tweet-from-donald-trump v0.1.1

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

https://www.npmjs.com/package/core-js-with-latest-tweet-from-donald-trump

Sponsors on Open Collective Backers on Open Collective Gitter version npm downloads Build Status devDependency status

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2020: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

If you looking documentation for obsolete core-js@2, please, check this branch.

As advertising: the author is looking for a good job -)

core-js@3, babel and a look into the future

Raising funds

core-js isn't backed by a company, so the future of this project depends on you. Become a sponsor or a backer on Open Collective or on Patreon if you are interested in core-js.




For enterprise

Available as part of the Tidelift Subscription.

The maintainers of core-js and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.


Example of usage:

import 'core-js'; // <- at the top of your entry point

Array.from(new Set([1, 2, 3, 2, 1]));          // => [1, 2, 3]
[1, [2, 3], [4, [5]]].flat(2);                 // => [1, 2, 3, 4, 5]
Promise.resolve(32).then(x => console.log(x)); // => 32

You can load only required features:

import 'core-js/features/array/from'; // <- at the top of your entry point
import 'core-js/features/array/flat'; // <- at the top of your entry point
import 'core-js/features/set';        // <- at the top of your entry point
import 'core-js/features/promise';    // <- at the top of your entry point

Array.from(new Set([1, 2, 3, 2, 1]));          // => [1, 2, 3]
[1, [2, 3], [4, [5]]].flat(2);                 // => [1, 2, 3, 4, 5]
Promise.resolve(32).then(x => console.log(x)); // => 32

Or use it without global namespace pollution:

import from from 'core-js-pure/features/array/from';
import flat from 'core-js-pure/features/array/flat';
import Set from 'core-js-pure/features/set';
import Promise from 'core-js-pure/features/promise';

from(new Set([1, 2, 3, 2, 1]));                // => [1, 2, 3]
flat([1, [2, 3], [4, [5]]], 2);                // => [1, 2, 3, 4, 5]
Promise.resolve(32).then(x => console.log(x)); // => 32

Index

Usage

Installation:

// global version
npm install --save core-js@3.6.5
// version without global namespace pollution
npm install --save core-js-pure@3.6.5
// bundled global version
npm install --save core-js-bundle@3.6.5

Already bundled version of core-js on CDN (minified version).

postinstall message

The core-js project needs your help, so the package shows a message about it after installation. If it causes problems for you, you can disable it:

ADBLOCK=true npm install
// or
DISABLE_OPENCOLLECTIVE=true npm install
// or
npm install --loglevel silent

CommonJS API

You can import only-required-for-you polyfills, like in examples at the top of README.md. Available CommonJS entry points for all polyfilled methods / constructors and namespaces. Just some examples:

// polyfill all `core-js` features:
import "core-js";
// polyfill only stable `core-js` features - ES and web standards:
import "core-js/stable";
// polyfill only stable ES features:
import "core-js/es";

// if you want to polyfill `Set`:
// all `Set`-related features, with ES proposals:
import "core-js/features/set";
// stable required for `Set` ES features and features from web standards
// (DOM collections iterator in this case):
import "core-js/stable/set";
// only stable ES features required for `Set`:
import "core-js/es/set";
// the same without global namespace pollution:
import Set from "core-js-pure/features/set";
import Set from "core-js-pure/stable/set";
import Set from "core-js-pure/es/set";

// if you want to polyfill just required methods:
import "core-js/features/set/intersection";
import "core-js/stable/queue-microtask";
import "core-js/es/array/from";

// polyfill reflect metadata proposal:
import "core-js/proposals/reflect-metadata";
// polyfill all stage 2+ proposals:
import "core-js/stage/2";
Caveats when using CommonJS API:
  • modules path is an internal API, does not inject all required dependencies and can be changed in minor or patch releases. Use it only for a custom build and/or if you know what are you doing.
  • If you use core-js with the extension of native objects, recommended load all core-js modules at the top of the entry point of your application, otherwise, you can have conflicts.
  • core-js is extremely modular and uses a lot of very tiny modules, because of that for usage in browsers bundle up core-js instead of usage loader for each file, otherwise, you will have hundreds of requests.

CommonJS and prototype methods without global namespace pollution

In the pure version, we can't pollute prototypes of native constructors. Because of that, prototype methods transformed into static methods like in examples above. But with transpilers, we can use one more trick - bind operator and virtual methods. Special for that, available /virtual/ entry points. Example:

import fill from 'core-js-pure/features/array/virtual/fill';
import findIndex from 'core-js-pure/features/array/virtual/find-index';

Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8)); // => 4

// or

import { fill, findIndex } from 'core-js-pure/features/array/virtual';

Array(10)::fill(0).map((a, b) => b * b)::findIndex(it => it && !(it % 8)); // => 4

Babel

core-js is integrated with babel and is the base for polyfilling-related babel features:

@babel/polyfill

@babel/polyfill IS just the import of stable core-js features and regenerator-runtime for generators and async functions, so if you load @babel/polyfill - you load the global version of core-js without ES proposals.

Now it's deprecated in favour of separate inclusion of required parts of core-js and regenerator-runtime and, for preventing breaking changes, left on core-js@2.

As a full equal of @babel/polyfill, you can use this:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

@babel/preset-env

@babel/preset-env has useBuiltIns option, which optimizes working with global version of core-js. With useBuiltIns option, you should also set corejs option to used version of core-js, like corejs: '3.6'.

Warning! Recommended to specify used minor core-js version, like corejs: '3.6', instead of corejs: 3, since with corejs: 3 will not be injected modules which were added in minor core-js releases.

  • useBuiltIns: 'entry' replaces imports of core-js to import only required for a target environment modules. So, for example,
import 'core-js/stable';

with chrome 71 target will be replaced just to:

import "core-js/modules/es.array.unscopables.flat";
import "core-js/modules/es.array.unscopables.flat-map";
import "core-js/modules/es.object.from-entries";
import "core-js/modules/web.immediate";

It works for all entry points of global version of core-js and their combinations, for example for

import 'core-js/es';
import 'core-js/proposals/set-methods';
import 'core-js/features/set/map';

with chrome 71 target you will have as a result:

import "core-js/modules/es.array.unscopables.flat";
import "core-js/modules/es.array.unscopables.flat-map";
import "core-js/modules/es.object.from-entries";
import "core-js/modules/esnext.set.difference";
import "core-js/modules/esnext.set.intersection";
import "core-js/modules/esnext.set.is-disjoint-from";
import "core-js/modules/esnext.set.is-subset-of";
import "core-js/modules/esnext.set.is-superset-of";
import "core-js/modules/esnext.set.map";
import "core-js/modules/esnext.set.symmetric-difference";
import "core-js/modules/esnext.set.union";
  • useBuiltIns: 'usage' adds to the top of each file import of polyfills for features used in this file and not supported by target environments, so for:
// first file:
var set = new Set([1, 2, 3]);

// second file:
var array = Array.of(1, 2, 3);

if target contains an old environment like IE 11 we will have something like:

// first file:
import 'core-js/modules/es.array.iterator';
import 'core-js/modules/es.object.to-string';
import 'core-js/modules/es.set';
var set = new Set([1, 2, 3]);

// second file:
import 'core-js/modules/es.array.of';
var array = Array.of(1, 2, 3);

By default, @babel/preset-env with useBuiltIns: 'usage' option only polyfills stable features, but you can enable polyfilling of proposals by proposals option, as corejs: { version: '3.6', proposals: true }.

@babel/runtime

@babel/runtime with corejs: 3 option simplifies work with core-js-pure. It automatically replaces usage of modern features from JS standard library to imports from the version of core-js without global namespace pollution, so instead of:

import from from 'core-js-pure/stable/array/from';
import flat from 'core-js-pure/stable/array/flat';
import Set from 'core-js-pure/stable/set';
import Promise from 'core-js-pure/stable/promise';

from(new Set([1, 2, 3, 2, 1]));
flat([1, [2, 3], [4, [5]]], 2);
Promise.resolve(32).then(x => console.log(x));

you can write just:

Array.from(new Set([1, 2, 3, 2, 1]));
[1, [2, 3], [4, [5]]].flat(2);
Promise.resolve(32).then(x => console.log(x));

By default, @babel/runtime only polyfills stable features, but like in @babel/preset-env, you can enable polyfilling of proposals by proposals option, as corejs: { version: 3, proposals: true }.

Warning! If you use @babel/preset-env and @babel/runtime together, use corejs option only in one place since it's duplicate functionality and will cause conflicts.

Configurable level of aggressiveness

By default, core-js sets polyfills only when they are required. That means that core-js checks if a feature is available and works correctly or not and if it has no problems, core-js use native implementation.

But sometimes core-js feature detection could be too strict for your case. For example, Promise constructor requires the support of unhandled rejection tracking and @@species.

Sometimes we could have inverse problem - knowingly broken environment with problems not covered by core-js feature detection.

For those cases, we could redefine this behaviour for certain polyfills:

const configurator = require('core-js/configurator');

configurator({
  useNative: ['Promise'],                                 // polyfills will be used only if natives completely unavailable
  usePolyfill: ['Array.from', 'String.prototype.padEnd'], // polyfills will be used anyway
  useFeatureDetection: ['Map', 'Set'],                    // default behaviour
});

require('core-js');

It does not work with some features. Also, if you change the default behaviour, even core-js internals may not work correctly.

Custom build

For some cases could be useful adding a blacklist of features or generation a polyfill for target engines. You could use core-js-builder package for that.

Compatibility data

core-js-compat package contains data about the necessity of core-js modules and API for getting a list of required core-js modules by browserslist query.

Supported engines

Tested in:

  • Chrome 26+
  • Firefox 4+
  • Safari 5+
  • Opera 12+
  • Internet Explorer 8+ (sure, IE8 with ES3 limitations; IE7- also should work, but no longer tested)
  • Edge
  • Android Browser 2.3+
  • iOS Safari 5.1+
  • PhantomJS 1.9+
  • NodeJS 0.8+

...and it doesn't mean core-js will not work in other engines, they just have not been tested.

Features:

CommonJS entry points:

core-js(-pure)

ECMAScript

CommonJS entry points:

core-js(-pure)/es

ECMAScript: Object

Modules es.object.assign, es.object.is, es.object.set-prototype-of, es.object.to-string, es.object.freeze, es.object.seal, es.object.prevent-extensions, es.object.is-frozen, es.object.is-sealed, es.object.is-extensible, es.object.get-own-property-descriptor, es.object.get-own-property-descriptors, es.object.get-prototype-of, es.object.keys, es.object.values, es.object.entries, es.object.get-own-property-names and es.object.from-entries.

Just ES5 features: es.object.create, es.object.define-property and es.object.define-properties.

ES2017 Annex B - modules es.object.define-setter, es.object.define-getter, es.object.lookup-setter and es.object.lookup-getter

class Object {
  toString(): string; // ES2015+ fix: @@toStringTag support
  __defineGetter__(property: PropertyKey, getter: Function): void;
  __defineSetter__(property: PropertyKey, setter: Function): void;
  __lookupGetter__(property: PropertyKey): Function | void;
  __lookupSetter__(property: PropertyKey): Function | void;
  static assign(target: Object, ...sources: Array<Object>): Object;
  static create(prototype: Object | null, properties?: { [property: PropertyKey]: PropertyDescriptor }): Object;
  static defineProperties(object: Object, properties: { [property: PropertyKey]: PropertyDescriptor })): Object;
  static defineProperty(object: Object, property: PropertyKey, attributes: PropertyDescriptor): Object;
  static entries(object: Object): Array<[string, mixed]>;
  static freeze(object: any): any;
  static fromEntries(iterable: Iterable<[key, value]>): Object;
  static getOwnPropertyDescriptor(object: any, property: PropertyKey): PropertyDescriptor | void;
  static getOwnPropertyDescriptors(object: any): { [property: PropertyKey]: PropertyDescriptor };
  static getOwnPropertyNames(object: any): Array<string>;
  static getPrototypeOf(object: any): Object | null;
  static is(value1: any, value2: any): boolean;
  static isExtensible(object: any): boolean;
  static isFrozen(object: any): boolean;
  static isSealed(object: any): boolean;
  static keys(object: any): Array<string>;
  static preventExtensions(object: any): any;
  static seal(object: any): any;
  static setPrototypeOf(target: any, prototype: Object | null): any; // required __proto__ - IE11+
  static values(object: any): Array<mixed>;
}

CommonJS entry points:

core-js(-pure)/es|stable|features/object
core-js(-pure)/es|stable|features/object/assign
core-js(-pure)/es|stable|features/object/is
core-js(-pure)/es|stable|features/object/set-prototype-of
core-js(-pure)/es|stable|features/object/get-prototype-of
core-js(-pure)/es|stable|features/object/create
core-js(-pure)/es|stable|features/object/define-property
core-js(-pure)/es|stable|features/object/define-properties
core-js(-pure)/es|stable|features/object/get-own-property-descriptor
core-js(-pure)/es|stable|features/object/get-own-property-descriptors
core-js(-pure)/es|stable|features/object/keys
core-js(-pure)/es|stable|features/object/values
core-js(-pure)/es|stable|features/object/entries
core-js(-pure)/es|stable|features/object/get-own-property-names
core-js(-pure)/es|stable|features/object/freeze
core-js(-pure)/es|stable|features/object/from-entries
core-js(-pure)/es|stable|features/object/seal
core-js(-pure)/es|stable|features/object/prevent-extensions
core-js(-pure)/es|stable|features/object/is-frozen
core-js(-pure)/es|stable|features/object/is-sealed
core-js(-pure)/es|stable|features/object/is-extensible
core-js/es|stable|features/object/to-string
core-js(-pure)/es|stable|features/object/define-getter
core-js(-pure)/es|stable|features/object/define-setter
core-js(-pure)/es|stable|features/object/lookup-getter
core-js(-pure)/es|stable|features/object/lookup-setter

Examples:

let foo = { q: 1, w: 2 };
let bar = { e: 3, r: 4 };
let baz = { t: 5, y: 6 };
Object.assign(foo, bar, baz); // => foo = { q: 1, w: 2, e: 3, r: 4, t: 5, y: 6 }

Object.is(NaN, NaN); // => true
Object.is(0, -0);    // => false
Object.is(42, 42);   // => true
Object.is(42, '42'); // => false

function Parent() {}
function Child() {}
Object.setPrototypeOf(Child.prototype, Parent.prototype);
new Child() instanceof Child;  // => true
new Child() instanceof Parent; // => true

let object = {
  [Symbol.toStringTag]: 'Foo'
};

'' + object; // => '[object Foo]'

Object.keys('qwe'); // => ['0', '1', '2']
Object.getPrototypeOf('qwe') === String.prototype; // => true

Object.values({ a: 1, b: 2, c: 3 });  // => [1, 2, 3]
Object.entries({ a: 1, b: 2, c: 3 }); // => [['a', 1], ['b', 2], ['c', 3]]

for (let [key, value] of Object.entries({ a: 1, b: 2, c: 3 })) {
  console.log(key);   // => 'a', 'b', 'c'
  console.log(value); // => 1, 2, 3
}

// Shallow object cloning with prototype and descriptors:
let copy = Object.create(Object.getPrototypeOf(object), Object.getOwnPropertyDescriptors(object));
// Mixin:
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));

const map = new Map([['a', 1], ['b', 2]]);
Object.fromEntries(map); // => { a: 1, b: 2 }

class Unit {
  constructor(id) {
    this.id = id;
  }
  toString() {
    return `unit${ this.id }`;
  }
}

const units = new Set([new Unit(101), new Unit(102)]);

Object.fromEntries(units.entries()); // => { unit101: Unit { id: 101 }, unit102: Unit { id: 102 } }

ECMAScript: Function

Modules es.function.name, es.function.has-instance. Just ES5: es.function.bind.

class Function {
  name: string;
  bind(thisArg: any, ...args: Array<mixed>): Function;
  @@hasInstance(value: any): boolean;
}

CommonJS entry points:

core-js/es|stable|features/function
core-js/es|stable|features/function/name
core-js/es|stable|features/function/has-instance
core-js/es|stable|features/function/bind
core-js/es|stable|features/function/virtual/bind

Example:

(function foo() {}).name // => 'foo'

console.log.bind(console, 42)(43); // => 42 43

ECMAScript: Array

Modules es.array.from, es.array.is-array, es.array.of, es.array.copy-within, es.array.fill, es.array.find, es.array.find-index, es.array.iterator, es.array.includes, es.array.slice, es.array.join, es.array.index-of, es.array.last-index-of, es.array.every, es.array.some, es.array.for-each, es.array.map, es.array.filter, es.array.reduce, es.array.reduce-right, es.array.reverse, es.array.sort, es.array.flat, es.array.flat-map, es.array.unscopables.flat and es.array.unscopables.flat-map

class Array {
  concat(...args: Array<mixed>): Array<mixed>; // with adding support of @@isConcatSpreadable and @@species
  copyWithin(target: number, start: number, end?: number): this;
  entries(): Iterator<[index, value]>;
  every(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): boolean;
  fill(value: any, start?: number, end?: number): this;
  filter(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): Array<mixed>; // with adding support of @@species
  find(callbackfn: (value: any, index: number, target: any) => boolean), thisArg?: any): any;
  findIndex(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): number;
  flat(depthArg?: number = 1): Array<mixed>;
  flatMap(mapFn: (value: any, index: number, target: any) => any, thisArg: any): Array<mixed>;
  forEach(callbackfn: (value: any, index: number, target: any) => void, thisArg?: any): void;
  includes(searchElement: any, from?: number): boolean;
  indexOf(searchElement: any, from?: number): number;
  join(separator: string = ','): string;
  keys(): Iterator<index>;
  lastIndexOf(searchElement: any, from?: number): number;
  map(mapFn: (value: any, index: number, target: any) => any, thisArg?: any): Array<mixed>; // with adding support of @@species
  reduce(callbackfn: (memo: any, value: any, index: number, target: any) => any, initialValue?: any): any;
  reduceRight(callbackfn: (memo: any, value: any, index: number, target: any) => any, initialValue?: any): any;
  reverse(): this; // Safari 12.0 bug fix
  slice(start?: number, end?: number): Array<mixed>; // with adding support of @@species
  splice(start?: number, deleteCount?: number, ...items: Array<mixed>): Array<mixed>; // with adding support of @@species
  some(callbackfn: (value: any, index: number, target: any) => boolean, thisArg?: any): boolean;
  sort(comparefn?: (a: any, b: any) => number): this;
  values(): Iterator<value>;
  @@iterator(): Iterator<value>;
  @@unscopables: { [newMethodNames: string]: true };
  static from(items: Iterable | ArrayLike, mapFn?: (value: any, index: number) => any, thisArg?: any): Array<mixed>;
  static isArray(value: any): boolean;
  static of(...args: Array<mixed>): Array<mixed>;
}

class Arguments {
  @@iterator(): Iterator<value>; // available only in core-js methods
}

CommonJS entry points:

core-js(-pure)/es|stable|features/array
core-js(-pure)/es|stable|features/array/from
core-js(-pure)/es|stable|features/array/of
core-js(-pure)/es|stable|features/array/is-array
core-js(-pure)/es|stable|features/array/concat
core-js(-pure)/es|stable|features/array/entries
core-js(-pure)/es|stable|features/array/every
core-js(-pure)/es|stable|features/array/copy-within
core-js(-pure)/es|stable|features/array/fill
core-js(-pure)/es|stable|features/array/filter
core-js(-pure)/es|stable|features/array/find
core-js(-pure)/es|stable|features/array/find-index
core-js(-pure)/es|stable|features/array/flat
core-js(-pure)/es|stable|features/array/flat-map
core-js(-pure)/es|stable|features/array/for-each
core-js(-pure)/es|stable|features/array/includes
core-js(-pure)/es|stable|features/array/index-of
core-js(-pure)/es|stable|features/array/iterator
core-js(-pure)/es|stable|features/array/join
core-js(-pure)/es|stable|features/array/keys
core-js(-pure)/es|stable|features/array/last-index-of
core-js(-pure)/es|stable|features/array/map
core-js(-pure)/es|stable|features/array/reduce
core-js(-pure)/es|stable|features/array/reduce-right
core-js(-pure)/es|stable|features/array/reverse
core-js(-pure)/es|stable|features/array/slice
core-js(-pure)/es|stable|features/array/splice
core-js(-pure)/es|stable|features/array/some
core-js(-pure)/es|stable|features/array/sort
core-js(-pure)/es|stable|features/array/values
core-js(-pure)/es|stable|features/array/virtual/concat
core-js(-pure)/es|stable|features/array/virtual/copy-within
core-js(-pure)/es|stable|features/array/virtual/entries
core-js(-pure)/es|stable|features/array/virtual/every
core-js(-pure)/es|stable|features/array/virtual/fill
core-js(-pure)/es|stable|features/array/virtual/filter
core-js(-pure)/es|stable|features/array/virtual/find
core-js(-pure)/es|stable|features/array/virtual/find-index
core-js(-pure)/es|stable|features/array/virtual/flat
core-js(-pure)/es|stable|features/array/virtual/flat-map
core-js(-pure)/es|stable|features/array/virtual/for-each
core-js(-pure)/es|stable|features/array/virtual/includes
core-js(-pure)/es|stable|features/array/virtual/index-of
core-js(-pure)/es|stable|features/array/virtual/iterator
core-js(-pure)/es|stable|features/array/virtual/join
core-js(-pure)/es|stable|features/array/virtual/keys
core-js(-pure)/es|stable|features/array/virtual/last-index-of
core-js(-pure)/es|stable|features/array/virtual/map
core-js(-pure)/es|stable|features/array/virtual/reduce
core-js(-pure)/es|stable|features/array/virtual/reduce-right
core-js(-pure)/es|stable|features/array/virtual/reverse
core-js(-pure)/es|stable|features/array/virtual/slice
core-js(-pure)/es|stable|features/array/virtual/some
core-js(-pure)/es|stable|features/array/virtual/sort
core-js(-pure)/es|stable|features/array/virtual/splice
core-js(-pure)/es|stable|features/array/virtual/values

Examples:

Array.from(new Set([1, 2, 3, 2, 1]));        // => [1, 2, 3]
Array.from({ 0: 1, 1: 2, 2: 3, length: 3 }); // => [1, 2, 3]
Array.from('123', Number);                   // => [1, 2, 3]
Array.from('123', it => it * it);            // => [1, 4, 9]

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

let array = ['a', 'b', 'c'];

for (let value of array) console.log(value);          // => 'a', 'b', 'c'
for (let value of array.values()) console.log(value); // => 'a', 'b', 'c'
for (let key of array.keys()) console.log(key);       // => 0, 1, 2
for (let [key, value] of array.entries()) {
  console.log(key);                                   // => 0, 1, 2
  console.log(value);                                 // => 'a', 'b', 'c'
}

function isOdd(value) {
  return value % 2;
}
[4, 8, 15, 16, 23, 42].find(isOdd);      // => 15
[4, 8, 15, 16, 23, 42].findIndex(isOdd); // => 2
[4, 8, 15, 16, 23, 42].find(isNaN);      // => undefined
[4, 8, 15, 16, 23, 42].findIndex(isNaN); // => -1

Array(5).fill(42); // => [42, 42, 42, 42, 42]

[1, 2, 3, 4, 5].copyWithin(0, 3); // => [4, 5, 3, 4, 5]


[1, 2, 3].includes(2);        // => true
[1, 2, 3].includes(4);        // => false
[1, 2, 3].includes(2, 2);     // => false

[NaN].indexOf(NaN);           // => -1
[NaN].includes(NaN);          // => true
Array(1).indexOf(undefined);  // => -1
Array(1).includes(undefined); // => true

[1, [2, 3], [4, 5]].flat();    // => [1, 2, 3, 4, 5]
[1, [2, [3, [4]]], 5].flat();  // => [1, 2, [3, [4]], 5]
[1, [2, [3, [4]]], 5].flat(3); // => [1, 2, 3, 4, 5]

[{ a: 1, b: 2 }, { a: 3, b: 4 }, { a: 5, b: 6 }].flatMap(it => [it.a, it.b]); // => [1, 2, 3, 4, 5, 6]

ECMAScript: String and RegExp

The main part of String features: modules es.string.from-code-point, es.string.raw, es.string.iterator, es.string.split, es.string.code-point-at, es.string.ends-with, es.string.includes, es.string.repeat, es.string.pad-start, es.string.pad-end, es.string.starts-with, es.string.trim, es.string.trim-start, es.string.trim-end, es.string.match-all.

Adding support of well-known symbols @@match, @@replace, @@search and @@split and direct .exec calls to related String methods, modules es.string.match, es.string.replace, es.string.search and es.string.split.

Annex B HTML methods. Ugly, but it's also the part of the spec. Modules es.string.anchor, es.string.big, es.string.blink, es.string.bold, es.string.fixed, es.string.fontcolor, es.string.fontsize, es.string.italics, es.string.link, es.string.small, es.string.strike, es.string.sub and es.string.sup.

RegExp features: modules es.regexp.constructor, es.regexp.flags, es.regexp.sticky and es.regexp.test.

class String {
  static fromCodePoint(...codePoints: Array<number>): string;
  static raw({ raw: Array<string> }, ...substitutions: Array<string>): string;
  split(separator: string, limit?: number): Array<string>;
  includes(searchString: string, position?: number): boolean;
  startsWith(searchString: string, position?: number): boolean;
  endsWith(searchString: string, position?: number): boolean;
  repeat(count: number): string;
  padStart(length: number, fillStr?: string = ' '): string;
  padEnd(length: number, fillStr?: string = ' '): string;
  codePointAt(pos: number): number | void;
  match(template: any): any; // ES2015+ fix for support @@match
  matchAll(regexp: RegExp): Iterator;
  replace(template: any, replacer: any): any; // ES2015+ fix for support @@replace
  search(template: any): any; // ES2015+ fix for support @@search
  split(template: any, limit: any): any; // ES2015+ fix for support @@split, some fixes for old engines
  trim(): string;
  trimLeft(): string;
  trimRight(): string;
  trimStart(): string;
  trimEnd(): string;
  anchor(name: string): string;
  big(): string;
  blink(): string;
  bold(): string;
  fixed(): string;
  fontcolor(color: string): string;
  fontsize(size: any): string;
  italics(): string;
  link(url: string): string;
  small(): string;
  strike(): string;
  sub(): string;
  sup(): string;
  @@iterator(): Iterator<characters>;
}

class RegExp {
  constructor(pattern: RegExp | string, flags?: string): RegExp; // support of sticky (`y`) flag; can alter flags
  exec(): Array<string | undefined> | null; // IE8 fixes
  test(string: string): boolean; // delegation to `.exec`
  toString(): string; // ES2015+ fix - generic
  @@match(string: string): Array | null;
  @@replace(string: string, replaceValue: Function | string): string;
  @@search(string: string): number;
  @@split(string: string, limit: number): Array<string>;
  readonly attribute flags: string; // IE9+
  readonly attribute sticky: boolean;
}

CommonJS entry points:

core-js(-pure)/es|stable|features/string
core-js(-pure)/es|stable|features/string/from-code-point
core-js(-pure)/es|stable|features/string/raw
core-js(-pure)/es|stable|features/string/code-point-at
core-js(-pure)/es|stable|features/string/ends-with
core-js(-pure)/es|stable|features/string/includes
core-js(-pure)/es|stable|features/string/starts-with
core-js/es|stable|features/string/match
core-js(-pure)/es|stable|features/string/match-all
core-js(-pure)/es|stable|features/string/repeat
core-js(-pure)/es|stable|features/string/pad-start
core-js(-pure)/es|stable|features/string/pad-end
core-js/es|stable|features/string/replace
core-js/es|stable|features/string/search
core-js/es|stable|features/string/split
core-js(-pure)/es|stable|features/string/trim
core-js(-pure)/es|stable|features/string/trim-start
core-js(-pure)/es|stable|features/string/trim-end
core-js(-pure)/es|stable|features/string/trim-left
core-js(-pure)/es|stable|features/string/trim-right
core-js(-pure)/es|stable|features/string/anchor
core-js(-pure)/es|stable|features/string/big
core-js(-pure)/es|stable|features/string/blink
core-js(-pure)/es|stable|features/string/bold
core-js(-pure)/es|stable|features/string/fixed
core-js(-pure)/es|stable|features/string/fontcolor
core-js(-pure)/es|stable|features/string/fontsize
core-js(-pure)/es|stable|features/string/italics
core-js(-pure)/es|stable|features/string/link
core-js(-pure)/es|stable|features/string/small
core-js(-pure)/es|stable|features/string/strike
core-js(-pure)/es|stable|features/string/sub
core-js(-pure)/es|stable|features/string/sup
core-js(-pure)/es|stable|features/string/iterator
core-js(-pure)/es|stable|features/string/virtual/includes
core-js(-pure)/es|stable|features/string/virtual/starts-with
core-js(-pure)/es|stable|features/string/virtual/ends-with
core-js(-pure)/es|stable|features/string/virtual/match-all
core-js(-pure)/es|stable|features/string/virtual/repeat
core-js(-pure)/es|stable|features/string/virtual/pad-start
core-js(-pure)/es|stable|features/string/virtual/pad-end
core-js(-pure)/es|stable|features/string/virtual/code-point-at
core-js(-pure)/es|stable|features/string/virtual/trim
core-js(-pure)/es|stable|features/string/virtual/trim-start
core-js(-pure)/es|stable|features/string/virtual/trim-end
core-js(-pure)/es|stable|features/string/virtual/trim-left
core-js(-pure)/es|stable|features/string/virtual/trim-right
core-js(-pure)/es|stable|features/string/virtual/anchor
core-js(-pure)/es|stable|features/string/virtual/big
core-js(-pure)/es|stable|features/string/virtual/blink
core-js(-pure)/es|stable|features/string/virtual/bold
core-js(-pure)/es|stable|features/string/virtual/fixed
core-js(-pure)/es|stable|features/string/virtual/fontcolor
core-js(-pure)/es|stable|features/string/virtual/fontsize
core-js(-pure)/es|stable|features/string/virtual/italics
core-js(-pure)/es|stable|features/string/virtual/link
core-js(-pure)/es|stable|features/string/virtual/small
core-js(-pure)/es|stable|features/string/virtual/strike
core-js(-pure)/es|stable|features/string/virtual/sub
core-js(-pure)/es|stable|features/string/virtual/sup
core-js(-pure)/es|stable|features/string/virtual/iterator
core-js/es|stable|features/regexp
core-js/es|stable|features/regexp/constructor
core-js(-pure)/es|stable|features/regexp/flags
core-js/es|stable|features/regexp/sticky
core-js/es|stable|features/regexp/test
core-js/es|stable|features/regexp/to-string

Examples:

for (let value of 'a𠮷b') {
  console.log(value); // => 'a', '𠮷', 'b'
}

'foobarbaz'.includes('bar');      // => true
'foobarbaz'.includes('bar', 4);   // => false
'foobarbaz'.startsWith('foo');    // => true
'foobarbaz'.startsWith('bar', 3); // => true
'foobarbaz'.endsWith('baz');      // => true
'foobarbaz'.endsWith('bar', 6);   // => true

'string'.repeat(3); // => 'stringstringstring'

'hello'.padStart(10);         // => '     hello'
'hello'.padStart(10, '1234'); // => '12341hello'
'hello'.padEnd(10);           // => 'hello     '
'hello'.padEnd(10, '1234');   // => 'hello12341'

'𠮷'.codePointAt(0); // => 134071
String.fromCodePoint(97, 134071, 98); // => 'a𠮷b'

let name = 'Bob';
String.raw`Hi\n${name}!`;             // => 'Hi\\nBob!' (ES2015 template string syntax)
String.raw({ raw: 'test' }, 0, 1, 2); // => 't0e1s2t'

'foo'.bold();                     // => '<b>foo</b>'
'bar'.anchor('a"b');              // => '<a name="a&quot;b">bar</a>'
'baz'.link('http://example.com'); // => '<a href="http://example.com">baz</a>'

RegExp(/./g, 'm'); // => /./m

/foo/.flags;    // => ''
/foo/gim.flags; // => 'gim'

RegExp('foo', 'y').sticky; // => true

const text = 'First line\nSecond line';
const regex = RegExp('(\\S+) line\\n?', 'y');

regex.exec(text)[1]; // => 'First'
regex.exec(text)[1]; // => 'Second'
regex.exec(text);    // => null

'foo'.match({ [Symbol.match]: () => 1 });     // => 1
'foo'.replace({ [Symbol.replace]: () => 2 }); // => 2
'foo'.search({ [Symbol.search]: () => 3 });   // => 3
'foo'.split({ [Symbol.split]: () => 4 });     // => 4

RegExp.prototype.toString.call({ source: 'foo', flags: 'bar' }); // => '/foo/bar'

'   hello   '.trimLeft();  // => 'hello   '
'   hello   '.trimRight(); // => '   hello'
'   hello   '.trimStart(); // => 'hello   '
'   hello   '.trimEnd();   // => '   hello'

for (let [_, d, D] of '1111a2b3cccc'.matchAll(/(\d)(\D)/g)) {
  console.log(d, D); // => 1 a, 2 b, 3 c
}

ECMAScript: Number

Module es.number.constructor. Number constructor support binary and octal literals, example:

Number('0b1010101'); // => 85
Number('0o7654321'); // => 2054353

Modules es.number.epsilon, es.number.is-finite, es.number.is-integer, es.number.is-nan, es.number.is-safe-integer, es.number.max-safe-integer, es.number.min-safe-integer, es.number.parse-float, es.number.parse-int, es.number.to-fixed, es.number.to-precision, es.parse-int, es.parse-float.

class Number {
  constructor(value: any): number;
  toFixed(digits: number): string;
  toPrecision(precision: number): string;
  static isFinite(number: any): boolean;
  static isNaN(number: any): boolean;
  static isInteger(number: any): boolean;
  static isSafeInteger(number: any): boolean;
  static parseFloat(string: string): number;
  static parseInt(string: string, radix?: number = 10): number;
  static EPSILON: number;
  static MAX_SAFE_INTEGER: number;
  static MIN_SAFE_INTEGER: number;
}

function parseFloat(string: string): number;
function parseInt(string: string, radix?: number = 10): number;

CommonJS entry points:

core-js(-pure)/es|stable|features/number
core-js/es|stable|features/number/constructor
core-js(-pure)/es|stable|features/number/is-finite
core-js(-pure)/es|stable|features/number/is-nan
core-js(-pure)/es|stable|features/number/is-integer
core-js(-pure)/es|stable|features/number/is-safe-integer
core-js(-pure)/es|stable|features/number/parse-float
core-js(-pure)/es|stable|features/number/parse-int
core-js(-pure)/es|stable|features/number/epsilon
core-js(-pure)/es|stable|features/number/max-safe-integer
core-js(-pure)/es|stable|features/number/min-safe-integer
core-js(-pure)/es|stable|features/number/to-fixed
core-js(-pure)/es|stable|features/number/to-precision
core-js(-pure)/es|stable|features/parse-float
core-js(-pure)/es|stable|features/parse-int

ECMAScript: Math

Modules es.math.acosh, es.math.asinh, es.math.atanh, es.math.cbrt, es.math.clz32, es.math.cosh, es.math.expm1, es.math.fround, es.math.hypot, es.math.imul, es.math.log10, es.math.log1p, es.math.log2, es.math.sign, es.math.sinh, es.math.tanh, es.math.trunc.

namespace Math {
  acosh(number: number): number;
  asinh(number: number): number;
  atanh(number: number): number;
  cbrt(number: number): number;
  clz32(number: number): number;
  cosh(number: number): number;
  expm1(number: number): number;
  fround(number: number): number;
  hypot(...args: Array<number>): number;
  imul(number1: number, number2: number): number;
  log1p(number: number): number;
  log10(number: number): number;
  log2(number: number): number;
  sign(number: number): 1 | -1 | 0 | -0 | NaN;
  sinh(number: number): number;
  tanh(number: number): number;
  trunc(number: number): number;
}

CommonJS entry points:

core-js(-pure)/es|stable|features/math
core-js(-pure)/es|stable|features/math/acosh
core-js(-pure)/es|stable|features/math/asinh
core-js(-pure)/es|stable|features/math/atanh
core-js(-pure)/es|stable|features/math/cbrt
core-js(-pure)/es|stable|features/math/clz32
core-js(-pure)/es|stable|features/math/cosh
core-js(-pure)/es|stable|features/math/expm1
core-js(-pure)/es|stable|features/math/fround
core-js(-pure)/es|stable|features/math/hypot
core-js(-pure)/es|stable|features/math/imul
core-js(-pure)/es|stable|features/math/log1p
core-js(-pure)/es|stable|features/math/log10
core-js(-pure)/es|stable|features/math/log2
core-js(-pure)/es|stable|features/math/sign
core-js(-pure)/es|stable|features/math/sinh
core-js(-pure)/es|stable|features/math/tanh
core-js(-pure)/es|stable|features/math/trunc

ECMAScript: Date

Modules es.date.to-string, ES5 features with fixes: es.date.now, es.date.to-iso-string, es.date.to-json and es.date.to-primitive.

class Date {
  toISOString(): string;
  toJSON(): string;
  toString(): string;
  @@toPrimitive(hint: 'default' | 'number' | 'string'): string | number;
  static now(): number;
}

CommonJS entry points:

core-js/es|stable|features/date
core-js/es|stable|features/date/to-string
core-js(-pure)/es|stable|features/date/now
core-js(-pure)/es|stable|features/date/to-iso-string
core-js(-pure)/es|stable|features/date/to-json
core-js(-pure)/es|stable|features/date/to-primitive

Example:

new Date(NaN).toString(); // => 'Invalid Date'

ECMAScript: Promise

Modules es.promise, es.promise.all-settled and es.promise.finally.

class Promise {
  constructor(executor: (resolve: Function, reject: Function) => void): Promise;
  then(onFulfilled: Function, onRejected: Function): Promise;
  catch(onRejected: Function): Promise;
  finally(onFinally: Function): Promise;
  static resolve(x: any): Promise;
  static reject(r: any): Promise;
  static all(iterable: Iterable): Promise;
  static allSettled(iterable: Iterable): Promise;
  static race(iterable: Iterable): Promise;
}

CommonJS entry points:

core-js(-pure)/es|stable|features/promise
core-js(-pure)/es|stable|features/promise/all-settled
core-js(-pure)/es|stable|features/promise/finally

Basic example:

function sleepRandom(time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time * 1e3, 0 | Math.random() * 1e3);
  });
}

console.log('Run');                    // => Run
sleepRandom(5).then(result => {
  console.log(result);                 // => 869, after 5 sec.
  return sleepRandom(10);
}).then(result => {
  console.log(result);                 // => 202, after 10 sec.
}).then(() => {
  console.log('immediately after');    // => immediately after
  throw Error('Irror!');
}).then(() => {
  console.log('will not be displayed');
}).catch(x => console.log(x));         // => => Error: Irror!

Promise.resolve and Promise.reject example:

Promise.resolve(42).then(x => console.log(x)); // => 42
Promise.reject(42).catch(x => console.log(x)); // => 42

Promise.resolve($.getJSON('/data.json')); // => ES promise

Promise#finally example:

Promise.resolve(42).finally(() => console.log('You will see it anyway'));

Promise.reject(42).finally(() => console.log('You will see it anyway'));

Promise.all example:

Promise.all([
  'foo',
  sleepRandom(5),
  sleepRandom(15),
  sleepRandom(10)             // after 15 sec:
]).then(x => console.log(x)); // => ['foo', 956, 85, 382]

Promise.race example:

function timeLimit(promise, time) {
  return Promise.race([promise, new Promise((resolve, reject) => {
    setTimeout(reject, time * 1e3, Error('Await > ' + time + ' sec'));
  })]);
}

timeLimit(sleepRandom(5), 10).then(x => console.log(x));   // => 853, after 5 sec.
timeLimit(sleepRandom(15), 10).catch(x => console.log(x)); // Error: Await > 10 sec

Promise.allSettled example:

Promise.allSettled([
  Promise.resolve(1),
  Promise.reject(2),
  Promise.resolve(3),
]).then(console.log); // => [{ value: 1, status: 'fulfilled' }, { reason: 2, status: 'rejected' }, { value: 3, status: 'fulfilled' }]

Example with async functions:

let delay = time => new Promise(resolve => setTimeout(resolve, time))

async function sleepRandom(time) {
  await delay(time * 1e3);
  return 0 | Math.random() * 1e3;
}

async function sleepError(time, msg) {
  await delay(time * 1e3);
  throw Error(msg);
}

(async () => {
  try {
    console.log('Run');                // => Run
    console.log(await sleepRandom(5)); // => 936, after 5 sec.
    let [a, b, c] = await Promise.all([
      sleepRandom(5),
      sleepRandom(15),
      sleepRandom(10)
    ]);
    console.log(a, b, c);              // => 210 445 71, after 15 sec.
    await sleepError(5, 'Error!');
    console.log('Will not be displayed');
  } catch (e) {
    console.log(e);                    // => Error: 'Error!', after 5 sec.
  }
})();
Unhandled rejection tracking

In Node.js, like in native implementation, available events unhandledRejection and rejectionHandled:

process.on('unhandledRejection', (reason, promise) => console.log('unhandled', reason, promise));
process.on('rejectionHandled', (promise) => console.log('handled', promise));

let promise = Promise.reject(42);
// unhandled 42 [object Promise]

setTimeout(() => promise.catch(() => {}), 1e3);
// handled [object Promise]

In a browser on rejection, by default, you will see notify in the console, or you can add a custom handler and a handler on handling unhandled, example:

window.addEventListener('unhandledrejection', e => console.log('unhandled', e.reason, e.promise));
window.addEventListener('rejectionhandled', e => console.log('handled', e.reason, e.promise));
// or
window.onunhandledrejection = e => console.log('unhandled', e.reason, e.promi
0.1.1

4 years ago

0.1.0

4 years ago