Core.js
Alternative modular compact (max. ~22kb w/o gzip) standard library for JavaScript. Includes polyfills for ECMAScript 5, ECMAScript 6: symbols, collections, iterators, promises; setImmediate, array generics, console cap. Additional functionality: dictionaries, extended partial application, date formatting and some other sugar.
Example:
console.log(Array.from(new Set([1, 2, 3, 2, 1])));
console.log('*'.repeat(10));
Promise.resolve(32).then(console.log);
setImmediate(console.log, 42);
Without extension of native objects:
var log = core.console.log;
log(core.Array.from(new core.Set([1, 2, 3, 2, 1])));
log(core.String.repeat('*', 10));
core.Promise.resolve(32).then(log);
core.setImmediate(log, 42);
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
.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
ECMAScript 6
Module es6
.
ECMAScript 6 Object
Object
.assign(target, ...src) -> target
.is(a, b) -> bool
.setPrototypeOf(target, proto | null) -> target, sham(ie10+)
#toString() -> string, fix for @@toStringTag
Example:
var foo = {q: 1, w: 2}
, bar = {e: 3, r: 4}
, baz = {t: 5, y: 6};
Object.assign(foo, bar, baz);
Object.is(NaN, NaN);
Object.is(0, -0);
Object.is(42, 42);
Object.is(42, '42');
ECMAScript 6 Array
Array
.from(iterable | array-like, mapFn(val, index)?, that) -> array
.of(...args) -> array
#copyWithin(target = 0, start = 0, end = @length) -> @
#fill(var, start = 0, end = @length) -> @
#find(fn(val, index, @), that) -> var
#findIndex(fn(val, index, @), that) -> int
Example:
Array.from(new Set([1, 2, 3, 2, 1]));
Array.from({0: 1, 1: 2, 2: 3, length: 3});
Array.from('123', Number);
Array.from('123', function(it){
return it * it;
});
Array.of(1);
Array.of(1, 2, 3);
function isOdd(val){
return val % 2;
}
[4, 8, 15, 16, 23, 42].find(isOdd);
[4, 8, 15, 16, 23, 42].findIndex(isOdd);
[4, 8, 15, 16, 23, 42].find(isNaN);
[4, 8, 15, 16, 23, 42].findIndex(isNaN);
Array(5).map(function(){
return 42;
});
Array(5).fill(42);
ECMAScript 6 String
String
.fromCodePoint(...codePoints) -> str
#includes(str, from?) -> bool
#startsWith(str, from?) -> bool
#endsWith(str, from?) -> bool
#repeat(num) -> str
#codePointAt(pos) -> uint
Example:
'foobarbaz'.includes('bar');
'foobarbaz'.includes('bar', 4);
'foobarbaz'.startsWith('foo');
'foobarbaz'.startsWith('bar', 3);
'foobarbaz'.endsWith('baz');
'foobarbaz'.endsWith('bar', 6);
'string'.repeat(3);
ECMAScript 6 Number & 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
.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
.for(key) -> symbol
.keyFor(symbol) -> key
.iterator -> symbol
.toStringTag -> symbol
.pure(description?) -> symbol || string
.set(object, key, val) -> object
Reflect -> object
.ownKeys(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');
console.log(person.getName());
console.log(person['name']);
console.log(person[Symbol('name')]);
for(var key in person)console.log(key);
Symbol.for
& Symbol.keyFor
example:
var symbol = Symbol.for('key');
symbol === Symbol.for('key');
Symbol.keyFor(symbol);
Reflect.ownKeys
return all object keys - strings & symbols, example:
var O = {a: 1};
Object.defineProperty(O, 'b', {value: 2});
O[Symbol('c')] = 3;
Reflect.ownKeys(O);
ECMAScript 6: Collections
Module es6_collections
, iterators for them are defined in es6_iterators.
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
Example:
var a = [1];
var map = new Map([['a', 1], [42, 2]]);
map.set(a, 3).set(true, 4);
console.log(map.size);
console.log(map.has(a));
console.log(map.has([1]));
console.log(map.get(a));
map.forEach(function(val, key){
console.log(val);
console.log(key);
});
map.delete(a);
console.log(map.size);
console.log(map.get(a));
console.log(Array.from(map));
Set
new Set(iterable?) -> set
#add(key) -> @
#clear() -> void
#delete(key) -> bool
#forEach(fn(el, el, @), that) -> void
#has(key) -> bool
#size
Example:
var set = new Set(['a', 'b', 'a', 'c']);
set.add('d').add('b').add('e');
console.log(set.size);
console.log(set.has('b'));
set.forEach(function(it){
console.log(it);
});
set.delete('b');
console.log(set.size);
console.log(set.has('b'));
console.log(Array.from(set));
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);
console.log(wmap.has(a));
console.log(wmap.has([1]));
console.log(wmap.get(a));
wmap.delete(a);
console.log(wmap.get(a));
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');
console.log(person.getName());
for(var key in person)console.log(key);
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);
console.log(wset.has(b));
console.log(wset.has([2]));
wset.delete(b);
console.log(wset.has(b));
ECMAScript 6: Iterators
Module es6_iterators
.
String
#@@iterator() -> iterator
Array
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iterator
Set
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iterator
Map
#values() -> iterator
#keys() -> iterator
#entries() -> iterator (entries)
#@@iterator() -> iterator (entries)
Arguments
#@@iterator() -> iterator (sham)
Example:
var string = 'abc';
for(var val of string)console.log(val);
var array = ['a', 'b', 'c'];
for(var val of array)console.log(val);
for(var val of array.values())console.log(val);
for(var key of array.keys())console.log(key);
for(var [key, val] of array.entries()){
console.log(key);
console.log(val);
}
var map = new Map([['a', 1], ['b', 2], ['c', 3]]);
for(var [key, val] of map){
console.log(key);
console.log(val);
}
for(var val of map.values())console.log(val);
for(var key of map.keys())console.log(key);
for(var [key, val] of map.entries()){
console.log(key);
console.log(val);
}
var set = new Set([1, 2, 3, 2, 1]);
for(var val of set)console.log(val);
for(var val of set.values())console.log(val);
for(var key of set.keys())console.log(key);
for(var [key, val] of set.entries()){
console.log(key);
console.log(val);
}
Module $for
- iterators chaining - for-of
and array / generator comprehensions helpers for ES5-.
$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){
console.log(it);
});
$for([1, 2, 3].entries(), true).of(function(key, value){
console.log(key);
console.log(value);
});
$for('abc').of(console.log, console);
$for([1, 2, 3, 4, 5]).of(function(it){
console.log(it);
if(it == 3)return false;
});
var ar1 = $for([1, 2, 3]).array(function(v){
return v * v;
});
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;
});
var iter = $for(set).filter(function(v){
return v % 2;
}).map(function(v){
return v * v;
});
iter.next();
iter.next();
iter.next();
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];
}));
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
Example:
var log = console.log.bind(console);
function sleepRandom(time){
return new Promise(function(resolve, reject){
setTimeout(resolve, time * 1e3, 0 | Math.random() * 1e3);
});
}
log('Run');
sleepRandom(5).then(function(result){
log(result);
return sleepRandom(10);
}).then(function(result){
log(result);
}).then(function(){
log('immediately after');
throw Error('Irror!');
}).then(function(){
log('will not be displayed');
}).catch(log);
Mozilla JavaScript: Array generics
Module array_statics
.
Array
.{...ArrayPrototype methods}
Array.slice(arguments, 1);
Array.join('abcdef', '+');
var form = document.getElementsByClassName('form__input');
Array.reduce(form, function(memo, it){
memo[it.name] = it.value;
return memo;
}, {});
setTimeout / setInterval
Module timers
. Additional arguments fix for IE9-.
setTimeout(fn(...args), time, ...args) -> id
setInterval(fn(...args), time, ...args) -> id
setTimeout(log.bind(null, 42), 1000);
setTimeout(log, 1000, 42);
setImmediate
Module immediate
. setImmediate polyfill.
setImmediate(fn(...args), ...args) -> id
clearImmediate(id) -> void
Console
Module console
. Console cap for old browsers and some additional functionality.
console(...args) -> void
.{...console API}
.enable() -> void
.disable() -> void
if(window.console && console.log)console.log(42);
console.log(42);
setTimeout(console.log.bind(console, 42), 1000);
[1, 2, 3].forEach(console.log, console);
setTimeout(console.log, 1000, 42);
[1, 2, 3].forEach(console.log);
console.disable();
console.warn('Console is disabled, you will not see this message.');
console.enable();
console.warn('Console is enabled again.');
console('Shortcut for console.log');
setTimeout(console.log.bind(console, 42), 1000);
setTimeout(console, 1000, 42);
Object
Module object
.
Object
.isObject(var) -> bool
.classof(var) -> string
.define(target, mixin) -> target
.make(proto | null, mixin?) -> object
Object classify examples:
Object.isObject({});
Object.isObject(isNaN);
Object.isObject(null);
var classof = Object.classof;
classof(null);
classof(undefined);
classof(1);
classof(true);
classof('string');
classof(Symbol());
classof(new Number(1));
classof(new Boolean(true));
classof(new String('string'));
var fn = function(){}
, list = (function(){return arguments})(1, 2, 3);
classof({});
classof(fn);
classof([]);
classof(list);
classof(/./);
classof(new TypeError);
classof(new Set);
classof(new Map);
classof(new WeakSet);
classof(new WeakMap);
classof(new Promise(fn));
classof([].values());
classof(new Set().values());
classof(new Map().values());
classof(Math);
classof(JSON);
function Example(){}
Example.prototype[Symbol.toStringTag] = 'Example';
classof(new Example);
Dict
Module dict
.
[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
Object
.values(object) -> array
.entries(object) -> array
Dict
create object without prototype from iterable or simple object. Example:
var map = new Map([['a', 1], ['b', 2], ['c', 3]]);
Dict();
Dict({a: 1, b: 2, c: 3});
Dict(map);
Dict([1, 2, 3].entries());
var dict = Dict({a: 42});
dict instanceof Object;
dict.a;
dict.toString;
'a' in dict;
'hasOwnProperty' in dict;
Dict.isDict({});
Dict.isDict(Dict());
Partial application
Module binding
.
Function
#part(...args | _) -> fn(...args)
#by(object | _, ...args | _) -> boundFn(...args)
#only(num, that ) -> (fn | boundFn)(...args)
Object
#[_](key) -> boundFn
Date formatting
Module 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');
new Date().formatUTC('W, MM D, YY, h:mm:ss');
new Date().format('W, D MM Y г., h:mm:ss', 'ru');
core.locale('ru');
new Date().format('W, D MM Y г., h:mm:ss');
new Date().format('DD.NN.YY');
new Date().format('hh:mm:ss');
new Date().format('DD.NN.Y hh:mm:ss');
new Date().format('W, D MM Y года');
new Date().format('D MM, h:mm');
new Date().format('M Y');
(typeof core != 'undefined' ? core : require('core-js/library')).addLocale('ru', {
weekdays: 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота',
months: 'Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь'
});
Array
Module array
.
Array
#includes(var, from?) -> bool
#turn(fn(memo, val, index, @), memo = []) -> memo
Number
Module number
.
Number
#@@iterator() -> iterator
#random(lim = 0) -> num
#{...Math}
Escaping characters
Module string
.
String
#escapeHTML() -> str
#unescapeHTML() -> str
'<script>doSomething();</script>'.escapeHTML();
'<script>doSomething();</script>'.unescapeHTML();
Module regexp
.
RegExp
.escape(str) -> str
RegExp.escape('Hello -[]{}()*+?.,\\^$|');
Install
// Node.js:
npm i core-js
// Bower:
bower install core.js
Browser builds: default, without extension of native objects, shim only.
Custom builds:
npm i -g grunt-cli
npm i core-js
cd node_modules/core-js && npm i
grunt build:date,console,library --path=custom uglify
Where date
and console
are module names, library
is flag for not extension of native objects and custom
is target file name.
Require in Node.js:
require('core-js');
var core = require('core-js/library');
require('core-js/shim');