Core.js
Alternative modular compact (max. ~23kb w/o gzip) standard library for JavaScript. Includes polyfills for ECMAScript 5, ECMAScript 6: symbols, collections, iterators, promises; setImmediate, array generics, console cap. Some additional functionality such as dictionaries, extended partial application, date formatting.
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
.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
ECMAScript 6
Module es6
. About iterators from this module here. Symbols, collections and promises in separate modules.
ECMAScript 6: Object
Object
.assign(target, ...src) -> target
.is(a, b) -> bool
.setPrototypeOf(target, proto | null) -> target, sham(ie11+)
#toString() -> string, fix for @@toStringTag support
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');
function Parent(){}
function Child(){}
Object.setPrototypeOf(Child.prototype, Parent.prototype);
new Child instanceof Child;
new Child instanceof Parent;
var O = {};
O[Symbol.toStringTag] = 'Foo';
'' + O;
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).fill(42);
[1, 2, 3, 4, 5].copyWithin(0, 3);
ECMAScript 6: String & 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
RegExp
#flags -> str (getter, IE9+)
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);
'𠮷'.codePointAt(0);
String.fromCodePoint(97, 134071, 98);
var name = 'Bob';
String.raw`Hi\n${name}!`;
String.raw({raw: 'test'}, 0, 1, 2);
/foo/.flags;
/foo/gim.flags;
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
.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
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);
By default, Symbol
polyfill define setter in Object.prototype
. You can disable it. Example:
Symbol.useSimple();
var s1 = Symbol('s1')
, o1 = {};
o1[s1] = true;
for(var key in o1)log(key);
Symbol.useSetter();
var s2 = Symbol('s2')
, o2 = {};
o2[s2] = true;
for(var key in o2)log(key);
Reflect.ownKeys
from Reflect
module returns all object keys - strings & symbols.
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
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
:
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)
Example:
var string = 'a𠮷b';
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- 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){
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
Basic 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);
Promise.resolve
and Promise.reject
example:
Promise.resolve(42).then(log);
Promise.reject(42).catch(log);
Promise.resolve($.getJSON('/data.json'));
Promise.all
example:
Promise.all([
'foo',
sleepRandom(5),
sleepRandom(15),
sleepRandom(10)
]).then(log);
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);
timeLimit(sleepRandom(15), 10).catch(log);
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');
log(await sleepRandom(5));
var [a, b, c] = await Promise.all([
sleepRandom(5),
sleepRandom(15),
sleepRandom(10)
]);
log(a, b, c);
await sleepError(5, 'Irror!');
log('Will not be displayed');
} catch(e){
log(e);
}
})();
ECMAScript 6: Reflect
Module es6_reflect
.
Reflect
.apply(target, thisArgument, argumentsList) -> var
.construct(target, argumentsList) -> 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;
console.log(Reflect.ownKeys(O));
function C(a, b){
this.c = a + b;
}
var instance = Reflect.construct(C, [20, 22]);
console.log(instance.c);
ECMAScript 7
Module es7
.
Array
#includes(var, from?) -> bool
String
#at(index) -> string
Object
.values(object) -> array
.entries(object) -> array
RegExp
.escape(str) -> str
Examples:
[1, 2, 3].includes(2);
[1, 2, 3].includes(4);
[1, 2, 3].includes(2, 2);
[NaN].indexOf(NaN);
[NaN].includes(NaN);
Array(1).indexOf(undefined);
Array(1).includes(undefined);
'a𠮷b'.at(1);
'a𠮷b'.at(1).length;
Object.values({a: 1, b: 2, c: 3});
Object.entries({a: 1, b: 2, c: 3});
RegExp.escape('Hello -[]{}()*+?.,\\^$|');
ECMAScript 7: Abstract References
Module es7_refs
. Symbols and methods for abstract references. At the moment, they are supported only by several translators, such as 6to5.
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');
console.log(person.getName());
for(var key in person)console.log(key);
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');
console.log(person.getName());
for(var key in person)console.log(key);
Virtual methods example:
var {toString} = {};
console.log([]::toString());
function sum(){
var {reduce} = [];
return arguments::reduce((a, b)=> a + b);
}
console.log(sum(1, 2, 3, 4, 5));
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);
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
Example:
setImmediate(function(arg1, arg2){
console.log(arg1, arg2);
}, 'Message will be displayed', 'with minimum delay');
clearImmediate(setImmediate(function(){
console.log('Message will not be displayed');
}));
Console
Module console
. Console cap for old browsers and some additional functionality.
console
.{...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.');
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);
Object.define
and Object.make
examples:
Object.defineProperty(target, 'c', {
enumerable: true,
configurable: true,
get: function(){
return this.a + this.b;
}
});
Object.define(target, {
get c(){
return this.a + this.b;
}
});
var copy = Object.make(Object.getPrototypeOf(src), src);
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);
console.log(vector.xy);
console.log(vector.xyz);
vector.y++;
console.log(vector.xy);
console.log(vector.xyz);
Dict
Module 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();
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());
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))console.log(key);
for(var [key, val] of Dict.entries(dict)){
console.log(key);
console.log(val);
}
$for(Dict.values(dict)).of(console.log);
new Map(Dict.entries(dict));
new Map((for([k, v] of Dict.entries(dict))if(v % 2)[k + k, v * v]));
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);
Dict.map(dict, function(it){
return it * it;
});
Dict.mapPairs(dict, function(val, key){
if(key != 'b')return [key + key, val * val];
});
Dict.filter(dict, function(it){
return it % 2;
});
Dict.some(dict, function(it){
return it === 2;
});
Dict.every(dict, function(it){
return it === 2;
});
Dict.find(dict, function(it){
return it > 2;
});
Dict.find(dict, function(it){
return it > 4;
});
Dict.findKey(dict, function(it){
return it > 2;
});
Dict.findKey(dict, function(it){
return it > 4;
});
Dict.keyOf(dict, 2);
Dict.keyOf(dict, 4);
Dict.includes(dict, 2);
Dict.includes(dict, 4);
Dict.reduce(dict, function(memo, it){
return memo + it;
});
Dict.reduce(dict, function(memo, it){
return memo + it;
}, '');
Dict.turn(dict, function(memo, it, key){
memo[key + key] = it;
});
Dict.turn(dict, function(memo, it, key){
it % 2 && memo.push(key + it);
}, []);
Partial application
Module binding
.
Function
#part(...args | _) -> fn(...args)
#by(object | _, ...args | _) -> boundFn(...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 extension of native objects) as placeholder. Examples:
var fn1 = console.log.part(1, 2);
fn1(3, 4);
var fn2 = console.log.part(_, 2, _, 4);
fn2(1, 3);
var fn3 = console.log.part(1, _, _, 4);
fn3(2, 3);
fn2(1, 3, 5);
fn2(1);
Method Function#by
is analogue of Function#bind
with the ability to use placeholder:
var fn = console.log.by(console, _, 2, _, 4);
fn(1, 3, 5);
Method Object#[_]
extracts bound method from object, examples:
['foobar', 'foobaz', 'barbaz'].filter(/bar/[_]('test'));
var has = {}.hasOwnProperty[_]('call');
log(has({key: 42}, 'foo'));
log(has({key: 42}, 'key'));
var array = []
, push = array[_]('push');
push(1);
push(2, 3);
log(array);
Method Function#only
limits number of arguments. Example:
[1, 2, 3].forEach(log.only(1));
Date formatting
Module 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');
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
#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);
}, {});
[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;
});
Number
Module number
.
Number
#@@iterator() -> iterator
#random(lim = 0) -> num
#{...Math}
Number Iterator examples:
for(var i of 3)console.log(i);
$for(3).of(console.log);
Array.from(10, Math.random);
Array.from(10);
Array.from(10, function(it){
return this + it * it;
}, .42);
[for(i of 10)if(i % 2)i * i];
Dict((for(i of 3)['key' + i, !(i % 2)]));
$for(10).filter(function(i){
return i % 2;
}).array(function(i){
return i * i;
});
Dict($for(3).map(function(i){
return ['key' + i, !(i % 2)];
}));
Math
methods in Number.prototype
examples:
3..pow(3);
(-729).abs().sqrt();
10..random(20);
10..random(20).floor();
var array = [1, 2, 3, 4, 5];
array[array.length.random().floor()];
Escaping characters
Module string
.
String
#escapeHTML() -> str
#unescapeHTML() -> str
Examples:
'<script>doSomething();</script>'.escapeHTML();
'<script>doSomething();</script>'.unescapeHTML();
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');
Changelog
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 - Optimize Map
& Set
- use entries chain on hash table
- fast & correct iteration
- iterators moved to
es6
and es6_collections
modules
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
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 - ES6:
0.2.1 - 2014.12.12 - Repair converting -0 to +0 in native collections
0.2.0 - 2014.12.06
- added
es7
, es7_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 - ES6:
0.1.4 - 2014.11.27
0.1.3 - 2014.11.20 - TC39 November meeting:
0.1.2 - 2014.11.19 - Map & Set bug fix
0.1.1 - 2014.11.18 - Public release