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 or extended partial application. You can require only standardized features polyfills, use features without global namespace pollution or create a custom build.
Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
'*'.repeat(10); // => '**********'
Promise.resolve(32).then(log); // => 32
setImmediate(log, 42); // => 42Without 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- Usage
- API
- ECMAScript 5
- ECMAScript 6
- ECMAScript 6: Symbols
- ECMAScript 6: Collections
- ECMAScript 6: Iterators
- ECMAScript 6: Promises
- ECMAScript 6: Reflect
- ECMAScript 7
- Mozilla JavaScript: Array generics
- setTimeout / setInterval
- setImmediate
- console
- Object
- Dict
- Partial application
- Number Iterator
- Escaping HTML
- delay
- Missing polyfills
- Changelog
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 complete build for browser, use builds from core-js/client path: default, without global namespace pollution, shim only.
Warning: 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 maybe conflicts.
You can require only needed modules.
require('core-js/es5'); // if you need support IE8-
require('core-js/fn/set');
require('core-js/fn/array/from');
require('core-js/fn/array/find-index');
Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
[1, 2, NaN, 3, 4].findIndex(isNaN); // => 2
// or, w/o global namespace pollution:
var core = require('core-js/library/es5'); // if you need support IE8-
var Set = require('core-js/library/fn/set');
var from = require('core-js/library/fn/array/from');
var findIndex = require('core-js/library/fn/array/find-index');
from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3]
findIndex([1, 2, NaN, 3, 4], isNaN); // => 2Available entry points for methods / constructors, as above examples, excluding features from es5 module (this module requires completely in ES3 environment before all other modules).
Available namespaces: for example, core-js/es6/array (core-js/library/es6/array) contains all ES6 Array features, core-js/es6 (core-js/library/es6) contains all ES6 features.
npm i core-js && cd node_modules/core-js && npm i
npm run 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 features, es6 contains all modules whose names start with es6.
Available custom build from js code (required webpack):
require('core-js/build')({
modules: ['es6', 'core.dict'], // modules / namespaces
blacklist: ['es6.reflect'], // blacklist of modules / namespaces
library: false, // flag for build without global namespace pollution
}, function(err, code){ // callback
// ...
});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
.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)
Date
.now() -> int
#toISOString() -> stringSome features moved to another modules / namespaces, but available as part of es5 namespace too:
Object
.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-
String
#trim() -> strModules es6.object.assign, es6.object.is, es6.object.set-prototype-of, es6.object.to-string, es6.function.name and es6.function.has-instance.
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+)
#@@hasInstance(var) -> boolvar 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'In ES6 most Object static methods should work with primitives. Modules es6.object.freeze, es6.object.seal, es6.object.prevent-extensions, es6.object.is-frozen, es6.object.is-sealed, es6.object.is-extensible, es6.object.get-own-property-descriptor, es6.object.get-prototype-of, es6.object.keys, es6.object.get-own-property-names.
Object
.freeze(var) -> var
.seal(var) -> var
.preventExtensions(var) -> var
.isFrozen(var) -> bool
.isSealed(var) -> bool
.isExtensible(var) -> bool
.getOwnPropertyDescriptor(var, key) -> desc | undefined
.getPrototypeOf(var) -> object | null
.keys(var) -> array
.getOwnPropertyNames(var) -> arrayObject.keys('qwe'); // => ['0', '1', '2']
Object.getPrototypeOf('qwe') === String.prototype; // => trueModules es6.array.from, es6.array.of, es6.array.copy-within, es6.array.fill, es6.array.find and es6.array.find-index.
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)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]String: modules es6.string.from-code-point, es6.string.raw, es6.string.code-point-at, es6.string.ends-with, es6.string.includes, es6.string.repeat, es6.string.starts-with and es6.string.trim.
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
#trim() -> str, ES6 fixRegExp: modules es6.regexp.constructor and es6.regexp.flags.
[new] RegExp(pattern, flags?) -> regexp, ES6 fix: can alter flags (IE9+)
#flags -> str (IE9+)
Support well-known symbols @@match, @@replace, @@search and @@split: modules es6.regexp.match, es6.regexp.replace, es6.regexp.search and es6.regexp.split.
String
#match(tpl) -> var, ES6 fix for support @@match
#replace(tpl, replacer) -> var, ES6 fix for support @@replace
#search(tpl) -> var, ES6 fix for support @@search
#split(tpl, limit) -> var, ES6 fix for support @@split
RegExp
#@@match(str) -> array | null
#@@replace(str, replacer) -> string
#@@search(str) -> index
#@@split(str, limit) -> array
'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'
'foo'.match({[Symbol.match]: _ => 1}); // => 1
'foo'.replace({[Symbol.replace]: _ => 2}); // => 2
'foo'.search({[Symbol.search]: _ => 3}); // => 3
'foo'.split({[Symbol.split]: _ => 4}); // => 4Module es6.number.constructor. Number constructor support binary and octal literals, example:
Number('0b1010101'); // => 85
Number('0o7654321'); // => 2054353Number: modules es6.number.epsilon, es6.number.is-finite, es6.number.is-integer, es6.number.is-nan, es6.number.is-safe-integer, es6.number.max-safe-integer, es6.number.min-safe-integer, es6.number.parse-float, es6.number.parse-int.
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) -> intMath: modules es6.math.acosh, es6.math.asinh, es6.math.atanh, es6.math.cbrt, es6.math.clz32, es6.math.cosh, es6.math.expm1, es6.math.fround, es6.math.hypot, es6.math.imul, es6.math.log10, es6.math.log1p, es6.math.log2, es6.math.sign, es6.math.sinh, es6.math.tanh, es6.math.trunc.
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
.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) -> numModule 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
Object
.getOwnPropertySymbols(object) -> arrayAlso wrapped some Object methods for correct work with Symbol polyfill.
Object
.create(proto | null, descriptors?) -> object
.defineProperty(target, key, desc) -> target
.defineProperties(target, descriptors) -> target
.getOwnPropertyDescriptor(var, key) -> desc | undefined
.getOwnPropertyNames(var) -> array
#propertyIsEnumerable(key) -> boolvar 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 enumerableSymbol.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)]- We can't add new primitive type,
Symbolreturns object. Symbol.forandSymbol.keyForcan't be shimmed cross-realm.- By default, to hide the keys,
Symbolpolyfill defines setter inObject.prototype. For this reason, uncontrolled creation of symbols can cause memory leak and theinoperator is not working correctly withSymbolpolyfill:Symbol() in {} // => true.
You can disable defining setters 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- Currently,
core-jsnot adds setters toObject.prototypefor well-known symbols for correct work something likeSymbol.iterator in foo. It can cause problems with their enumerability.
core-js uses native collections in most case, just fixes methods / constructor, if it's required, and in old environment uses fast polyfill (O(1) lookup).
Module es6.map. About iterators from this module here.
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 -> uintvar 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]]Module es6.set. About iterators from this module here.
new Set(iterable?) -> set
#add(key) -> @
#clear() -> void
#delete(key) -> bool
#forEach(fn(el, el, @), that) -> void
#has(key) -> bool
#size -> uintvar 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']Module es6.weak-map.
new WeakMap(iterable (entries) ?) -> weakmap
#delete(key) -> bool
#get(key) -> val
#has(key) -> bool
#set(key, val) -> @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'Module es6.weak-set.
new WeakSet(iterable?) -> weakset
#add(key) -> @
#delete(key) -> bool
#has(key) -> boolvar 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- 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.
Modules es6.string.iterator and es6.array.iterator:
String
#@@iterator() -> iterator
Array
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iterator
Arguments
#@@iterator() -> iterator (sham, available only in core-js methods)Modules es6.map and es6.set:
Map
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iterator (entries)
Set
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iteratorModule web.dom.iterable:
NodeList
#@@iterator() -> iteratorvar 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);
}Modules core.is-iterable, core.get-iterator, core.get-iterator-method - helpers for check iterable / get iterator in library version or, for example, for arguments object:
core
.isIterable(var) -> bool
.getIterator(iterable) -> iterator
.getIteratorMethod(var) -> function | undefinedvar list = (function(){
return arguments;
})(1, 2, 3);
log(core.isIterable(list)); // true;
var iter = core.getIterator(list);
log(iter.next().value); // 1
log(iter.next().value); // 2
log(iter.next().value); // 3
log(iter.next().value); // undefined
core.getIterator({}); // TypeError: [object Object] is not iterable!
var iterFn = core.getIteratorMethod(list);
log(typeof iterFn); // 'function'
var iter = iterFn.call(list);
log(iter.next().value); // 1
log(iter.next().value); // 2
log(iter.next().value); // 3
log(iter.next().value); // undefined
log(core.getIteratorMethod({})); // undefinedModule 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) -> promiseBasic 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 promisePromise.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 secECMAScript 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.
}
})();core-js Promise supports (but not adds to native implementations) unhandled rejection tracking. In browser you will see notify in console, in node.js / io.js you can use unhandledRejection event.
Modules es6.reflect.apply, es6.reflect.construct, es6.reflect.define-property, es6.reflect.delete-property, es6.reflect.enumerate, es6.reflect.get, es6.reflect.get-own-property-descriptor, es6.reflect.get-prototype-of, es6.reflect.has, es6.reflect.is-extensible, es6.reflect.own-keys, es6.reflect.prevent-extensions, es6.reflect.set, es6.reflect.set-prototype-of.
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+)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; // => 42Array#includesproposal - modulees7.array.includesString#atproposal - modulees7.string.atString#padLeft,String#padRightproposal - moduleses7.string.pad-left,es7.string.pad-rightString#trimLeft,String#trimRightproposal - moduleses7.string.trim-left,es7.string.trim-rightObject.values,Object.entriestc39 discuss - moduleses7.object.values,es7.object.entriesObject.getOwnPropertyDescriptorsproposal - modulees7.object.get-own-property-descriptorsRegExp.escapeproposal - modulees7.regexp.escapeMap#toJSON,Set#toJSONproposal - moduleses7.map.to-json,es7.set.to-json
Array
#includes(var, from?) -> bool
String
#at(index) -> string
#padLeft(length, fillStr = ' ') -> string
#padRight(length, fillStr = ' ') -> string
#trimLeft() -> string
#trimRight() -> string
Object
.values(object) -> array
.entries(object) -> array
.getOwnPropertyDescriptors(object) -> object
RegExp
.escape(str) -> str
Map
#toJSON() -> array
Set
#toJSON() -> array[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
'hello'.padLeft(10); // => ' hello'
'hello'.padLeft(10, '1234'); // => '41234hello'
'hello'.padRight(10); // => 'hello '
'hello'.padRight(10, '1234'); // => 'hello12341'
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, \[\]\{\}\(\)\*\+\?\.\\\^\$\|!'
JSON.stringify(new Map([['a', 'b'], ['c', 'd']])); // => '[["a","b"],["c","d"]]'
JSON.stringify(new Set([1, 2, 3, 2, 1])); // => '[1,2,3]'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'}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);Module web.immediate. setImmediate polyfill.
setImmediate(fn(...args), ...args) -> id
clearImmediate(id) -> voidsetImmediate(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');
}));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.');Modules core.object.is-object, core.object.classof, core.object.define, core.object.make.
Object
.isObject(var) -> bool
.classof(var) -> string
.define(target, mixin) -> target
.make(proto | null, mixin?) -> objectObject 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.495097567963924Module core.dict. Based on TC39 discuss / strawman.
[new] Dict(iterable (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?) -> varDict 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()); // => trueDict.keys, Dict.values and Dict.entries returns 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 val of Dict.values(dict))log(val); // => 1, 2, 3
for(var [key, val] of Dict.entries(dict)){
log(key); // => 'a', 'b', 'c'
log(val); // => 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}Basic dict operations for objects with prototype example:
'q' in {q: 1}; // => true
'toString' in {}; // => true
Dict.has({q: 1}, 'q'); // => true
Dict.has({}, 'toString'); // => false
({q: 1})['q']; // => 1
({}).toString; // => function toString(){ [native code] }
Dict.get({q: 1}, 'q'); // => 1
Dict.get({}, 'toString'); // => undefined
var O = {};
O['q'] = 1;
O['q']; // => 1
O['__proto__'] = {w: 2};
O['__proto__']; // => {w: 2}
O['w']; // => 2
var O = {};
Dict.set(O, 'q', 1);
O['q']; // => 1
Dict.set(O, '__proto__', {w: 2});
O['__proto__']; // => {w: 2}
O['w']; // => undefinedOther 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'Module core.function.part.
Function
#part(...args | _) -> fn(...args)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, 4Modules core.number.iterator.
Number
#@@iterator() -> iteratorfor(var i of 3)log(i); // => 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}Modules core.string.escape-html and core.string.unescape-html.
String
#escapeHTML() -> str
#unescapeHTML() -> str'<script>doSomething();</script>'.escapeHTML(); // => '<script>doSomething();</script>'
'<script>doSomething();</script>'.unescapeHTML(); // => '<script>doSomething();</script>'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');
})();- ES5
JSONis missing now only in IE7- and never it will be added tocore-js, if you need it in these old browsers available many implementations, for example, json3. - ES6 Typed Arrays can be polyfilled without serious problems, but it will be slow - getter / setter for each element and they are missing completely only in IE9-. You can use this polyfill. Possible, it will be added to
core-jsin the future, completely or only missing methods of existing arrays. - ES6
String#normalizeis not very usefull feature, but this polyfill will be very large. If you need it, you can use unorm. - ES6
Proxycan't be polyfilled, but for Node.js / Chromium with additional flags you can try harmony-reflect for adapt old styleProxyAPI to final ES6 version. - ES7
Object.observecan be polyfilled with many limitations, but it will be very slow - dirty checking on each tick. In nearest future it will not be added tocore-js- it will cause serious slowdown in applications which usesObject.observeand fallback if it's missing. Possible it will be added as optional feature then most actual browsers will have this feature. Now you can use this polyfill. - ES7
SIMD.core-jsdoesn't adds polyfill of this feature because of large size and some other reasons. You can use this polyfill. window.fetchis not crossplatform feature, in some environments it make no sense. For this reason I don't think it should be incore-js. Looking at the large number of requests it maybe added in the future. Now you can use, for example, this polyfill.
- updated string padding to actual proposal - renamed, minor internal changes:
String#lpad->String#padLeftString#rpad->String#padRight
- added string trim functions - proposal, defacto standard - required only for IE11- and fixed for some old engines:
String#trimLeftString#trimRight
String#trimfixed for some engines by es6 spec and moved fromes5to singlees6module- splitted
es6.object.statics-accept-primitives - caps for
freeze-familyObjectmethods moved fromes5toes6namespace and joined with es6 wrappers es5namespace also includes modules, moved toes6namespace - you can use it as before- increased
MessageChannelpriority in$.task, #95 - does not get
global.Symbolon each getting iterator, if you wanna use alternativeSymbolshim - add it beforecore-js Reflect.constructoptimized and fixed for some cases- simplified
Reflect.enumerate, see this question - some corrections in
Math.acosh - fixed
Math.imulfor old WebKit - some fixes in string / RegExp well-known symbols logic
- some other fixes and optimizations
- some fixes for final MS Edge, replaced broken native
Reflect.defineProperty - some minor fixes and optimizations
- changed compression
client/*.min.jsoptions for safeFunction#nameandFunction#length, should be fixed #92
- added logic for well-known symbols:
Symbol.matchSymbol.replaceSymbol.splitSymbol.search
- actualized and optimized work with iterables:
- optimized
Map,Set,WeakMap,WeakSetconstructors,Promise.all,Promise.racefor defaultArray Iterator - optimized
Array.fromfor defaultArray Iterator - added
core.getIteratorMethodhelper
- optimized
- uses enumerable properties in shimmed instances - collections, iterators, etc for optimize performance
- added support native constructors to
Reflect.constructwith 2 arguments - added support native constructors to
Function#bindshim withnew - removed obsolete
.clearmethods nativeWeak-collections - maximum modularity, reduced minimal custom build size, separated into submodules:
es6.reflectes6.regexpes6.mathes6.numberes7.object.to-arraycore.objectcore.stringcore.iter-helpers- internal modules (
$,$.iter, etc)
- many other optimizations
- final cleaning non-standard features
- moved
$forto separate library. This work for syntax -for-ofloop and comprehensions - moved
Date#{format, formatUTC}to separate library. Standard way for this -ECMA-402 - removed
Mathmethods fromNumber.prototype. Slight sugar for simpleMathmethods calling - removed
{Array#, Array, Dict}.turn - removed
core.global
- moved
- uses
ToNumberinstead ofToLengthinNumber Iterator,Array.from(2.5)will be[0, 1, 2]instead of[0, 1] - fixed #85 - invalid
Promiseunhandled rejection message in nestedsetTimeout - fixed #86 - support FF extensions
- fixed #89 - behavior
Numberconstructor in strange case
- removed
/fromRegExp.escapeescaped characters
- updated
RegExp.escapeto the latest proposal - fixed conflict with webpack dev server + IE buggy behavior
- more correct order resolving thenable in
Promisepolyfill - uses polyfill instead of buggy V8
Promise
- collections from
libraryversion return wrapped native instances - fixed collections prototype methods in
libraryversion - optimized
Math.hypot
- updated
Promise.resolvebehavior - added fallback for IE11 buggy
Object.getOwnPropertyNames+ iframe - some other fixes
- added fallback for
Symbolpolyfill for old Android - some other fixes
- different instances
core-jsshould use / recognize the same symbols - some fixes
- simplified custom build
- add custom build js api
- added
grunt-clitodevDependenciesfornpm run grunt
- some fixes
- wrapped
Function#toStringfor correct work wrapped methods / constructors with methods similar to thelodashisNative - added proto versions of methods to export object in
defaultversion for consistency withlibraryversion
- wrapped
Object#propertyIsEnumerableforSymbolpolyfill - added proto versions of methods to
libraryfor ES7 bind syntax - some other fixes
- fixed
Math.hypotwith negative arguments - added
Object#toString.toStringas fallback forlodashisNative
- added support DOM collections to IE8-
Array#slice
- added
String#lpad,String#rpad
- added cap for
Function#@@hasInstance - some fixes and optimizations
- fixed
RegExpconstructor
- some fixes and optimizations
- more correct
Promiseunhandled rejection tracking and resolving / rejection priority
- fixed
__proto__-basedPromisesubclassing in some environments
- added correct symbols descriptors
- fixed behavior
Object.{assign, create, defineProperty, defineProperties, getOwnPropertyDescriptor, getOwnPropertyDescriptors}with symbols - added single entry points for
Object.{create, defineProperty, defineProperties}
- fixed behavior
- added
Map#toJSON - removed non-standard methods
Object#[_]andFunction#only- they solves syntax problems, but now in compilers available arrows andin near future will be availableavailable bind syntax - removed non-standard undocumented methods
Symbol.{pure, set} - some fixes and internal changes
- uses
webpackinstead ofbrowserifyfor browser builds - more compression-friendly result
- fixed
Arraystatics with single entry points
Math.froundnow also works in IE9-- added
Set#toJSON - some optimizations and fixes
- fixed
Symbol.keyFor
- changed CommonJS API
- splitted and renamed some modules
- added support ES3 environment (ES5 polyfill) to all default versions - size increases slightly (+ ~4kb w/o gzip), many issues disappear, if you don't need it - simply include only required namespaces / features / modules
- removed abstract references support - proposal has been superseded =\
$for.isIterable->core.isIterable,$for.getIterator->core.getIterator, temporary available in old namespace- fixed iterators support in v8
Promise.allandPromise.race - many other fixes
- some fixes
- some fixes
- rewritten and splitted into CommonJS modules
- fixed support
Object.definePropertywith accessors on DOM elements on IE8
- added support safe closing iteration - calling
iterator.returnon abort iteration, if it exists - added basic support
Promiseunhandled rejection tracking in shim - added
Object.getOwnPropertyDescriptors - removed
consolecap - creates too many problems - you can usecore.logmodule as that - restructuring namespaces
- some fixes
- some fixes
- added support binary and octal literals to
Numberconstructor - added
Date#toISOString
- some fixes
- some fixes
- systematization of modules
- splitted
es6module - splitted
consolemodule:web.console- only cap for missing methods,core.log- bound methods & additional features - added
delaymethod - some fixes
Object.getOwnPropertySymbolspolyfill returns array of wrapped keys
- FF20-24 fix
- some collections fixes
- added support frozen objects as collections keys
- added
Object.getOwnPropertySymbols - added
NodeList.prototype[@@iterator] - added basic
@@specieslogic - getter in native constructors - removed
Function#by - some fixes
- some fixes
- enabled CSP support
- added
Functioninstancesnameproperty for IE9+
Objectstatic methods accept primitivesRegExpconstructor can alter flags (IE9+)- added
Array.prototype[Symbol.unscopables]
- some fixes
- added
es6.reflectmodule:- 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
- added
core-jsmethods now can use externalSymbol.iteratorpolyfill- some fixes
- console cap excluded from node.js default builds
- added cap for ES5 freeze-family methods
- fixed
consolebug
- some fixes
- Optimize
Map&Set:- use entries chain on hash table
- fast & correct iteration
- iterators moved to
es6andes6.collectionsmodules
consoleno longer shortcut forconsole.log(compatibility problems)- some fixes
- better compliance of ES6
- added
Math.fround(IE10+) - some fixes
- Symbols:
- added option to disable addition setter to
Object.prototypefor Symbol polyfill:- added
Symbol.useSimple - added
Symbol.useSetter
- added
- 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
- added
- added option to disable addition setter to
- added
RegExp#flags(December 2014 Draft Rev 29) - added
String.raw
- repair converting -0 to +0 in native collections
- added
es7.proposalsandes7.abstract-refsmodules - 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]
- added
- removed deprecated
.containsmethods - some fixes
- added
Array#copyWithin - added
String#codePointAt - added
String.fromCodePoint
- added
Dict.mapPairs
- TC39 November meeting:
.contains->.includesString#contains->String#includesArray#contains->Array#includesDict.contains->Dict.includes
- removed
WeakMap#clear - removed
WeakSet#clear
Map&Setbug fix
- public release