Giter Site home page Giter Site logo

core-js's Introduction

core-js

Gitter

Modular compact standard library for JavaScript. Includes polyfills for ECMAScript 5, ECMAScript 6: symbols, collections, iterators, promises, ECMAScript 7 proposals; setImmediate, array generics. Some additional features such as dictionaries, extended partial application, console cap, date formatting. You can require only standardized features polyfills, use features without global namespace pollution or create a custom build.

Example:

Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
'*'.repeat(10);                       // => '**********'
Promise.resolve(32).then(log);        // => 32
setImmediate(log, 42);                // => 42

Without global namespace pollution:

var core = require('core-js/library'); // With a modular system, otherwise use global `core`
core.Array.from(new core.Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
core.String.repeat('*', 10);                    // => '**********'
core.Promise.resolve(32).then(core.log);        // => 32
core.setImmediate(core.log, 42);                // => 42

NPM

Usage

Basic

npm i core-js
bower install core.js
// Default
require('core-js');
// Without global namespace pollution
var core = require('core-js/library');
// Shim only
require('core-js/shim');

If you need support IE8- or need complete build for browser, use builds from core-js/client path: default, without global namespace pollution, shim only.

CommonJS

You can require only needed modules. Warning! It's an experimental feature, API can be changed.

require('core-js/es5'); // if you need support IE8-, require `es5` before other modules
require('core-js/es6/collections');
require('core-js/es6/array/statics');
Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]

// or, w/o global namespace pollution:

var core = require('core-js/as-library');
require('core-js/es5');
require('core-js/es6/collections');
require('core-js/es6/array/statics');
core.Array.from(new core.Set([1, 2, 3, 2, 1])); // => [1, 2, 3]

Available namespaces: for example, core-js/es6/array contains es6.array.statics and es6.array.prototype modules, core-js/es6 contains all modules whose names start with es6.

Caveat: if you uses core-js with extension of native objects, require all needed core-js modules at the beginning of entry point of your application, otherwise possible conflicts.

Custom build

npm i -g grunt-cli
npm i core-js
cd node_modules/core-js && npm i
grunt build:core.dict,es6 --blacklist=es6.promise,es6.math --library=on --path=custom uglify

Where core.dict and es6 are modules (namespaces) names, which will be added to the build, es6.promise and es6.math are modules (namespaces) names, which will be excluded from the build, --library=on is flag for build without global namespace pollution and custom is target file name.

Available namespaces: for example, es6.array contains es6.array.statics and es6.array.prototype modules, es6 contains all modules whose names start with es6.

API:

ECMAScript 5

Module es5, nothing new - without examples.

Object
  .create(proto | null, descriptors?) -> object
  .getPrototypeOf(object) -> proto | null
  .defineProperty(target, key, desc) -> target, cap for ie8-
  .defineProperties(target, descriptors) -> target, cap for ie8-
  .getOwnPropertyDescriptor(object, key) -> desc
  .getOwnPropertyNames(object) -> array
  .seal(object) -> object, cap for ie8-
  .freeze(object) -> object, cap for ie8-
  .preventExtensions(object) -> object, cap for ie8-
  .isSealed(object) -> bool, cap for ie8-
  .isFrozen(object) -> bool, cap for ie8-
  .isExtensible(object) -> bool, cap for ie8-
  .keys(object) -> array
Array
  .isArray(var) -> bool
  #slice(start?, end?) -> array, fix for ie7-
  #join(string = ',') -> string, fix for ie7-
  #indexOf(var, from?) -> int
  #lastIndexOf(var, from?) -> int
  #every(fn(val, index, @), that) -> bool
  #some(fn(val, index, @), that) -> bool
  #forEach(fn(val, index, @), that) -> void
  #map(fn(val, index, @), that) -> array
  #filter(fn(val, index, @), that) -> array
  #reduce(fn(memo, val, index, @), memo?) -> var
  #reduceRight(fn(memo, val, index, @), memo?) -> var
Function
  #bind(object, ...args) -> boundFn(...args)
String
  #trim() -> str
Date
  .now() -> int
  #toISOString() -> string

ECMAScript 6

ECMAScript 6: Object

Modules es6.object.statics, es6.object.prototype and es6.function.

Object
  .assign(target, ...src) -> target
  .is(a, b) -> bool
  .setPrototypeOf(target, proto | null) -> target, sham (required __proto__)
  #toString() -> string, ES6 fix: @@toStringTag support
Function
  #name -> string (IE9+)

Example:

var foo = {q: 1, w: 2}
  , bar = {e: 3, r: 4}
  , 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

var O = {};
O[Symbol.toStringTag] = 'Foo';
'' + O; // => '[object Foo]'

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

Module es6.object.statics-accept-primitives. In ES6 most Object static methods should work with primitives. Example:

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

ECMAScript 6: Array

Modules es6.array.statics and es6.array.prototype.

Array
  .from(iterable | array-like, mapFn(val, index)?, that) -> array
  .of(...args) -> array
  #copyWithin(target = 0, start = 0, end = @length) -> @
  #fill(val, start = 0, end = @length) -> @
  #find(fn(val, index, @), that) -> val
  #findIndex(fn(val, index, @), that) -> index
  #@@unscopables -> object (cap)

Example:

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', function(it){
  return it * it;
});                                        // => [1, 4, 9]

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

function isOdd(val){
  return val % 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]

ECMAScript 6: String & RegExp

Modules es6.string and es6.regexp.

String
  .fromCodePoint(...codePoints) -> str
  .raw({raw}, ...substitutions) -> str
  #includes(str, from?) -> bool
  #startsWith(str, from?) -> bool
  #endsWith(str, from?) -> bool
  #repeat(num) -> str
  #codePointAt(pos) -> uint
[new] RegExp(pattern, flags?) -> regexp, ES6 fix: can alter flags
  #flags -> str (IE9+)

Example:

'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'

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

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

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

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

ECMAScript 6: Number & Math

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

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

Modules es6.number.statics and es6.math.

Number
  .EPSILON -> num
  .isFinite(num) -> bool
  .isInteger(num) -> bool
  .isNaN(num) -> bool
  .isSafeInteger(num) -> bool
  .MAX_SAFE_INTEGER -> int
  .MIN_SAFE_INTEGER -> int
  .parseFloat(str) -> num
  .parseInt(str) -> int
Math
  .acosh(num) -> num
  .asinh(num) -> num
  .atanh(num) -> num
  .cbrt(num) -> num
  .clz32(num) -> uint
  .cosh(num) -> num
  .expm1(num) -> num
  .fround(num) -> num (IE10+)
  .hypot(...args) -> num
  .imul(num, num) -> int
  .log1p(num) -> num
  .log10(num) -> num
  .log2(num) -> num
  .sign(num) -> 1 | -1 | 0 | -0 | NaN
  .sinh(num) -> num
  .tanh(num) -> num
  .trunc(num) -> num

ECMAScript 6: Symbols

Module es6.symbol.

Symbol(description?) -> symbol
  .hasInstance -> @@hasInstance
  .isConcatSpreadable -> @@isConcatSpreadable
  .iterator -> @@iterator
  .match -> @@match
  .replace -> @@replace
  .search -> @@search
  .species -> @@species
  .split -> @@split
  .toPrimitive -> @@toPrimitive
  .toStringTag -> @@toStringTag
  .unscopables -> @@unscopables
  .for(key) -> symbol
  .keyFor(symbol) -> key
  .useSimple() -> void
  .useSetter() -> void
  .pure(description?) -> symbol || string
  .set(object, key, val) -> object
Object
  .getOwnPropertySymbols(object) -> array

Basic example:

var Person = (function(){
  var NAME = Symbol('name');
  function Person(name){
    this[NAME] = name;
  }
  Person.prototype.getName = function(){
    return this[NAME];
  };
  return Person;
})();

var person = new Person('Vasya');
log(person.getName());          // => 'Vasya'
log(person['name']);            // => undefined
log(person[Symbol('name')]);    // => undefined, symbols are uniq
for(var key in person)log(key); // => only 'getName', symbols are not enumerable

Symbol.for & Symbol.keyFor example:

var symbol = Symbol.for('key');
symbol === Symbol.for('key'); // true
Symbol.keyFor(symbol);        // 'key'

Example with methods for getting own object keys:

var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Object.keys(O);                  // => ['a']
Object.getOwnPropertyNames(O);   // => ['a', 'b']
Object.getOwnPropertySymbols(O); // => [Symbol(c)]
Reflect.ownKeys(O);              // => ['a', 'b', Symbol(c)]

Caveats when using Symbol polyfill:

  • We can't add new primitive type, Symbol returns object.
  • By default, to hide the keys, Symbol polyfill defines setter in Object.prototype. For this reason, the in operator is not working correctly with Symbol polyfill: Symbol() in {} // => true.

You can disable defining setter in Object.prototype. Example:

Symbol.useSimple();
var s1 = Symbol('s1')
  , o1 = {};
o1[s1] = true;
for(var key in o1)log(key); // => 'Symbol(s1)_t.qamkg9f3q', w/o native Symbol

Symbol.useSetter();
var s2 = Symbol('s2')
  , o2 = {};
o2[s2] = true;
for(var key in o2)log(key); // nothing

ECMAScript 6: Collections

Module es6.collections. About iterators from this module here.

Map

new Map(iterable (entries) ?) -> map
  #clear() -> void
  #delete(key) -> bool
  #forEach(fn(val, key, @), that) -> void
  #get(key) -> val
  #has(key) -> bool
  #set(key, val) -> @
  #size -> uint

Example:

var a = [1];

var map = new Map([['a', 1], [42, 2]]);
map.set(a, 3).set(true, 4);

log(map.size);        // => 4
log(map.has(a));      // => true
log(map.has([1]));    // => false
log(map.get(a));      // => 3
map.forEach(function(val, key){
  log(val);           // => 1, 2, 3, 4
  log(key);           // => 'a', 42, [1], true
});
map.delete(a);
log(map.size);        // => 3
log(map.get(a));      // => undefined
log(Array.from(map)); // => [['a', 1], [42, 2], [true, 4]]

Set

new Set(iterable?) -> set
  #add(key) -> @
  #clear() -> void
  #delete(key) -> bool
  #forEach(fn(el, el, @), that) -> void
  #has(key) -> bool
  #size -> uint

Example:

var set = new Set(['a', 'b', 'a', 'c']);
set.add('d').add('b').add('e');
log(set.size);        // => 5
log(set.has('b'));    // => true
set.forEach(function(it){
  log(it);            // => 'a', 'b', 'c', 'd', 'e'
});
set.delete('b');
log(set.size);        // => 4
log(set.has('b'));    // => false
log(Array.from(set)); // => ['a', 'c', 'd', 'e']

WeakMap

new WeakMap(iterable (entries) ?) -> weakmap
  #delete(key) -> bool
  #get(key) -> val
  #has(key) -> bool
  #set(key, val) -> @

Example:

var a = [1]
  , b = [2]
  , c = [3];

var wmap = new WeakMap([[a, 1], [b, 2]]);
wmap.set(c, 3).set(b, 4);
log(wmap.has(a));   // => true
log(wmap.has([1])); // => false
log(wmap.get(a));   // => 1
wmap.delete(a);
log(wmap.get(a));   // => undefined

// Private properties store:
var Person = (function(){
  var names = new WeakMap;
  function Person(name){
    names.set(this, name);
  }
  Person.prototype.getName = function(){
    return names.get(this);
  };
  return Person;
})();

var person = new Person('Vasya');
log(person.getName());          // => 'Vasya'
for(var key in person)log(key); // => only 'getName'

WeakSet

new WeakSet(iterable?) -> weakset
  #add(key) -> @
  #delete(key) -> bool
  #has(key) -> bool

Example:

var a = [1]
  , b = [2]
  , c = [3];

var wset = new WeakSet([a, b, a]);
wset.add(c).add(b).add(c);
log(wset.has(b));   // => true
log(wset.has([2])); // => false
wset.delete(b);
log(wset.has(b));   // => false

Caveats when using collections polyfill:

  • Frozen objects as collection keys are supported, but not recomended - it's slow (O(n) instead of O(1)) and, for weak-collections, leak.
  • Weak-collections polyfill stores values as hidden properties of keys. It works correct and not leak in most cases. However, it is desirable to store a collection longer than its keys.

ECMAScript 6: Iterators

Module es6.iterators:

String
  #@@iterator() -> iterator
Array
  #values() -> iterator
  #keys() -> iterator
  #entries() -> iterator (entries)
  #@@iterator() -> iterator
Arguments
  #@@iterator() -> iterator (sham, available only in core-js methods)

Module es6.collections:

Set
  #values() -> iterator
  #keys() -> iterator
  #entries() -> iterator (entries)
  #@@iterator() -> iterator
Map
  #values() -> iterator
  #keys() -> iterator
  #entries() -> iterator (entries)
  #@@iterator() -> iterator (entries)

Module web.dom.iterable:

NodeList
  #@@iterator() -> iterator

Example:

var string = 'a๐ ฎทb';

for(var val of string)log(val);         // => 'a', '๐ ฎท', 'b'

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

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

var map = new Map([['a', 1], ['b', 2], ['c', 3]]);

for(var [key, val] of map){
  log(key);                             // => 'a', 'b', 'c'
  log(val);                             // => 1, 2, 3
}
for(var val of map.values())log(val);   // => 1, 2, 3
for(var key of map.keys())log(key);     // => 'a', 'b', 'c'
for(var [key, val] of map.entries()){
  log(key);                             // => 'a', 'b', 'c'
  log(val);                             // => 1, 2, 3
}

var set = new Set([1, 2, 3, 2, 1]);

for(var val of set)log(val);            // => 1, 2, 3
for(var val of set.values())log(val);   // => 1, 2, 3
for(var key of set.keys())log(key);     // => 1, 2, 3
for(var [key, val] of set.entries()){
  log(key);                             // => 1, 2, 3
  log(val);                             // => 1, 2, 3
}

for(var x of document.querySelectorAll('*')){
  log(x.id);
}

Module core.$for - iterators chaining - for-of and array / generator comprehensions helpers for ES5- syntax.

$for(iterable, entries) -> iterator ($for)
  #of(fn(value, key?), that) -> void
  #array(mapFn(value, key?)?, that) -> array
  #filter(fn(value, key?), that) -> iterator ($for)
  #map(fn(value, key?), that) -> iterator ($for)
  .isIterable(var) -> bool
  .getIterator(iterable) -> iterator

Examples:

$for(new Set([1, 2, 3, 2, 1])).of(function(it){
  log(it); // => 1, 2, 3
});

$for([1, 2, 3].entries(), true).of(function(key, value){
  log(key);   // => 0, 1, 2
  log(value); // => 1, 2, 3
});

$for('abc').of(console.log, console); // => 'a', 'b', 'c'

$for([1, 2, 3, 4, 5]).of(function(it){
  log(it); // => 1, 2, 3
  if(it == 3)return false;
});

var ar1 = $for([1, 2, 3]).array(function(v){
  return v * v;
}); // => [1, 4, 9]

var set = new Set([1, 2, 3, 2, 1]);
var ar1 = $for(set).filter(function(v){
  return v % 2;
}).array(function(v){
  return v * v;
}); // => [1, 9]

var iter = $for(set).filter(function(v){
  return v % 2;
}).map(function(v){
  return v * v;
});
iter.next(); // => {value: 1, done: false}
iter.next(); // => {value: 9, done: false}
iter.next(); // => {value: undefined, done: true}

var map1 = new Map([['a', 1], ['b', 2], ['c', 3]]);
var map2 = new Map($for(map1, true).filter(function(k, v){
  return v % 2;
}).map(function(k, v){
  return [k + k, v * v];
})); // => Map {aa: 1, cc: 9}

ECMAScript 6: Promises

Module es6.promise.

new Promise(executor(resolve(var), reject(var))) -> promise
  #then(resolved(var), rejected(var)) -> promise
  #catch(rejected(var)) -> promise
  .resolve(var || promise) -> promise
  .reject(var) -> promise
  .all(iterable) -> promise
  .race(iterable) -> promise

Basic example:

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

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

Promise.resolve and Promise.reject example:

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

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

Promise.all example:

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

Promise.race example:

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

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

ECMAScript 7 async functions example:

var 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 {
    log('Run');                // => Run
    log(await sleepRandom(5)); // => 936, after 5 sec.
    var [a, b, c] = await Promise.all([
      sleepRandom(5),
      sleepRandom(15),
      sleepRandom(10)
    ]);
    log(a, b, c);              // => 210 445 71, after 15 sec.
    await sleepError(5, 'Irror!');
    log('Will not be displayed');
  } catch(e){
    log(e);                    // => Error: 'Irror!', after 5 sec.
  }
})();

ECMAScript 6: Reflect

Module es6.reflect.

Reflect
  .apply(target, thisArgument, argumentsList) -> var
  .construct(target, argumentsList, newTarget?) -> object
  .defineProperty(target, propertyKey, attributes) -> bool
  .deleteProperty(target, propertyKey) -> bool
  .enumerate(target) -> iterator
  .get(target, propertyKey, receiver?) -> var
  .getOwnPropertyDescriptor(target, propertyKey) -> desc
  .getPrototypeOf(target) -> object | null
  .has(target, propertyKey) -> bool
  .isExtensible(target) -> bool
  .ownKeys(target) -> array
  .preventExtensions(target) -> bool
  .set(target, propertyKey, V, receiver?) -> bool
  .setPrototypeOf(target, proto) -> bool, sham(ie11+)

Example:

var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Reflect.ownKeys(O); // => ['a', 'b', Symbol(c)]

function C(a, b){
  this.c = a + b;
}

var instance = Reflect.construct(C, [20, 22]);
instance.c; // => 42

ECMAScript 7

Module es7.proposals.

Array
  #includes(var, from?) -> bool
String
  #at(index) -> string
Object
  .values(object) -> array
  .entries(object) -> array
  .getOwnPropertyDescriptors(object) -> object
RegExp
  .escape(str) -> str

Examples:

[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

'a๐ ฎทb'.at(1);        // => '๐ ฎท'
'a๐ ฎทb'.at(1).length; // => 2

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]]

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

RegExp.escape('Hello -[]{}()*+?.,\\^$|'); // => 'Hello \-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|'

ECMAScript 7: Abstract References

Module es7.abstract-refs. Symbols and methods for abstract references. At the moment, they are supported only by several transpilers, such as babel.

Symbol
  .referenceGet -> @@referenceGet
  .referenceSet -> @@referenceSet
  .referenceDelete -> @@referenceDelete
Function
  #@@referenceGet() -> @
Map
  #@@referenceGet ==== #get
  #@@referenceSet ==== #set
  #@@referenceDelete ==== #delete
WeakMap
  #@@referenceGet ==== #get
  #@@referenceSet ==== #set
  #@@referenceDelete ==== #delete

Private properties example with WeakMaps, class and basic abstract refs syntax:

var Person = (NAME => class {
  constructor(name){
    this::NAME = name;
  }
  getName(){
    return this::NAME;
  }
})(new WeakMap);

var person = new Person('Vasya');
log(person.getName());        // => 'Vasya'
log(Reflect.ownKeys(person)); // => []

The same example with the private keyword:

class Person {
  private NAME
  constructor(name){
    this::NAME = name;
  }
  getName(){
    return this::NAME;
  }
}

var person = new Person('Vasya');
log(person.getName());        // => 'Vasya'
log(Reflect.ownKeys(person)); // => []

Virtual methods example:

var {toString} = {};
[]::toString() // => '[object Array]'

function sum(){
  var {reduce} = [];
  return arguments::reduce((a, b)=> a + b);
}
sum(1, 2, 3, 4, 5) // => 15

Virtual size property for dictionaries example:

let size = {
  [Symbol.referenceGet](it){
    return Object.keys(it).length;
  },
  [Symbol.referenceSet](it, length){
    for(let key of Object.keys(it).slice(length))delete it[key];
  }
}

{q: 1, w: 2, e: 3}::size // => 3
var dict = {q: 1, w: 2, e: 3};
dict::size = 2;
dict // => {q: 1, w: 2};

Methods from Dict module override @@referenceGet method, example:

var {filter, map} = Dict;
var dict = {q: 1, w: 2, e: 3}
  ::filter((v, k) => k != 'w')
  ::map(v => v * v); // => {"q":1,"e":9}

Mozilla JavaScript: Array generics

Module js.array.statics.

Array
  .{...ArrayPrototype methods}
Array.slice(arguments, 1);

Array.join('abcdef', '+'); // => 'a+b+c+d+e+f'

var form = document.getElementsByClassName('form__input');
Array.reduce(form, function(memo, it){
  memo[it.name] = it.value;
  return memo;
}, {}); // => {name: 'Vasya', age: '42', sex: 'yes, please'}

setTimeout / setInterval

Module web.timers. Additional arguments fix for IE9-.

setTimeout(fn(...args), time, ...args) -> id
setInterval(fn(...args), time, ...args) -> id
// Before:
setTimeout(log.bind(null, 42), 1000);
// After:
setTimeout(log, 1000, 42);

setImmediate

Module web.immediate. setImmediate polyfill.

setImmediate(fn(...args), ...args) -> id
clearImmediate(id) -> void

Example:

setImmediate(function(arg1, arg2){
  log(arg1, arg2); // => Message will be displayed with minimum delay
}, 'Message will be displayed', 'with minimum delay');

clearImmediate(setImmediate(function(){
  log('Message will not be displayed');
}));

Console

Module core.log. Console cap for old browsers and some additional functionality. In IE, Node.js / IO.js and Firebug console methods not require call from console object, but in Chromium and V8 this throws error. For some reason, we can't replace console methods by their bound versions. Add log object with bound console methods. Some more sugar: log is shortcut for log.log, we can disable output.

log ==== log.log
  .{...console API}
  .enable() -> void
  .disable() -> void
// Before:
if(window.console && console.warn)console.warn(42);
// After:
log.warn(42);

// Before:
setTimeout(console.warn.bind(console, 42), 1000);
[1, 2, 3].forEach(console.warn, console);
// After:
setTimeout(log.warn, 1000, 42);
[1, 2, 3].forEach(log.warn);

// log is shortcut for log.log
setImmediate(log, 42); // => 42

log.disable();
log.warn('Console is disabled, you will not see this message.');
log.enable();
log.warn('Console is enabled again.');

Object

Module core.object.

Object
  .isObject(var) -> bool
  .classof(var) -> string 
  .define(target, mixin) -> target
  .make(proto | null, mixin?) -> object

Object classify examples:

Object.isObject({});    // => true
Object.isObject(isNaN); // => true
Object.isObject(null);  // => false

var classof = Object.classof;

classof(null);                 // => 'Null'
classof(undefined);            // => 'Undefined'
classof(1);                    // => 'Number'
classof(true);                 // => 'Boolean'
classof('string');             // => 'String'
classof(Symbol());             // => 'Symbol'

classof(new Number(1));        // => 'Number'
classof(new Boolean(true));    // => 'Boolean'
classof(new String('string')); // => 'String'

var fn   = function(){}
  , list = (function(){return arguments})(1, 2, 3);

classof({});                   // => 'Object'
classof(fn);                   // => 'Function'
classof([]);                   // => 'Array'
classof(list);                 // => 'Arguments'
classof(/./);                  // => 'RegExp'
classof(new TypeError);        // => 'Error'

classof(new Set);              // => 'Set'
classof(new Map);              // => 'Map'
classof(new WeakSet);          // => 'WeakSet'
classof(new WeakMap);          // => 'WeakMap'
classof(new Promise(fn));      // => 'Promise'

classof([].values());          // => 'Array Iterator'
classof(new Set().values());   // => 'Set Iterator'
classof(new Map().values());   // => 'Map Iterator'

classof(Math);                 // => 'Math'
classof(JSON);                 // => 'JSON'

function Example(){}
Example.prototype[Symbol.toStringTag] = 'Example';

classof(new Example);          // => 'Example'

Object.define and Object.make examples:

// Before:
Object.defineProperty(target, 'c', {
  enumerable: true,
  configurable: true,
  get: function(){
    return this.a + this.b;
  }
});

// After:
Object.define(target, {
  get c(){
    return this.a + this.b;
  }
});

// Shallow object cloning with prototype and descriptors:
var copy = Object.make(Object.getPrototypeOf(src), src);

// Simple inheritance:
function Vector2D(x, y){
  this.x = x;
  this.y = y;
}
Object.define(Vector2D.prototype, {
  get xy(){
    return Math.hypot(this.x, this.y);
  }
});
function Vector3D(x, y, z){
  Vector2D.apply(this, arguments);
  this.z = z;
}
Vector3D.prototype = Object.make(Vector2D.prototype, {
  constructor: Vector3D,
  get xyz(){
    return Math.hypot(this.x, this.y, this.z);
  }
});

var vector = new Vector3D(9, 12, 20);
log(vector.xy);  // => 15
log(vector.xyz); // => 25
vector.y++;
log(vector.xy);  // => 15.811388300841896
log(vector.xyz); // => 25.495097567963924

Dict

Module core.dict. Based on TC39 discuss / strawman.

[new] Dict(itarable (entries) | object ?) -> dict
  .isDict(var) -> bool
  .values(object) -> iterator
  .keys(object) -> iterator
  .entries(object) -> iterator (entries)
  .has(object, key) -> bool
  .get(object, key) -> val
  .set(object, key, value) -> object
  .forEach(object, fn(val, key, @), that) -> void
  .map(object, fn(val, key, @), that) -> new @
  .mapPairs(object, fn(val, key, @), that) -> new @
  .filter(object, fn(val, key, @), that) -> new @
  .some(object, fn(val, key, @), that) -> bool
  .every(object, fn(val, key, @), that) -> bool
  .find(object, fn(val, key, @), that) -> val
  .findKey(object, fn(val, key, @), that) -> key
  .keyOf(object, var) -> key
  .includes(object, var) -> bool
  .reduce(object, fn(memo, val, key, @), memo?) -> var
  .turn(object, fn(memo, val, key, @), memo = new @) -> memo

Dict create object without prototype from iterable or simple object. Example:

var map = new Map([['a', 1], ['b', 2], ['c', 3]]);

Dict();                    // => {__proto__: null}
Dict({a: 1, b: 2, c: 3});  // => {__proto__: null, a: 1, b: 2, c: 3}
Dict(map);                 // => {__proto__: null, a: 1, b: 2, c: 3}
Dict([1, 2, 3].entries()); // => {__proto__: null, 0: 1, 1: 2, 2: 3}

var dict = Dict({a: 42});
dict instanceof Object;   // => false
dict.a;                   // => 42
dict.toString;            // => undefined
'a' in dict;              // => true
'hasOwnProperty' in dict; // => false

Dict.isDict({});     // => false
Dict.isDict(Dict()); // => true

Dict.keys, Dict.values and Dict.entries return iterators for objects, examples:

var dict = {a: 1, b: 2, c: 3};

for(var key of Dict.keys(dict))log(key); // => 'a', 'b', 'c'

for(var [key, val] of Dict.entries(dict)){
  log(key); // => 'a', 'b', 'c'
  log(val); // => 1, 2, 3
}

$for(Dict.values(dict)).of(log); // => 1, 2, 3

new Map(Dict.entries(dict)); // => Map {a: 1, b: 2, c: 3}

new Map((for([k, v] of Dict.entries(dict))if(v % 2)[k + k, v * v])); // =>  Map {aa: 1, cc: 9}

Other methods of Dict module are static equialents of Array.prototype methods for dictionaries, examples:

var dict = {a: 1, b: 2, c: 3};

Dict.forEach(dict, console.log, console);
// => 1, 'a', {a: 1, b: 2, c: 3}
// => 2, 'b', {a: 1, b: 2, c: 3}
// => 3, 'c', {a: 1, b: 2, c: 3}

Dict.map(dict, function(it){
  return it * it;
}); // => {a: 1, b: 4, c: 9}

Dict.mapPairs(dict, function(val, key){
  if(key != 'b')return [key + key, val * val];
}); // => {aa: 1, cc: 9}

Dict.filter(dict, function(it){
  return it % 2;
}); // => {a: 1, c: 3}

Dict.some(dict, function(it){
  return it === 2;
}); // => true

Dict.every(dict, function(it){
  return it === 2;
}); // => false

Dict.find(dict, function(it){
  return it > 2;
}); // => 3
Dict.find(dict, function(it){
  return it > 4;
}); // => undefined

Dict.findKey(dict, function(it){
  return it > 2;
}); // => 'c'
Dict.findKey(dict, function(it){
  return it > 4;
}); // => undefined

Dict.keyOf(dict, 2);    // => 'b'
Dict.keyOf(dict, 4);    // => undefined

Dict.includes(dict, 2); // => true
Dict.includes(dict, 4); // => false

Dict.reduce(dict, function(memo, it){
  return memo + it;
});     // => 6
Dict.reduce(dict, function(memo, it){
  return memo + it;
}, ''); // => '123'

Dict.turn(dict, function(memo, it, key){
  memo[key + key] = it;
});     // => {aa: 1, bb: 2, cc: 3}
Dict.turn(dict, function(memo, it, key){
  it % 2 && memo.push(key + it);
}, []); // => ['a1', 'c3']

Partial application

Module core.binding.

Function
  #part(...args | _) -> fn(...args)
  #only(num, that /* = @ */) -> (fn | boundFn)(...args)
Object
  #[_](key) -> boundFn

Function#part partial apply function without this binding. Uses global variable _ (core._ for builds without global namespace pollution) as placeholder and not conflict with Underscore / LoDash. Examples:

var fn1 = log.part(1, 2);
fn1(3, 4);    // => 1, 2, 3, 4

var fn2 = log.part(_, 2, _, 4);
fn2(1, 3);    // => 1, 2, 3, 4

var fn3 = log.part(1, _, _, 4);
fn3(2, 3);    // => 1, 2, 3, 4

fn2(1, 3, 5); // => 1, 2, 3, 4, 5
fn2(1);       // => 1, 2, undefined, 4

Method Object#[_] extracts bound method from object, examples:

['foobar', 'foobaz', 'barbaz'].filter(/bar/[_]('test')); // => ['foobar', 'barbaz']

var has = {}.hasOwnProperty[_]('call');

log(has({key: 42}, 'foo')); // => false
log(has({key: 42}, 'key')); // => true

var array = []
  , push  = array[_]('push');
push(1);
push(2, 3);
log(array); // => [1, 2, 3];

Method Function#only limits number of arguments. Example:

[1, 2, 3].forEach(log.only(1)); // => 1, 2, 3

Date formatting

Module core.date. Much more simple and compact (~60 lines with en & ru locales) than Intl or Moment.js. Use them if you need extended work with Date.

Date
  #format(str, key?) -> str
  #formatUTC(str, key?) -> str
core
  .addLocale(key, object) -> core
  .locale(key?) -> key
Token Unit Sample
s Seconds 0-59
ss Seconds, 2 digits 00-59
m Minutes 0-59
mm Minutes, 2 digits 00-59
h Hours 0-23
hh Hours, 2 digits 00-23
D Date 1-31
DD Date, 2 digits 01-31
W Weekday, string ะ’ั‚ะพั€ะฝะธะบ
N Month 1-12
NN Month, 2 digits 01-12
M Month, string ะะพัะฑั€ัŒ
MM Of month, string ะะพัะฑั€ั
Y Year, full 2014
YY Year, 2 digits 14
Examples:
new Date().format('W, MM D, YY, h:mm:ss');        // => 'Friday, November 28, 14, 18:47:05'
new Date().formatUTC('W, MM D, YY, h:mm:ss');     // => 'Friday, November 28, 14, 12:47:05'

new Date().format('W, D MM Y ะณ., h:mm:ss', 'ru'); // => 'ะŸัั‚ะฝะธั†ะฐ, 28 ะะพัะฑั€ั 2014 ะณ., 18:07:25'

core.locale('ru');
new Date().format('W, D MM Y ะณ., h:mm:ss');       // => 'ะŸัั‚ะฝะธั†ะฐ, 28 ะะพัะฑั€ั 2014 ะณ., 18:07:25'

new Date().format('DD.NN.YY');         // => '28.11.14'
new Date().format('hh:mm:ss');         // => '18:47:05'
new Date().format('DD.NN.Y hh:mm:ss'); // => '28.11.2014 18:47:05'
new Date().format('W, D MM Y ะณะพะดะฐ');   // => 'ะŸัั‚ะฝะธั†ะฐ, 28 ะะพัะฑั€ั 2014 ะณะพะดะฐ'
new Date().format('D MM, h:mm');       // => '28 ะะพัะฑั€ั, 16:47'
new Date().format('M Y');              // => 'ะะพัะฑั€ัŒ 2014'

(typeof core != 'undefined' ? core : require('core-js/library')).addLocale('ru', {
  weekdays: 'ะ’ะพัะบั€ะตัะตะฝัŒะต,ะŸะพะฝะตะดะตะปัŒะฝะธะบ,ะ’ั‚ะพั€ะฝะธะบ,ะกั€ะตะดะฐ,ะงะตั‚ะฒะตั€ะณ,ะŸัั‚ะฝะธั†ะฐ,ะกัƒะฑะฑะพั‚ะฐ',
  months: 'ะฏะฝะฒะฐั€:ั|ัŒ,ะคะตะฒั€ะฐะป:ั|ัŒ,ะœะฐั€ั‚:ะฐ|,ะะฟั€ะตะป:ั|ัŒ,ะœะฐ:ั|ะน,ะ˜ัŽะฝ:ั|ัŒ,ะ˜ัŽะป:ั|ัŒ,ะะฒะณัƒัั‚:ะฐ|,ะกะตะฝั‚ัะฑั€:ั|ัŒ,ะžะบั‚ัะฑั€:ั|ัŒ,ะะพัะฑั€:ั|ัŒ,ะ”ะตะบะฐะฑั€:ั|ัŒ'
});

Array

Module core.array.

Array
  #turn(fn(memo, val, index, @), memo = []) -> memo

Method Array#turn reduce array to object, example:

[1, 2, 3, 4, 5].turn(function(memo, it){
  memo['key' + it] = !!(it % 2);
}, {}); // => {key1: true, key2: false, key3: true, key4: false, key5: true}

[1, 2, 3, 4, 5, 6, 7, 8, 9].turn(function(memo, it){
  it % 2 && memo.push(it * it);
  if(memo.length == 3)return false;
}); // => [1, 9, 25]

Number

Module core.number.

Number
  #@@iterator() -> iterator
  #random(lim = 0) -> num
  #{...Math} 

Number Iterator examples:

for(var i of 3)log(i); // => 0, 1, 2

$for(3).of(log); // => 0, 1, 2

Array.from(10, Math.random); // => [0.9817775336559862, 0.02720663254149258, ...]

Array.from(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.from(10, function(it){
  return this + it * it;
}, .42); // => [0.42, 1.42, 4.42, 9.42, 16.42, 25.42, 36.42, 49.42, 64.42, 81.42]

// Comprehensions:
[for(i of 10)if(i % 2)i * i]; // => [1, 9, 25, 49, 81]

Dict((for(i of 3)['key' + i, !(i % 2)])); // => {key0: true, key1: false, key2: true}

$for(10).filter(function(i){
  return i % 2;
}).array(function(i){
  return i * i;
});  // => [1, 9, 25, 49, 81]

Dict($for(3).map(function(i){
  return ['key' + i, !(i % 2)];
})); // => {key0: true, key1: false, key2: true}

Math methods in Number.prototype examples:

3..pow(3);           // => 27
(-729).abs().sqrt(); // => 27

10..random(20);         // => Random number (10, 20), for example, 16.818793776910752
10..random(20).floor(); // => Random integer [10, 19], for example, 16

var array = [1, 2, 3, 4, 5];
array[array.length.random().floor()]; // => Random element, for example, 4

Escaping characters

Module core.string.

String
  #escapeHTML() -> str
  #unescapeHTML() -> str

Examples:

'<script>doSomething();</script>'.escapeHTML(); // => '&lt;script&gt;doSomething();&lt;/script&gt;'
'&lt;script&gt;doSomething();&lt;/script&gt;'.unescapeHTML(); // => '<script>doSomething();</script>'

delay

Module core.delay. Promise-returning delay function, esdiscuss. Example:

delay(1e3).then(() => log('after 1 sec'));

(async () => {
  await delay(3e3);
  log('after 3 sec');
  
  while(await delay(3e3))log('each 3 sec');
})();

Changelog

0.7.2 - 2015.03.09
  • some fixes
0.7.1 - 2015.03.07
  • some fixes
0.7.0 - 2015.03.06
0.6.1 - 2015.02.24
0.6.0 - 2015.02.23
  • added support safe closing iteration - calling iterator.return on abort iteration, if it exists
  • added basic support Promise unhandled rejection tracking in shim
  • added Object.getOwnPropertyDescriptors
  • removed console cap - creates too many problems - you can use core.log module as that
  • restructuring namespaces
  • some fixes
0.5.4 - 2015.02.15
  • some fixes
0.5.3 - 2015.02.14
0.5.2 - 2015.02.10
  • some fixes
0.5.1 - 2015.02.09
  • some fixes
0.5.0 - 2015.02.08
  • systematization of modules
  • splitted es6 module
  • splitted console module: web.console - only cap for missing methods, core.log - bound methods & additional features
  • added delay method
  • some fixes
0.4.10 - 2015.01.28
0.4.9 - 2015.01.27
  • FF20-24 fix
0.4.8 - 2015.01.25
0.4.7 - 2015.01.25
0.4.6 - 2015.01.21
0.4.5 - 2015.01.16
  • some fixes
0.4.4 - 2015.01.11
  • enabled CSP support
0.4.3 - 2015.01.10
  • added Function instances name property for IE9+
0.4.2 - 2015.01.10
  • Object static methods accept primitives
  • RegExp constructor can alter flags (IE9+)
  • added Array.prototype[Symbol.unscopables]
0.4.1 - 2015.01.05
  • some fixes
0.4.0 - 2015.01.03
  • added es6.reflect module:
    • added Reflect.apply
    • added Reflect.construct
    • added Reflect.defineProperty
    • added Reflect.deleteProperty
    • added Reflect.enumerate
    • added Reflect.get
    • added Reflect.getOwnPropertyDescriptor
    • added Reflect.getPrototypeOf
    • added Reflect.has
    • added Reflect.isExtensible
    • added Reflect.preventExtensions
    • added Reflect.set
    • added Reflect.setPrototypeOf
  • core-js methods now can use external Symbol.iterator polyfill
  • some fixes
0.3.3 - 2014.12.28
0.3.2 - 2014.12.25
  • added cap for ES5 freeze-family methods
  • fixed console bug
0.3.1 - 2014.12.23
  • some fixes
0.3.0 - 2014.12.23
0.2.5 - 2014.12.20
  • console no longer shortcut for console.log (compatibility problems)
  • some fixes
0.2.4 - 2014.12.17
  • better compliance of ES6
  • added Math.fround (IE10+)
  • some fixes
0.2.3 - 2014.12.15
  • Symbols:
    • added option to disable addition setter to Object.prototype for Symbol polyfill:
      • added Symbol.useSimple
      • added Symbol.useSetter
    • added cap for well-known Symbols:
      • added Symbol.hasInstance
      • added Symbol.isConcatSpreadable
      • added Symbol.match
      • added Symbol.replace
      • added Symbol.search
      • added Symbol.species
      • added Symbol.split
      • added Symbol.toPrimitive
      • added Symbol.unscopables
0.2.2 - 2014.12.13
0.2.1 - 2014.12.12
0.2.0 - 2014.12.06
  • added es7.proposals and es7.abstract-refs modules
  • added String#at
  • added real String Iterator, older versions used Array Iterator
  • added abstract references support:
    • added Symbol.referenceGet
    • added Symbol.referenceSet
    • added Symbol.referenceDelete
    • added Function#@@referenceGet
    • added Map#@@referenceGet
    • added Map#@@referenceSet
    • added Map#@@referenceDelete
    • added WeakMap#@@referenceGet
    • added WeakMap#@@referenceSet
    • added WeakMap#@@referenceDelete
    • added Dict.{...methods}[@@referenceGet]
  • removed deprecated .contains methods
  • some fixes
0.1.5 - 2014.12.01
0.1.4 - 2014.11.27
0.1.3 - 2014.11.20
0.1.2 - 2014.11.19
  • Map & Set bug fix
0.1.1 - 2014.11.18
  • public release

core-js's People

Contributors

felixbuenemann avatar gitter-badger avatar kevinsawicki avatar zloirock avatar

Watchers

 avatar  avatar

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.