Skip to content

Instantly share code, notes, and snippets.

@lixiaoyan
Created June 22, 2016 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lixiaoyan/eb141fe5da2110d5012c09da8389d17e to your computer and use it in GitHub Desktop.
Save lixiaoyan/eb141fe5da2110d5012c09da8389d17e to your computer and use it in GitHub Desktop.
Intris 20fps
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
require("core-js");
require("whatwg-fetch");
require("dom4");
var _loglevel = require("loglevel");
var _loglevel2 = _interopRequireDefault(_loglevel);
var _game = require("./src/game");
var _game2 = _interopRequireDefault(_game);
var _renderer = require("./src/renderer");
var _renderer2 = _interopRequireDefault(_renderer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
System.global.log = _loglevel2.default;
var game = new _game2.default();
var renderer = new _renderer2.default();
game.run(renderer.render.bind(renderer));
},{"./src/game":394,"./src/renderer":398,"core-js":5,"dom4":312,"loglevel":314,"whatwg-fetch":386}],2:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('@most/create', ['exports', 'most', '@most/multicast'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('most'), require('@most/multicast'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.most, global.multicast);
global.mostCreate = mod.exports;
}
})(this, function (exports, _most, _multicast) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
/** @license MIT License (c) copyright 2010-2016 original author or authors */
var defer = function defer(task) {
return Promise.resolve(task).then(runTask);
};
function runTask(task) {
try {
return task.run();
} catch (e) {
return task.error(e);
}
}
/** @license MIT License (c) copyright 2010-2016 original author or authors */
var PropagateAllTask = function () {
function PropagateAllTask(sink, time, events) {
_classCallCheck(this, PropagateAllTask);
this.sink = sink;
this.time = time;
this.events = events;
}
_createClass(PropagateAllTask, [{
key: 'run',
value: function run() {
var events = this.events;
var sink = this.sink;
var event = void 0;
for (var i = 0, l = events.length; i < l; ++i) {
event = events[i];
this.time = event.time;
sink.event(event.time, event.value);
}
events.length = 0;
}
}, {
key: 'error',
value: function error(e) {
this.sink.error(this.time, e);
}
}]);
return PropagateAllTask;
}();
var EndTask = function () {
function EndTask(t, x, sink) {
_classCallCheck(this, EndTask);
this.time = t;
this.value = x;
this.sink = sink;
}
_createClass(EndTask, [{
key: 'run',
value: function run() {
this.sink.end(this.time, this.value);
}
}, {
key: 'error',
value: function error(e) {
this.sink.error(this.time, e);
}
}]);
return EndTask;
}();
var ErrorTask = function () {
function ErrorTask(t, e, sink) {
_classCallCheck(this, ErrorTask);
this.time = t;
this.value = e;
this.sink = sink;
}
_createClass(ErrorTask, [{
key: 'run',
value: function run() {
this.sink.error(this.time, this.value);
}
}, {
key: 'error',
value: function error(e) {
throw e;
}
}]);
return ErrorTask;
}();
var DeferredSink = function () {
function DeferredSink(sink) {
_classCallCheck(this, DeferredSink);
this.sink = sink;
this.events = [];
this.active = true;
}
_createClass(DeferredSink, [{
key: 'event',
value: function event(t, x) {
if (!this.active) {
return;
}
if (this.events.length === 0) {
defer(new PropagateAllTask(this.sink, t, this.events));
}
this.events.push({ time: t, value: x });
}
}, {
key: 'end',
value: function end(t, x) {
if (!this.active) {
return;
}
this._end(new EndTask(t, x, this.sink));
}
}, {
key: 'error',
value: function error(t, e) {
this._end(new ErrorTask(t, e, this.sink));
}
}, {
key: '_end',
value: function _end(task) {
this.active = false;
defer(task);
}
}]);
return DeferredSink;
}();
var CreateSubscriber = function () {
function CreateSubscriber(sink, scheduler, subscribe) {
_classCallCheck(this, CreateSubscriber);
this.sink = sink;
this.scheduler = scheduler;
this._unsubscribe = this._init(subscribe);
}
_createClass(CreateSubscriber, [{
key: '_init',
value: function _init(subscribe) {
var _this = this;
var add = function add(x) {
return _this.sink.event(_this.scheduler.now(), x);
};
var end = function end(x) {
return _this.sink.end(_this.scheduler.now(), x);
};
var error = function error(e) {
return _this.sink.error(_this.scheduler.now(), e);
};
try {
return subscribe(add, end, error);
} catch (e) {
error(e);
}
}
}, {
key: 'dispose',
value: function dispose() {
if (typeof this._unsubscribe === 'function') {
return this._unsubscribe.call(void 0);
}
}
}]);
return CreateSubscriber;
}();
var Create = function () {
function Create(subscribe) {
_classCallCheck(this, Create);
this._subscribe = subscribe;
}
_createClass(Create, [{
key: 'run',
value: function run(sink, scheduler) {
return new CreateSubscriber(new DeferredSink(sink), scheduler, this._subscribe);
}
}]);
return Create;
}();
var index = function index(run) {
return new _most.Stream(new _multicast.MulticastSource(new Create(run)));
};
exports.default = index;
});
},{"@most/multicast":3,"most":381}],3:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('@most/multicast', ['exports', '@most/prelude'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('@most/prelude'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.prelude);
global.mostMulticast = mod.exports;
}
})(this, function (exports, _prelude) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MulticastSource = undefined;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var MulticastDisposable = function () {
function MulticastDisposable(source, sink) {
_classCallCheck(this, MulticastDisposable);
this.source = source;
this.sink = sink;
this.disposed = false;
}
_createClass(MulticastDisposable, [{
key: 'dispose',
value: function dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
var remaining = this.source.remove(this.sink);
return remaining === 0 && this.source._dispose();
}
}]);
return MulticastDisposable;
}();
function tryEvent(t, x, sink) {
try {
sink.event(t, x);
} catch (e) {
sink.error(t, e);
}
}
function tryEnd(t, x, sink) {
try {
sink.end(t, x);
} catch (e) {
sink.error(t, e);
}
}
var dispose = function dispose(disposable) {
return disposable.dispose();
};
var emptyDisposable = {
dispose: function dispose() {}
};
var MulticastSource = function () {
function MulticastSource(source) {
_classCallCheck(this, MulticastSource);
this.source = source;
this.sinks = [];
this._disposable = emptyDisposable;
}
_createClass(MulticastSource, [{
key: 'run',
value: function run(sink, scheduler) {
var n = this.add(sink);
if (n === 1) {
this._disposable = this.source.run(this, scheduler);
}
return new MulticastDisposable(this, sink);
}
}, {
key: '_dispose',
value: function _dispose() {
var disposable = this._disposable;
this._disposable = emptyDisposable;
return Promise.resolve(disposable).then(dispose);
}
}, {
key: 'add',
value: function add(sink) {
this.sinks = (0, _prelude.append)(sink, this.sinks);
return this.sinks.length;
}
}, {
key: 'remove',
value: function remove(sink) {
var i = (0, _prelude.findIndex)(sink, this.sinks);
// istanbul ignore next
if (i >= 0) {
this.sinks = (0, _prelude.remove)(i, this.sinks);
}
return this.sinks.length;
}
}, {
key: 'event',
value: function event(time, value) {
var s = this.sinks;
if (s.length === 1) {
return s[0].event(time, value);
}
for (var i = 0; i < s.length; ++i) {
tryEvent(time, value, s[i]);
}
}
}, {
key: 'end',
value: function end(time, value) {
var s = this.sinks;
for (var i = 0; i < s.length; ++i) {
tryEnd(time, value, s[i]);
}
}
}, {
key: 'error',
value: function error(time, err) {
var s = this.sinks;
for (var i = 0; i < s.length; ++i) {
s[i].error(time, err);
}
}
}]);
return MulticastSource;
}();
function multicast(stream) {
var source = stream.source;
return source instanceof MulticastSource ? stream : new stream.constructor(new MulticastSource(source));
}
exports.MulticastSource = MulticastSource;
exports.default = multicast;
});
},{"@most/prelude":4}],4:[function(require,module,exports){
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('@most/prelude', ['exports'], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.mostPrelude = mod.exports;
}
})(this, function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/** @license MIT License (c) copyright 2010-2016 original author or authors */
// Non-mutating array operations
// cons :: a -> [a] -> [a]
// a with x prepended
function cons(x, a) {
var l = a.length;
var b = new Array(l + 1);
b[0] = x;
for (var i = 0; i < l; ++i) {
b[i + 1] = a[i];
}
return b;
}
// append :: a -> [a] -> [a]
// a with x appended
function append(x, a) {
var l = a.length;
var b = new Array(l + 1);
for (var i = 0; i < l; ++i) {
b[i] = a[i];
}
b[l] = x;
return b;
}
// drop :: Int -> [a] -> [a]
// drop first n elements
function drop(n, a) {
// eslint-disable-line complexity
if (n < 0) {
throw new TypeError('n must be >= 0');
}
var l = a.length;
if (n === 0 || l === 0) {
return a;
}
if (n >= l) {
return [];
}
return unsafeDrop(n, a, l - n);
}
// unsafeDrop :: Int -> [a] -> Int -> [a]
// Internal helper for drop
function unsafeDrop(n, a, l) {
var b = new Array(l);
for (var i = 0; i < l; ++i) {
b[i] = a[n + i];
}
return b;
}
// tail :: [a] -> [a]
// drop head element
function tail(a) {
return drop(1, a);
}
// copy :: [a] -> [a]
// duplicate a (shallow duplication)
function copy(a) {
var l = a.length;
var b = new Array(l);
for (var i = 0; i < l; ++i) {
b[i] = a[i];
}
return b;
}
// map :: (a -> b) -> [a] -> [b]
// transform each element with f
function map(f, a) {
var l = a.length;
var b = new Array(l);
for (var i = 0; i < l; ++i) {
b[i] = f(a[i]);
}
return b;
}
// reduce :: (a -> b -> a) -> a -> [b] -> a
// accumulate via left-fold
function reduce(f, z, a) {
var r = z;
for (var i = 0, l = a.length; i < l; ++i) {
r = f(r, a[i], i);
}
return r;
}
// replace :: a -> Int -> [a]
// replace element at index
function replace(x, i, a) {
// eslint-disable-line complexity
if (i < 0) {
throw new TypeError('i must be >= 0');
}
var l = a.length;
var b = new Array(l);
for (var j = 0; j < l; ++j) {
b[j] = i === j ? x : a[j];
}
return b;
}
// remove :: Int -> [a] -> [a]
// remove element at index
function remove(i, a) {
// eslint-disable-line complexity
if (i < 0) {
throw new TypeError('i must be >= 0');
}
var l = a.length;
if (l === 0 || i >= l) {
// exit early if index beyond end of array
return a;
}
if (l === 1) {
// exit early if index in bounds and length === 1
return [];
}
return unsafeRemove(i, a, l - 1);
}
// unsafeRemove :: Int -> [a] -> Int -> [a]
// Internal helper to remove element at index
function unsafeRemove(i, a, l) {
var b = new Array(l);
var j = void 0;
for (j = 0; j < i; ++j) {
b[j] = a[j];
}
for (j = i; j < l; ++j) {
b[j] = a[j + 1];
}
return b;
}
// removeAll :: (a -> boolean) -> [a] -> [a]
// remove all elements matching a predicate
function removeAll(f, a) {
var l = a.length;
var b = new Array(l);
var j = 0;
for (var x, i = 0; i < l; ++i) {
x = a[i];
if (!f(x)) {
b[j] = x;
++j;
}
}
b.length = j;
return b;
}
// findIndex :: a -> [a] -> Int
// find index of x in a, from the left
function findIndex(x, a) {
for (var i = 0, l = a.length; i < l; ++i) {
if (x === a[i]) {
return i;
}
}
return -1;
}
// isArrayLike :: * -> boolean
// Return true iff x is array-like
function isArrayLike(x) {
return x != null && typeof x.length === 'number' && typeof x !== 'function';
}
/** @license MIT License (c) copyright 2010-2016 original author or authors */
// id :: a -> a
var id = function id(x) {
return x;
};
// compose :: (b -> c) -> (a -> b) -> (a -> c)
var compose = function compose(f, g) {
return function (x) {
return f(g(x));
};
};
// apply :: (a -> b) -> a -> b
var apply = function apply(f, x) {
return f(x);
};
// curry2 :: ((a, b) -> c) -> (a -> b -> c)
function curry2(f) {
function curried(a, b) {
switch (arguments.length) {
case 0:
return curried;
case 1:
return function (b) {
return f(a, b);
};
default:
return f(a, b);
}
}
return curried;
}
// curry3 :: ((a, b, c) -> d) -> (a -> b -> c -> d)
function curry3(f) {
function curried(a, b, c) {
// eslint-disable-line complexity
switch (arguments.length) {
case 0:
return curried;
case 1:
return curry2(function (b, c) {
return f(a, b, c);
});
case 2:
return function (c) {
return f(a, b, c);
};
default:
return f(a, b, c);
}
}
return curried;
}
exports.cons = cons;
exports.append = append;
exports.drop = drop;
exports.tail = tail;
exports.copy = copy;
exports.map = map;
exports.reduce = reduce;
exports.replace = replace;
exports.remove = remove;
exports.removeAll = removeAll;
exports.findIndex = findIndex;
exports.isArrayLike = isArrayLike;
exports.id = id;
exports.compose = compose;
exports.apply = apply;
exports.curry2 = curry2;
exports.curry3 = curry3;
});
},{}],5:[function(require,module,exports){
require('./shim');
require('./modules/core.dict');
require('./modules/core.get-iterator-method');
require('./modules/core.get-iterator');
require('./modules/core.is-iterable');
require('./modules/core.delay');
require('./modules/core.function.part');
require('./modules/core.object.is-object');
require('./modules/core.object.classof');
require('./modules/core.object.define');
require('./modules/core.object.make');
require('./modules/core.number.iterator');
require('./modules/core.regexp.escape');
require('./modules/core.string.escape-html');
require('./modules/core.string.unescape-html');
module.exports = require('./modules/_core');
},{"./modules/_core":26,"./modules/core.delay":122,"./modules/core.dict":123,"./modules/core.function.part":124,"./modules/core.get-iterator":126,"./modules/core.get-iterator-method":125,"./modules/core.is-iterable":127,"./modules/core.number.iterator":128,"./modules/core.object.classof":129,"./modules/core.object.define":130,"./modules/core.object.is-object":131,"./modules/core.object.make":132,"./modules/core.regexp.escape":133,"./modules/core.string.escape-html":134,"./modules/core.string.unescape-html":135,"./shim":311}],6:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],7:[function(require,module,exports){
var cof = require('./_cof');
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
},{"./_cof":21}],8:[function(require,module,exports){
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = require('./_wks')('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)require('./_hide')(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
},{"./_hide":43,"./_wks":121}],9:[function(require,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],10:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":52}],11:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = require('./_to-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length');
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
},{"./_to-index":109,"./_to-length":112,"./_to-object":113}],12:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = require('./_to-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length');
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
},{"./_to-index":109,"./_to-length":112,"./_to-object":113}],13:[function(require,module,exports){
var forOf = require('./_for-of');
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"./_for-of":40}],14:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject')
, toLength = require('./_to-length')
, toIndex = require('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":109,"./_to-iobject":111,"./_to-length":112}],15:[function(require,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = require('./_ctx')
, IObject = require('./_iobject')
, toObject = require('./_to-object')
, toLength = require('./_to-length')
, asc = require('./_array-species-create');
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./_array-species-create":18,"./_ctx":28,"./_iobject":48,"./_to-length":112,"./_to-object":113}],16:[function(require,module,exports){
var aFunction = require('./_a-function')
, toObject = require('./_to-object')
, IObject = require('./_iobject')
, toLength = require('./_to-length');
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
},{"./_a-function":6,"./_iobject":48,"./_to-length":112,"./_to-object":113}],17:[function(require,module,exports){
var isObject = require('./_is-object')
, isArray = require('./_is-array')
, SPECIES = require('./_wks')('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"./_is-array":50,"./_is-object":52,"./_wks":121}],18:[function(require,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = require('./_array-species-constructor');
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"./_array-species-constructor":17}],19:[function(require,module,exports){
'use strict';
var aFunction = require('./_a-function')
, isObject = require('./_is-object')
, invoke = require('./_invoke')
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
},{"./_a-function":6,"./_invoke":47,"./_is-object":52}],20:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof')
, TAG = require('./_wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":21,"./_wks":121}],21:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],22:[function(require,module,exports){
'use strict';
var dP = require('./_object-dp').f
, create = require('./_object-create')
, hide = require('./_hide')
, redefineAll = require('./_redefine-all')
, ctx = require('./_ctx')
, anInstance = require('./_an-instance')
, defined = require('./_defined')
, forOf = require('./_for-of')
, $iterDefine = require('./_iter-define')
, step = require('./_iter-step')
, setSpecies = require('./_set-species')
, DESCRIPTORS = require('./_descriptors')
, fastKey = require('./_meta').fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"./_an-instance":9,"./_ctx":28,"./_defined":30,"./_descriptors":31,"./_for-of":40,"./_hide":43,"./_iter-define":56,"./_iter-step":58,"./_meta":65,"./_object-create":69,"./_object-dp":71,"./_redefine-all":90,"./_set-species":95}],23:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = require('./_classof')
, from = require('./_array-from-iterable');
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"./_array-from-iterable":13,"./_classof":20}],24:[function(require,module,exports){
'use strict';
var redefineAll = require('./_redefine-all')
, getWeak = require('./_meta').getWeak
, anObject = require('./_an-object')
, isObject = require('./_is-object')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, createArrayMethod = require('./_array-methods')
, $has = require('./_has')
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"./_an-instance":9,"./_an-object":10,"./_array-methods":15,"./_for-of":40,"./_has":42,"./_is-object":52,"./_meta":65,"./_redefine-all":90}],25:[function(require,module,exports){
'use strict';
var global = require('./_global')
, $export = require('./_export')
, redefine = require('./_redefine')
, redefineAll = require('./_redefine-all')
, meta = require('./_meta')
, forOf = require('./_for-of')
, anInstance = require('./_an-instance')
, isObject = require('./_is-object')
, fails = require('./_fails')
, $iterDetect = require('./_iter-detect')
, setToStringTag = require('./_set-to-string-tag')
, inheritIfRequired = require('./_inherit-if-required');
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./_an-instance":9,"./_export":35,"./_fails":37,"./_for-of":40,"./_global":41,"./_inherit-if-required":46,"./_is-object":52,"./_iter-detect":57,"./_meta":65,"./_redefine":91,"./_redefine-all":90,"./_set-to-string-tag":96}],26:[function(require,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],27:[function(require,module,exports){
'use strict';
var $defineProperty = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
},{"./_object-dp":71,"./_property-desc":89}],28:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./_a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./_a-function":6}],29:[function(require,module,exports){
'use strict';
var anObject = require('./_an-object')
, toPrimitive = require('./_to-primitive')
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
},{"./_an-object":10,"./_to-primitive":114}],30:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],31:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":37}],32:[function(require,module,exports){
var isObject = require('./_is-object')
, document = require('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":41,"./_is-object":52}],33:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],34:[function(require,module,exports){
// all enumerable object keys, includes symbols
var getKeys = require('./_object-keys')
, gOPS = require('./_object-gops')
, pIE = require('./_object-pie');
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"./_object-gops":77,"./_object-keys":80,"./_object-pie":81}],35:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, hide = require('./_hide')
, redefine = require('./_redefine')
, ctx = require('./_ctx')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":26,"./_ctx":28,"./_global":41,"./_hide":43,"./_redefine":91}],36:[function(require,module,exports){
var MATCH = require('./_wks')('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
},{"./_wks":121}],37:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],38:[function(require,module,exports){
'use strict';
var hide = require('./_hide')
, redefine = require('./_redefine')
, fails = require('./_fails')
, defined = require('./_defined')
, wks = require('./_wks');
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
},{"./_defined":30,"./_fails":37,"./_hide":43,"./_redefine":91,"./_wks":121}],39:[function(require,module,exports){
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = require('./_an-object');
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
},{"./_an-object":10}],40:[function(require,module,exports){
var ctx = require('./_ctx')
, call = require('./_iter-call')
, isArrayIter = require('./_is-array-iter')
, anObject = require('./_an-object')
, toLength = require('./_to-length')
, getIterFn = require('./core.get-iterator-method')
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"./_an-object":10,"./_ctx":28,"./_is-array-iter":49,"./_iter-call":54,"./_to-length":112,"./core.get-iterator-method":125}],41:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],42:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],43:[function(require,module,exports){
var dP = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":31,"./_object-dp":71,"./_property-desc":89}],44:[function(require,module,exports){
module.exports = require('./_global').document && document.documentElement;
},{"./_global":41}],45:[function(require,module,exports){
module.exports = !require('./_descriptors') && !require('./_fails')(function(){
return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":31,"./_dom-create":32,"./_fails":37}],46:[function(require,module,exports){
var isObject = require('./_is-object')
, setPrototypeOf = require('./_set-proto').set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
},{"./_is-object":52,"./_set-proto":94}],47:[function(require,module,exports){
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
},{}],48:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":21}],49:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./_iterators')
, ITERATOR = require('./_wks')('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":59,"./_wks":121}],50:[function(require,module,exports){
// 7.2.2 IsArray(argument)
var cof = require('./_cof');
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"./_cof":21}],51:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var isObject = require('./_is-object')
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
},{"./_is-object":52}],52:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],53:[function(require,module,exports){
// 7.2.8 IsRegExp(argument)
var isObject = require('./_is-object')
, cof = require('./_cof')
, MATCH = require('./_wks')('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
},{"./_cof":21,"./_is-object":52,"./_wks":121}],54:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./_an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./_an-object":10}],55:[function(require,module,exports){
'use strict';
var create = require('./_object-create')
, descriptor = require('./_property-desc')
, setToStringTag = require('./_set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":43,"./_object-create":69,"./_property-desc":89,"./_set-to-string-tag":96,"./_wks":121}],56:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, $export = require('./_export')
, redefine = require('./_redefine')
, hide = require('./_hide')
, has = require('./_has')
, Iterators = require('./_iterators')
, $iterCreate = require('./_iter-create')
, setToStringTag = require('./_set-to-string-tag')
, getPrototypeOf = require('./_object-gpo')
, ITERATOR = require('./_wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":35,"./_has":42,"./_hide":43,"./_iter-create":55,"./_iterators":59,"./_library":61,"./_object-gpo":78,"./_redefine":91,"./_set-to-string-tag":96,"./_wks":121}],57:[function(require,module,exports){
var ITERATOR = require('./_wks')('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
},{"./_wks":121}],58:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],59:[function(require,module,exports){
module.exports = {};
},{}],60:[function(require,module,exports){
var getKeys = require('./_object-keys')
, toIObject = require('./_to-iobject');
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"./_object-keys":80,"./_to-iobject":111}],61:[function(require,module,exports){
module.exports = false;
},{}],62:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
},{}],63:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
},{}],64:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
},{}],65:[function(require,module,exports){
var META = require('./_uid')('meta')
, isObject = require('./_is-object')
, has = require('./_has')
, setDesc = require('./_object-dp').f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !require('./_fails')(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"./_fails":37,"./_has":42,"./_is-object":52,"./_object-dp":71,"./_uid":118}],66:[function(require,module,exports){
var Map = require('./es6.map')
, $export = require('./_export')
, shared = require('./_shared')('metadata')
, store = shared.store || (shared.store = new (require('./es6.weak-map')));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
},{"./_export":35,"./_shared":98,"./es6.map":165,"./es6.weak-map":271}],67:[function(require,module,exports){
var global = require('./_global')
, macrotask = require('./_task').set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = require('./_cof')(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
},{"./_cof":21,"./_global":41,"./_task":108}],68:[function(require,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = require('./_object-keys')
, gOPS = require('./_object-gops')
, pIE = require('./_object-pie')
, toObject = require('./_to-object')
, IObject = require('./_iobject')
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || require('./_fails')(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
},{"./_fails":37,"./_iobject":48,"./_object-gops":77,"./_object-keys":80,"./_object-pie":81,"./_to-object":113}],69:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object')
, dPs = require('./_object-dps')
, enumBugKeys = require('./_enum-bug-keys')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = require('./_dom-create')('iframe')
, i = enumBugKeys.length
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
require('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":10,"./_dom-create":32,"./_enum-bug-keys":33,"./_html":44,"./_object-dps":72,"./_shared-key":97}],70:[function(require,module,exports){
var dP = require('./_object-dp')
, gOPD = require('./_object-gopd')
, ownKeys = require('./_own-keys')
, toIObject = require('./_to-iobject');
module.exports = function define(target, mixin){
var keys = ownKeys(toIObject(mixin))
, length = keys.length
, i = 0, key;
while(length > i)dP.f(target, key = keys[i++], gOPD.f(mixin, key));
return target;
};
},{"./_object-dp":71,"./_object-gopd":74,"./_own-keys":84,"./_to-iobject":111}],71:[function(require,module,exports){
var anObject = require('./_an-object')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, toPrimitive = require('./_to-primitive')
, dP = Object.defineProperty;
exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":10,"./_descriptors":31,"./_ie8-dom-define":45,"./_to-primitive":114}],72:[function(require,module,exports){
var dP = require('./_object-dp')
, anObject = require('./_an-object')
, getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":10,"./_descriptors":31,"./_object-dp":71,"./_object-keys":80}],73:[function(require,module,exports){
// Forced replacement prototype accessors methods
module.exports = require('./_library')|| !require('./_fails')(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete require('./_global')[K];
});
},{"./_fails":37,"./_global":41,"./_library":61}],74:[function(require,module,exports){
var pIE = require('./_object-pie')
, createDesc = require('./_property-desc')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, has = require('./_has')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = require('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"./_descriptors":31,"./_has":42,"./_ie8-dom-define":45,"./_object-pie":81,"./_property-desc":89,"./_to-iobject":111,"./_to-primitive":114}],75:[function(require,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = require('./_to-iobject')
, gOPN = require('./_object-gopn').f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"./_object-gopn":76,"./_to-iobject":111}],76:[function(require,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = require('./_object-keys-internal')
, hiddenKeys = require('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":33,"./_object-keys-internal":79}],77:[function(require,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],78:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has')
, toObject = require('./_to-object')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":42,"./_shared-key":97,"./_to-object":113}],79:[function(require,module,exports){
var has = require('./_has')
, toIObject = require('./_to-iobject')
, arrayIndexOf = require('./_array-includes')(false)
, IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":14,"./_has":42,"./_shared-key":97,"./_to-iobject":111}],80:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal')
, enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":33,"./_object-keys-internal":79}],81:[function(require,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],82:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./_export')
, core = require('./_core')
, fails = require('./_fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./_core":26,"./_export":35,"./_fails":37}],83:[function(require,module,exports){
var getKeys = require('./_object-keys')
, toIObject = require('./_to-iobject')
, isEnum = require('./_object-pie').f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
},{"./_object-keys":80,"./_object-pie":81,"./_to-iobject":111}],84:[function(require,module,exports){
// all object keys, includes non-enumerable and symbols
var gOPN = require('./_object-gopn')
, gOPS = require('./_object-gops')
, anObject = require('./_an-object')
, Reflect = require('./_global').Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
},{"./_an-object":10,"./_global":41,"./_object-gopn":76,"./_object-gops":77}],85:[function(require,module,exports){
var $parseFloat = require('./_global').parseFloat
, $trim = require('./_string-trim').trim;
module.exports = 1 / $parseFloat(require('./_string-ws') + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
},{"./_global":41,"./_string-trim":106,"./_string-ws":107}],86:[function(require,module,exports){
var $parseInt = require('./_global').parseInt
, $trim = require('./_string-trim').trim
, ws = require('./_string-ws')
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
},{"./_global":41,"./_string-trim":106,"./_string-ws":107}],87:[function(require,module,exports){
'use strict';
var path = require('./_path')
, invoke = require('./_invoke')
, aFunction = require('./_a-function');
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
},{"./_a-function":6,"./_invoke":47,"./_path":88}],88:[function(require,module,exports){
module.exports = require('./_global');
},{"./_global":41}],89:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],90:[function(require,module,exports){
var redefine = require('./_redefine');
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
},{"./_redefine":91}],91:[function(require,module,exports){
var global = require('./_global')
, hide = require('./_hide')
, has = require('./_has')
, SRC = require('./_uid')('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
require('./_core').inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
},{"./_core":26,"./_global":41,"./_has":42,"./_hide":43,"./_uid":118}],92:[function(require,module,exports){
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
},{}],93:[function(require,module,exports){
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
},{}],94:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = require('./_is-object')
, anObject = require('./_an-object');
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = require('./_ctx')(Function.call, require('./_object-gopd').f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./_an-object":10,"./_ctx":28,"./_is-object":52,"./_object-gopd":74}],95:[function(require,module,exports){
'use strict';
var global = require('./_global')
, dP = require('./_object-dp')
, DESCRIPTORS = require('./_descriptors')
, SPECIES = require('./_wks')('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./_descriptors":31,"./_global":41,"./_object-dp":71,"./_wks":121}],96:[function(require,module,exports){
var def = require('./_object-dp').f
, has = require('./_has')
, TAG = require('./_wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./_has":42,"./_object-dp":71,"./_wks":121}],97:[function(require,module,exports){
var shared = require('./_shared')('keys')
, uid = require('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":98,"./_uid":118}],98:[function(require,module,exports){
var global = require('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":41}],99:[function(require,module,exports){
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = require('./_an-object')
, aFunction = require('./_a-function')
, SPECIES = require('./_wks')('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
},{"./_a-function":6,"./_an-object":10,"./_wks":121}],100:[function(require,module,exports){
var fails = require('./_fails');
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
},{"./_fails":37}],101:[function(require,module,exports){
var toInteger = require('./_to-integer')
, defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":30,"./_to-integer":110}],102:[function(require,module,exports){
// helper for String#{startsWith, endsWith, includes}
var isRegExp = require('./_is-regexp')
, defined = require('./_defined');
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
},{"./_defined":30,"./_is-regexp":53}],103:[function(require,module,exports){
var $export = require('./_export')
, fails = require('./_fails')
, defined = require('./_defined')
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
},{"./_defined":30,"./_export":35,"./_fails":37}],104:[function(require,module,exports){
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = require('./_to-length')
, repeat = require('./_string-repeat')
, defined = require('./_defined');
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
},{"./_defined":30,"./_string-repeat":105,"./_to-length":112}],105:[function(require,module,exports){
'use strict';
var toInteger = require('./_to-integer')
, defined = require('./_defined');
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
},{"./_defined":30,"./_to-integer":110}],106:[function(require,module,exports){
var $export = require('./_export')
, defined = require('./_defined')
, fails = require('./_fails')
, spaces = require('./_string-ws')
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
},{"./_defined":30,"./_export":35,"./_fails":37,"./_string-ws":107}],107:[function(require,module,exports){
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
},{}],108:[function(require,module,exports){
var ctx = require('./_ctx')
, invoke = require('./_invoke')
, html = require('./_html')
, cel = require('./_dom-create')
, global = require('./_global')
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(require('./_cof')(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
},{"./_cof":21,"./_ctx":28,"./_dom-create":32,"./_global":41,"./_html":44,"./_invoke":47}],109:[function(require,module,exports){
var toInteger = require('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":110}],110:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],111:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject')
, defined = require('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":30,"./_iobject":48}],112:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":110}],113:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":30}],114:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":52}],115:[function(require,module,exports){
'use strict';
if(require('./_descriptors')){
var LIBRARY = require('./_library')
, global = require('./_global')
, fails = require('./_fails')
, $export = require('./_export')
, $typed = require('./_typed')
, $buffer = require('./_typed-buffer')
, ctx = require('./_ctx')
, anInstance = require('./_an-instance')
, propertyDesc = require('./_property-desc')
, hide = require('./_hide')
, redefineAll = require('./_redefine-all')
, isInteger = require('./_is-integer')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, toIndex = require('./_to-index')
, toPrimitive = require('./_to-primitive')
, has = require('./_has')
, same = require('./_same-value')
, classof = require('./_classof')
, isObject = require('./_is-object')
, toObject = require('./_to-object')
, isArrayIter = require('./_is-array-iter')
, create = require('./_object-create')
, getPrototypeOf = require('./_object-gpo')
, gOPN = require('./_object-gopn').f
, isIterable = require('./core.is-iterable')
, getIterFn = require('./core.get-iterator-method')
, uid = require('./_uid')
, wks = require('./_wks')
, createArrayMethod = require('./_array-methods')
, createArrayIncludes = require('./_array-includes')
, speciesConstructor = require('./_species-constructor')
, ArrayIterators = require('./es6.array.iterator')
, Iterators = require('./_iterators')
, $iterDetect = require('./_iter-detect')
, setSpecies = require('./_set-species')
, arrayFill = require('./_array-fill')
, arrayCopyWithin = require('./_array-copy-within')
, $DP = require('./_object-dp')
, $GOPD = require('./_object-gopd')
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
},{"./_an-instance":9,"./_array-copy-within":11,"./_array-fill":12,"./_array-includes":14,"./_array-methods":15,"./_classof":20,"./_ctx":28,"./_descriptors":31,"./_export":35,"./_fails":37,"./_global":41,"./_has":42,"./_hide":43,"./_is-array-iter":49,"./_is-integer":51,"./_is-object":52,"./_iter-detect":57,"./_iterators":59,"./_library":61,"./_object-create":69,"./_object-dp":71,"./_object-gopd":74,"./_object-gopn":76,"./_object-gpo":78,"./_property-desc":89,"./_redefine-all":90,"./_same-value":93,"./_set-species":95,"./_species-constructor":99,"./_to-index":109,"./_to-integer":110,"./_to-length":112,"./_to-object":113,"./_to-primitive":114,"./_typed":117,"./_typed-buffer":116,"./_uid":118,"./_wks":121,"./core.get-iterator-method":125,"./core.is-iterable":127,"./es6.array.iterator":146}],116:[function(require,module,exports){
'use strict';
var global = require('./_global')
, DESCRIPTORS = require('./_descriptors')
, LIBRARY = require('./_library')
, $typed = require('./_typed')
, hide = require('./_hide')
, redefineAll = require('./_redefine-all')
, fails = require('./_fails')
, anInstance = require('./_an-instance')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, gOPN = require('./_object-gopn').f
, dP = require('./_object-dp').f
, arrayFill = require('./_array-fill')
, setToStringTag = require('./_set-to-string-tag')
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, parseInt = global.parseInt
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, min = Math.min
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
},{"./_an-instance":9,"./_array-fill":12,"./_descriptors":31,"./_fails":37,"./_global":41,"./_hide":43,"./_library":61,"./_object-dp":71,"./_object-gopn":76,"./_redefine-all":90,"./_set-to-string-tag":96,"./_to-integer":110,"./_to-length":112,"./_typed":117}],117:[function(require,module,exports){
var global = require('./_global')
, hide = require('./_hide')
, uid = require('./_uid')
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
},{"./_global":41,"./_hide":43,"./_uid":118}],118:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],119:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, LIBRARY = require('./_library')
, wksExt = require('./_wks-ext')
, defineProperty = require('./_object-dp').f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"./_core":26,"./_global":41,"./_library":61,"./_object-dp":71,"./_wks-ext":120}],120:[function(require,module,exports){
exports.f = require('./_wks');
},{"./_wks":121}],121:[function(require,module,exports){
var store = require('./_shared')('wks')
, uid = require('./_uid')
, Symbol = require('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":41,"./_shared":98,"./_uid":118}],122:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, $export = require('./_export')
, partial = require('./_partial');
// https://esdiscuss.org/topic/promise-returning-delay-function
$export($export.G + $export.F, {
delay: function delay(time){
return new (core.Promise || global.Promise)(function(resolve){
setTimeout(partial.call(resolve, true), time);
});
}
});
},{"./_core":26,"./_export":35,"./_global":41,"./_partial":87}],123:[function(require,module,exports){
'use strict';
var ctx = require('./_ctx')
, $export = require('./_export')
, createDesc = require('./_property-desc')
, assign = require('./_object-assign')
, create = require('./_object-create')
, getPrototypeOf = require('./_object-gpo')
, getKeys = require('./_object-keys')
, dP = require('./_object-dp')
, keyOf = require('./_keyof')
, aFunction = require('./_a-function')
, forOf = require('./_for-of')
, isIterable = require('./core.is-iterable')
, $iterCreate = require('./_iter-create')
, step = require('./_iter-step')
, isObject = require('./_is-object')
, toIObject = require('./_to-iobject')
, DESCRIPTORS = require('./_descriptors')
, has = require('./_has');
// 0 -> Dict.forEach
// 1 -> Dict.map
// 2 -> Dict.filter
// 3 -> Dict.some
// 4 -> Dict.every
// 5 -> Dict.find
// 6 -> Dict.findKey
// 7 -> Dict.mapPairs
var createDictMethod = function(TYPE){
var IS_MAP = TYPE == 1
, IS_EVERY = TYPE == 4;
return function(object, callbackfn, that /* = undefined */){
var f = ctx(callbackfn, that, 3)
, O = toIObject(object)
, result = IS_MAP || TYPE == 7 || TYPE == 2
? new (typeof this == 'function' ? this : Dict) : undefined
, key, val, res;
for(key in O)if(has(O, key)){
val = O[key];
res = f(val, key, object);
if(TYPE){
if(IS_MAP)result[key] = res; // map
else if(res)switch(TYPE){
case 2: result[key] = val; break; // filter
case 3: return true; // some
case 5: return val; // find
case 6: return key; // findKey
case 7: result[res[0]] = res[1]; // mapPairs
} else if(IS_EVERY)return false; // every
}
}
return TYPE == 3 || IS_EVERY ? IS_EVERY : result;
};
};
var findKey = createDictMethod(6);
var createDictIter = function(kind){
return function(it){
return new DictIterator(it, kind);
};
};
var DictIterator = function(iterated, kind){
this._t = toIObject(iterated); // target
this._a = getKeys(iterated); // keys
this._i = 0; // next index
this._k = kind; // kind
};
$iterCreate(DictIterator, 'Dict', function(){
var that = this
, O = that._t
, keys = that._a
, kind = that._k
, key;
do {
if(that._i >= keys.length){
that._t = undefined;
return step(1);
}
} while(!has(O, key = keys[that._i++]));
if(kind == 'keys' )return step(0, key);
if(kind == 'values')return step(0, O[key]);
return step(0, [key, O[key]]);
});
function Dict(iterable){
var dict = create(null);
if(iterable != undefined){
if(isIterable(iterable)){
forOf(iterable, true, function(key, value){
dict[key] = value;
});
} else assign(dict, iterable);
}
return dict;
}
Dict.prototype = null;
function reduce(object, mapfn, init){
aFunction(mapfn);
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, i = 0
, memo, key;
if(arguments.length < 3){
if(!length)throw TypeError('Reduce of empty object with no initial value');
memo = O[keys[i++]];
} else memo = Object(init);
while(length > i)if(has(O, key = keys[i++])){
memo = mapfn(memo, O[key], key, object);
}
return memo;
}
function includes(object, el){
return (el == el ? keyOf(object, el) : findKey(object, function(it){
return it != it;
})) !== undefined;
}
function get(object, key){
if(has(object, key))return object[key];
}
function set(object, key, value){
if(DESCRIPTORS && key in Object)dP.f(object, key, createDesc(0, value));
else object[key] = value;
return object;
}
function isDict(it){
return isObject(it) && getPrototypeOf(it) === Dict.prototype;
}
$export($export.G + $export.F, {Dict: Dict});
$export($export.S, 'Dict', {
keys: createDictIter('keys'),
values: createDictIter('values'),
entries: createDictIter('entries'),
forEach: createDictMethod(0),
map: createDictMethod(1),
filter: createDictMethod(2),
some: createDictMethod(3),
every: createDictMethod(4),
find: createDictMethod(5),
findKey: findKey,
mapPairs: createDictMethod(7),
reduce: reduce,
keyOf: keyOf,
includes: includes,
has: has,
get: get,
set: set,
isDict: isDict
});
},{"./_a-function":6,"./_ctx":28,"./_descriptors":31,"./_export":35,"./_for-of":40,"./_has":42,"./_is-object":52,"./_iter-create":55,"./_iter-step":58,"./_keyof":60,"./_object-assign":68,"./_object-create":69,"./_object-dp":71,"./_object-gpo":78,"./_object-keys":80,"./_property-desc":89,"./_to-iobject":111,"./core.is-iterable":127}],124:[function(require,module,exports){
var path = require('./_path')
, $export = require('./_export');
// Placeholder
require('./_core')._ = path._ = path._ || {};
$export($export.P + $export.F, 'Function', {part: require('./_partial')});
},{"./_core":26,"./_export":35,"./_partial":87,"./_path":88}],125:[function(require,module,exports){
var classof = require('./_classof')
, ITERATOR = require('./_wks')('iterator')
, Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":20,"./_core":26,"./_iterators":59,"./_wks":121}],126:[function(require,module,exports){
var anObject = require('./_an-object')
, get = require('./core.get-iterator-method');
module.exports = require('./_core').getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
},{"./_an-object":10,"./_core":26,"./core.get-iterator-method":125}],127:[function(require,module,exports){
var classof = require('./_classof')
, ITERATOR = require('./_wks')('iterator')
, Iterators = require('./_iterators');
module.exports = require('./_core').isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
},{"./_classof":20,"./_core":26,"./_iterators":59,"./_wks":121}],128:[function(require,module,exports){
'use strict';
require('./_iter-define')(Number, 'Number', function(iterated){
this._l = +iterated;
this._i = 0;
}, function(){
var i = this._i++
, done = !(i < this._l);
return {done: done, value: done ? undefined : i};
});
},{"./_iter-define":56}],129:[function(require,module,exports){
var $export = require('./_export');
$export($export.S + $export.F, 'Object', {classof: require('./_classof')});
},{"./_classof":20,"./_export":35}],130:[function(require,module,exports){
var $export = require('./_export')
, define = require('./_object-define');
$export($export.S + $export.F, 'Object', {define: define});
},{"./_export":35,"./_object-define":70}],131:[function(require,module,exports){
var $export = require('./_export');
$export($export.S + $export.F, 'Object', {isObject: require('./_is-object')});
},{"./_export":35,"./_is-object":52}],132:[function(require,module,exports){
var $export = require('./_export')
, define = require('./_object-define')
, create = require('./_object-create');
$export($export.S + $export.F, 'Object', {
make: function(proto, mixin){
return define(create(proto), mixin);
}
});
},{"./_export":35,"./_object-create":69,"./_object-define":70}],133:[function(require,module,exports){
// https://github.com/benjamingr/RexExp.escape
var $export = require('./_export')
, $re = require('./_replacer')(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
},{"./_export":35,"./_replacer":92}],134:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $re = require('./_replacer')(/[&<>"']/g, {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&apos;'
});
$export($export.P + $export.F, 'String', {escapeHTML: function escapeHTML(){ return $re(this); }});
},{"./_export":35,"./_replacer":92}],135:[function(require,module,exports){
'use strict';
var $export = require('./_export');
var $re = require('./_replacer')(/&(?:amp|lt|gt|quot|apos);/g, {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&apos;': "'"
});
$export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }});
},{"./_export":35,"./_replacer":92}],136:[function(require,module,exports){
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', {copyWithin: require('./_array-copy-within')});
require('./_add-to-unscopables')('copyWithin');
},{"./_add-to-unscopables":8,"./_array-copy-within":11,"./_export":35}],137:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $every = require('./_array-methods')(4);
$export($export.P + $export.F * !require('./_strict-method')([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":15,"./_export":35,"./_strict-method":100}],138:[function(require,module,exports){
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = require('./_export');
$export($export.P, 'Array', {fill: require('./_array-fill')});
require('./_add-to-unscopables')('fill');
},{"./_add-to-unscopables":8,"./_array-fill":12,"./_export":35}],139:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $filter = require('./_array-methods')(2);
$export($export.P + $export.F * !require('./_strict-method')([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":15,"./_export":35,"./_strict-method":100}],140:[function(require,module,exports){
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = require('./_export')
, $find = require('./_array-methods')(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":8,"./_array-methods":15,"./_export":35}],141:[function(require,module,exports){
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = require('./_export')
, $find = require('./_array-methods')(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')(KEY);
},{"./_add-to-unscopables":8,"./_array-methods":15,"./_export":35}],142:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $forEach = require('./_array-methods')(0)
, STRICT = require('./_strict-method')([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":15,"./_export":35,"./_strict-method":100}],143:[function(require,module,exports){
'use strict';
var ctx = require('./_ctx')
, $export = require('./_export')
, toObject = require('./_to-object')
, call = require('./_iter-call')
, isArrayIter = require('./_is-array-iter')
, toLength = require('./_to-length')
, createProperty = require('./_create-property')
, getIterFn = require('./core.get-iterator-method');
$export($export.S + $export.F * !require('./_iter-detect')(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
},{"./_create-property":27,"./_ctx":28,"./_export":35,"./_is-array-iter":49,"./_iter-call":54,"./_iter-detect":57,"./_to-length":112,"./_to-object":113,"./core.get-iterator-method":125}],144:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $indexOf = require('./_array-includes')(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
},{"./_array-includes":14,"./_export":35,"./_strict-method":100}],145:[function(require,module,exports){
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = require('./_export');
$export($export.S, 'Array', {isArray: require('./_is-array')});
},{"./_export":35,"./_is-array":50}],146:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables')
, step = require('./_iter-step')
, Iterators = require('./_iterators')
, toIObject = require('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":8,"./_iter-define":56,"./_iter-step":58,"./_iterators":59,"./_to-iobject":111}],147:[function(require,module,exports){
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (require('./_iobject') != Object || !require('./_strict-method')(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
},{"./_export":35,"./_iobject":48,"./_strict-method":100,"./_to-iobject":111}],148:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, toInteger = require('./_to-integer')
, toLength = require('./_to-length')
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !require('./_strict-method')($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
},{"./_export":35,"./_strict-method":100,"./_to-integer":110,"./_to-iobject":111,"./_to-length":112}],149:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $map = require('./_array-methods')(1);
$export($export.P + $export.F * !require('./_strict-method')([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":15,"./_export":35,"./_strict-method":100}],150:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, createProperty = require('./_create-property');
// WebKit Array.of isn't generic
$export($export.S + $export.F * require('./_fails')(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
},{"./_create-property":27,"./_export":35,"./_fails":37}],151:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
},{"./_array-reduce":16,"./_export":35,"./_strict-method":100}],152:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $reduce = require('./_array-reduce');
$export($export.P + $export.F * !require('./_strict-method')([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
},{"./_array-reduce":16,"./_export":35,"./_strict-method":100}],153:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, html = require('./_html')
, cof = require('./_cof')
, toIndex = require('./_to-index')
, toLength = require('./_to-length')
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * require('./_fails')(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
},{"./_cof":21,"./_export":35,"./_fails":37,"./_html":44,"./_to-index":109,"./_to-length":112}],154:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $some = require('./_array-methods')(3);
$export($export.P + $export.F * !require('./_strict-method')([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
},{"./_array-methods":15,"./_export":35,"./_strict-method":100}],155:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, aFunction = require('./_a-function')
, toObject = require('./_to-object')
, fails = require('./_fails')
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !require('./_strict-method')($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
},{"./_a-function":6,"./_export":35,"./_fails":37,"./_strict-method":100,"./_to-object":113}],156:[function(require,module,exports){
require('./_set-species')('Array');
},{"./_set-species":95}],157:[function(require,module,exports){
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = require('./_export');
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
},{"./_export":35}],158:[function(require,module,exports){
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = require('./_export')
, fails = require('./_fails')
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
},{"./_export":35,"./_fails":37}],159:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive');
$export($export.P + $export.F * require('./_fails')(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
},{"./_export":35,"./_fails":37,"./_to-object":113,"./_to-primitive":114}],160:[function(require,module,exports){
var TO_PRIMITIVE = require('./_wks')('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))require('./_hide')(proto, TO_PRIMITIVE, require('./_date-to-primitive'));
},{"./_date-to-primitive":29,"./_hide":43,"./_wks":121}],161:[function(require,module,exports){
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
require('./_redefine')(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
},{"./_redefine":91}],162:[function(require,module,exports){
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = require('./_export');
$export($export.P, 'Function', {bind: require('./_bind')});
},{"./_bind":19,"./_export":35}],163:[function(require,module,exports){
'use strict';
var isObject = require('./_is-object')
, getPrototypeOf = require('./_object-gpo')
, HAS_INSTANCE = require('./_wks')('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))require('./_object-dp').f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
},{"./_is-object":52,"./_object-dp":71,"./_object-gpo":78,"./_wks":121}],164:[function(require,module,exports){
var dP = require('./_object-dp').f
, createDesc = require('./_property-desc')
, has = require('./_has')
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || require('./_descriptors') && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
},{"./_descriptors":31,"./_has":42,"./_object-dp":71,"./_property-desc":89}],165:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
// 23.1 Map Objects
module.exports = require('./_collection')('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"./_collection":25,"./_collection-strong":22}],166:[function(require,module,exports){
// 20.2.2.3 Math.acosh(x)
var $export = require('./_export')
, log1p = require('./_math-log1p')
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
},{"./_export":35,"./_math-log1p":63}],167:[function(require,module,exports){
// 20.2.2.5 Math.asinh(x)
var $export = require('./_export')
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
},{"./_export":35}],168:[function(require,module,exports){
// 20.2.2.7 Math.atanh(x)
var $export = require('./_export')
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
},{"./_export":35}],169:[function(require,module,exports){
// 20.2.2.9 Math.cbrt(x)
var $export = require('./_export')
, sign = require('./_math-sign');
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
},{"./_export":35,"./_math-sign":64}],170:[function(require,module,exports){
// 20.2.2.11 Math.clz32(x)
var $export = require('./_export');
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
},{"./_export":35}],171:[function(require,module,exports){
// 20.2.2.12 Math.cosh(x)
var $export = require('./_export')
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
},{"./_export":35}],172:[function(require,module,exports){
// 20.2.2.14 Math.expm1(x)
var $export = require('./_export')
, $expm1 = require('./_math-expm1');
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
},{"./_export":35,"./_math-expm1":62}],173:[function(require,module,exports){
// 20.2.2.16 Math.fround(x)
var $export = require('./_export')
, sign = require('./_math-sign')
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
},{"./_export":35,"./_math-sign":64}],174:[function(require,module,exports){
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = require('./_export')
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
},{"./_export":35}],175:[function(require,module,exports){
// 20.2.2.18 Math.imul(x, y)
var $export = require('./_export')
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * require('./_fails')(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
},{"./_export":35,"./_fails":37}],176:[function(require,module,exports){
// 20.2.2.21 Math.log10(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
},{"./_export":35}],177:[function(require,module,exports){
// 20.2.2.20 Math.log1p(x)
var $export = require('./_export');
$export($export.S, 'Math', {log1p: require('./_math-log1p')});
},{"./_export":35,"./_math-log1p":63}],178:[function(require,module,exports){
// 20.2.2.22 Math.log2(x)
var $export = require('./_export');
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
},{"./_export":35}],179:[function(require,module,exports){
// 20.2.2.28 Math.sign(x)
var $export = require('./_export');
$export($export.S, 'Math', {sign: require('./_math-sign')});
},{"./_export":35,"./_math-sign":64}],180:[function(require,module,exports){
// 20.2.2.30 Math.sinh(x)
var $export = require('./_export')
, expm1 = require('./_math-expm1')
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * require('./_fails')(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
},{"./_export":35,"./_fails":37,"./_math-expm1":62}],181:[function(require,module,exports){
// 20.2.2.33 Math.tanh(x)
var $export = require('./_export')
, expm1 = require('./_math-expm1')
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
},{"./_export":35,"./_math-expm1":62}],182:[function(require,module,exports){
// 20.2.2.34 Math.trunc(x)
var $export = require('./_export');
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
},{"./_export":35}],183:[function(require,module,exports){
'use strict';
var global = require('./_global')
, has = require('./_has')
, cof = require('./_cof')
, inheritIfRequired = require('./_inherit-if-required')
, toPrimitive = require('./_to-primitive')
, fails = require('./_fails')
, gOPN = require('./_object-gopn').f
, gOPD = require('./_object-gopd').f
, dP = require('./_object-dp').f
, $trim = require('./_string-trim').trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(require('./_object-create')(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = require('./_descriptors') ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
require('./_redefine')(global, NUMBER, $Number);
}
},{"./_cof":21,"./_descriptors":31,"./_fails":37,"./_global":41,"./_has":42,"./_inherit-if-required":46,"./_object-create":69,"./_object-dp":71,"./_object-gopd":74,"./_object-gopn":76,"./_redefine":91,"./_string-trim":106,"./_to-primitive":114}],184:[function(require,module,exports){
// 20.1.2.1 Number.EPSILON
var $export = require('./_export');
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
},{"./_export":35}],185:[function(require,module,exports){
// 20.1.2.2 Number.isFinite(number)
var $export = require('./_export')
, _isFinite = require('./_global').isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
},{"./_export":35,"./_global":41}],186:[function(require,module,exports){
// 20.1.2.3 Number.isInteger(number)
var $export = require('./_export');
$export($export.S, 'Number', {isInteger: require('./_is-integer')});
},{"./_export":35,"./_is-integer":51}],187:[function(require,module,exports){
// 20.1.2.4 Number.isNaN(number)
var $export = require('./_export');
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
},{"./_export":35}],188:[function(require,module,exports){
// 20.1.2.5 Number.isSafeInteger(number)
var $export = require('./_export')
, isInteger = require('./_is-integer')
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
},{"./_export":35,"./_is-integer":51}],189:[function(require,module,exports){
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
},{"./_export":35}],190:[function(require,module,exports){
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = require('./_export');
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
},{"./_export":35}],191:[function(require,module,exports){
var $export = require('./_export')
, $parseFloat = require('./_parse-float');
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
},{"./_export":35,"./_parse-float":85}],192:[function(require,module,exports){
var $export = require('./_export')
, $parseInt = require('./_parse-int');
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
},{"./_export":35,"./_parse-int":86}],193:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, anInstance = require('./_an-instance')
, toInteger = require('./_to-integer')
, aNumberValue = require('./_a-number-value')
, repeat = require('./_string-repeat')
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !require('./_fails')(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
},{"./_a-number-value":7,"./_an-instance":9,"./_export":35,"./_fails":37,"./_string-repeat":105,"./_to-integer":110}],194:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $fails = require('./_fails')
, aNumberValue = require('./_a-number-value')
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
},{"./_a-number-value":7,"./_export":35,"./_fails":37}],195:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $export = require('./_export');
$export($export.S + $export.F, 'Object', {assign: require('./_object-assign')});
},{"./_export":35,"./_object-assign":68}],196:[function(require,module,exports){
var $export = require('./_export')
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: require('./_object-create')});
},{"./_export":35,"./_object-create":69}],197:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperties: require('./_object-dps')});
},{"./_descriptors":31,"./_export":35,"./_object-dps":72}],198:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f});
},{"./_descriptors":31,"./_export":35,"./_object-dp":71}],199:[function(require,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"./_is-object":52,"./_meta":65,"./_object-sap":82}],200:[function(require,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = require('./_to-iobject')
, $getOwnPropertyDescriptor = require('./_object-gopd').f;
require('./_object-sap')('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./_object-gopd":74,"./_object-sap":82,"./_to-iobject":111}],201:[function(require,module,exports){
// 19.1.2.7 Object.getOwnPropertyNames(O)
require('./_object-sap')('getOwnPropertyNames', function(){
return require('./_object-gopn-ext').f;
});
},{"./_object-gopn-ext":75,"./_object-sap":82}],202:[function(require,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = require('./_to-object')
, $getPrototypeOf = require('./_object-gpo');
require('./_object-sap')('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"./_object-gpo":78,"./_object-sap":82,"./_to-object":113}],203:[function(require,module,exports){
// 19.1.2.11 Object.isExtensible(O)
var isObject = require('./_is-object');
require('./_object-sap')('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
},{"./_is-object":52,"./_object-sap":82}],204:[function(require,module,exports){
// 19.1.2.12 Object.isFrozen(O)
var isObject = require('./_is-object');
require('./_object-sap')('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
},{"./_is-object":52,"./_object-sap":82}],205:[function(require,module,exports){
// 19.1.2.13 Object.isSealed(O)
var isObject = require('./_is-object');
require('./_object-sap')('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
},{"./_is-object":52,"./_object-sap":82}],206:[function(require,module,exports){
// 19.1.3.10 Object.is(value1, value2)
var $export = require('./_export');
$export($export.S, 'Object', {is: require('./_same-value')});
},{"./_export":35,"./_same-value":93}],207:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object')
, $keys = require('./_object-keys');
require('./_object-sap')('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./_object-keys":80,"./_object-sap":82,"./_to-object":113}],208:[function(require,module,exports){
// 19.1.2.15 Object.preventExtensions(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
},{"./_is-object":52,"./_meta":65,"./_object-sap":82}],209:[function(require,module,exports){
// 19.1.2.17 Object.seal(O)
var isObject = require('./_is-object')
, meta = require('./_meta').onFreeze;
require('./_object-sap')('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
},{"./_is-object":52,"./_meta":65,"./_object-sap":82}],210:[function(require,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = require('./_export');
$export($export.S, 'Object', {setPrototypeOf: require('./_set-proto').set});
},{"./_export":35,"./_set-proto":94}],211:[function(require,module,exports){
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = require('./_classof')
, test = {};
test[require('./_wks')('toStringTag')] = 'z';
if(test + '' != '[object z]'){
require('./_redefine')(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
},{"./_classof":20,"./_redefine":91,"./_wks":121}],212:[function(require,module,exports){
var $export = require('./_export')
, $parseFloat = require('./_parse-float');
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
},{"./_export":35,"./_parse-float":85}],213:[function(require,module,exports){
var $export = require('./_export')
, $parseInt = require('./_parse-int');
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
},{"./_export":35,"./_parse-int":86}],214:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, global = require('./_global')
, ctx = require('./_ctx')
, classof = require('./_classof')
, $export = require('./_export')
, isObject = require('./_is-object')
, anObject = require('./_an-object')
, aFunction = require('./_a-function')
, anInstance = require('./_an-instance')
, forOf = require('./_for-of')
, setProto = require('./_set-proto').set
, speciesConstructor = require('./_species-constructor')
, task = require('./_task').set
, microtask = require('./_microtask')()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[require('./_wks')('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = require('./_redefine-all')($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
require('./_set-to-string-tag')($Promise, PROMISE);
require('./_set-species')(PROMISE);
Wrapper = require('./_core')[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && require('./_iter-detect')(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
},{"./_a-function":6,"./_an-instance":9,"./_an-object":10,"./_classof":20,"./_core":26,"./_ctx":28,"./_export":35,"./_for-of":40,"./_global":41,"./_is-object":52,"./_iter-detect":57,"./_library":61,"./_microtask":67,"./_redefine-all":90,"./_set-proto":94,"./_set-species":95,"./_set-to-string-tag":96,"./_species-constructor":99,"./_task":108,"./_wks":121}],215:[function(require,module,exports){
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = require('./_export')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(aFunction(target), thisArgument, anObject(argumentsList));
}
});
},{"./_a-function":6,"./_an-object":10,"./_export":35}],216:[function(require,module,exports){
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = require('./_export')
, create = require('./_object-create')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, isObject = require('./_is-object')
, bind = require('./_bind');
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * require('./_fails')(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
},{"./_a-function":6,"./_an-object":10,"./_bind":19,"./_export":35,"./_fails":37,"./_is-object":52,"./_object-create":69}],217:[function(require,module,exports){
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = require('./_object-dp')
, $export = require('./_export')
, anObject = require('./_an-object')
, toPrimitive = require('./_to-primitive');
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * require('./_fails')(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
},{"./_an-object":10,"./_export":35,"./_fails":37,"./_object-dp":71,"./_to-primitive":114}],218:[function(require,module,exports){
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = require('./_export')
, gOPD = require('./_object-gopd').f
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
},{"./_an-object":10,"./_export":35,"./_object-gopd":74}],219:[function(require,module,exports){
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = require('./_export')
, anObject = require('./_an-object');
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
require('./_iter-create')(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
},{"./_an-object":10,"./_export":35,"./_iter-create":55}],220:[function(require,module,exports){
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = require('./_object-gopd')
, $export = require('./_export')
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
},{"./_an-object":10,"./_export":35,"./_object-gopd":74}],221:[function(require,module,exports){
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = require('./_export')
, getProto = require('./_object-gpo')
, anObject = require('./_an-object');
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
},{"./_an-object":10,"./_export":35,"./_object-gpo":78}],222:[function(require,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = require('./_object-gopd')
, getPrototypeOf = require('./_object-gpo')
, has = require('./_has')
, $export = require('./_export')
, isObject = require('./_is-object')
, anObject = require('./_an-object');
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
},{"./_an-object":10,"./_export":35,"./_has":42,"./_is-object":52,"./_object-gopd":74,"./_object-gpo":78}],223:[function(require,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $export = require('./_export');
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
},{"./_export":35}],224:[function(require,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $export = require('./_export')
, anObject = require('./_an-object')
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
},{"./_an-object":10,"./_export":35}],225:[function(require,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $export = require('./_export');
$export($export.S, 'Reflect', {ownKeys: require('./_own-keys')});
},{"./_export":35,"./_own-keys":84}],226:[function(require,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $export = require('./_export')
, anObject = require('./_an-object')
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
},{"./_an-object":10,"./_export":35}],227:[function(require,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = require('./_export')
, setProto = require('./_set-proto');
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
},{"./_export":35,"./_set-proto":94}],228:[function(require,module,exports){
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = require('./_object-dp')
, gOPD = require('./_object-gopd')
, getPrototypeOf = require('./_object-gpo')
, has = require('./_has')
, $export = require('./_export')
, createDesc = require('./_property-desc')
, anObject = require('./_an-object')
, isObject = require('./_is-object');
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
},{"./_an-object":10,"./_export":35,"./_has":42,"./_is-object":52,"./_object-dp":71,"./_object-gopd":74,"./_object-gpo":78,"./_property-desc":89}],229:[function(require,module,exports){
var global = require('./_global')
, inheritIfRequired = require('./_inherit-if-required')
, dP = require('./_object-dp').f
, gOPN = require('./_object-gopn').f
, isRegExp = require('./_is-regexp')
, $flags = require('./_flags')
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(require('./_descriptors') && (!CORRECT_NEW || require('./_fails')(function(){
re2[require('./_wks')('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
require('./_redefine')(global, 'RegExp', $RegExp);
}
require('./_set-species')('RegExp');
},{"./_descriptors":31,"./_fails":37,"./_flags":39,"./_global":41,"./_inherit-if-required":46,"./_is-regexp":53,"./_object-dp":71,"./_object-gopn":76,"./_redefine":91,"./_set-species":95,"./_wks":121}],230:[function(require,module,exports){
// 21.2.5.3 get RegExp.prototype.flags()
if(require('./_descriptors') && /./g.flags != 'g')require('./_object-dp').f(RegExp.prototype, 'flags', {
configurable: true,
get: require('./_flags')
});
},{"./_descriptors":31,"./_flags":39,"./_object-dp":71}],231:[function(require,module,exports){
// @@match logic
require('./_fix-re-wks')('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
},{"./_fix-re-wks":38}],232:[function(require,module,exports){
// @@replace logic
require('./_fix-re-wks')('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
},{"./_fix-re-wks":38}],233:[function(require,module,exports){
// @@search logic
require('./_fix-re-wks')('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
},{"./_fix-re-wks":38}],234:[function(require,module,exports){
// @@split logic
require('./_fix-re-wks')('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = require('./_is-regexp')
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
},{"./_fix-re-wks":38,"./_is-regexp":53}],235:[function(require,module,exports){
'use strict';
require('./es6.regexp.flags');
var anObject = require('./_an-object')
, $flags = require('./_flags')
, DESCRIPTORS = require('./_descriptors')
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
require('./_redefine')(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(require('./_fails')(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
},{"./_an-object":10,"./_descriptors":31,"./_fails":37,"./_flags":39,"./_redefine":91,"./es6.regexp.flags":230}],236:[function(require,module,exports){
'use strict';
var strong = require('./_collection-strong');
// 23.2 Set Objects
module.exports = require('./_collection')('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
},{"./_collection":25,"./_collection-strong":22}],237:[function(require,module,exports){
'use strict';
// B.2.3.2 String.prototype.anchor(name)
require('./_string-html')('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
},{"./_string-html":103}],238:[function(require,module,exports){
'use strict';
// B.2.3.3 String.prototype.big()
require('./_string-html')('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
},{"./_string-html":103}],239:[function(require,module,exports){
'use strict';
// B.2.3.4 String.prototype.blink()
require('./_string-html')('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
},{"./_string-html":103}],240:[function(require,module,exports){
'use strict';
// B.2.3.5 String.prototype.bold()
require('./_string-html')('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
},{"./_string-html":103}],241:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $at = require('./_string-at')(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
},{"./_export":35,"./_string-at":101}],242:[function(require,module,exports){
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = require('./_export')
, toLength = require('./_to-length')
, context = require('./_string-context')
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
},{"./_export":35,"./_fails-is-regexp":36,"./_string-context":102,"./_to-length":112}],243:[function(require,module,exports){
'use strict';
// B.2.3.6 String.prototype.fixed()
require('./_string-html')('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
},{"./_string-html":103}],244:[function(require,module,exports){
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
require('./_string-html')('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
},{"./_string-html":103}],245:[function(require,module,exports){
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
require('./_string-html')('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
},{"./_string-html":103}],246:[function(require,module,exports){
var $export = require('./_export')
, toIndex = require('./_to-index')
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
},{"./_export":35,"./_to-index":109}],247:[function(require,module,exports){
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = require('./_export')
, context = require('./_string-context')
, INCLUDES = 'includes';
$export($export.P + $export.F * require('./_fails-is-regexp')(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
},{"./_export":35,"./_fails-is-regexp":36,"./_string-context":102}],248:[function(require,module,exports){
'use strict';
// B.2.3.9 String.prototype.italics()
require('./_string-html')('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
},{"./_string-html":103}],249:[function(require,module,exports){
'use strict';
var $at = require('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./_iter-define":56,"./_string-at":101}],250:[function(require,module,exports){
'use strict';
// B.2.3.10 String.prototype.link(url)
require('./_string-html')('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
},{"./_string-html":103}],251:[function(require,module,exports){
var $export = require('./_export')
, toIObject = require('./_to-iobject')
, toLength = require('./_to-length');
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
},{"./_export":35,"./_to-iobject":111,"./_to-length":112}],252:[function(require,module,exports){
var $export = require('./_export');
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: require('./_string-repeat')
});
},{"./_export":35,"./_string-repeat":105}],253:[function(require,module,exports){
'use strict';
// B.2.3.11 String.prototype.small()
require('./_string-html')('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
},{"./_string-html":103}],254:[function(require,module,exports){
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = require('./_export')
, toLength = require('./_to-length')
, context = require('./_string-context')
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * require('./_fails-is-regexp')(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
},{"./_export":35,"./_fails-is-regexp":36,"./_string-context":102,"./_to-length":112}],255:[function(require,module,exports){
'use strict';
// B.2.3.12 String.prototype.strike()
require('./_string-html')('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
},{"./_string-html":103}],256:[function(require,module,exports){
'use strict';
// B.2.3.13 String.prototype.sub()
require('./_string-html')('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
},{"./_string-html":103}],257:[function(require,module,exports){
'use strict';
// B.2.3.14 String.prototype.sup()
require('./_string-html')('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
},{"./_string-html":103}],258:[function(require,module,exports){
'use strict';
// 21.1.3.25 String.prototype.trim()
require('./_string-trim')('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
},{"./_string-trim":106}],259:[function(require,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = require('./_global')
, has = require('./_has')
, DESCRIPTORS = require('./_descriptors')
, $export = require('./_export')
, redefine = require('./_redefine')
, META = require('./_meta').KEY
, $fails = require('./_fails')
, shared = require('./_shared')
, setToStringTag = require('./_set-to-string-tag')
, uid = require('./_uid')
, wks = require('./_wks')
, wksExt = require('./_wks-ext')
, wksDefine = require('./_wks-define')
, keyOf = require('./_keyof')
, enumKeys = require('./_enum-keys')
, isArray = require('./_is-array')
, anObject = require('./_an-object')
, toIObject = require('./_to-iobject')
, toPrimitive = require('./_to-primitive')
, createDesc = require('./_property-desc')
, _create = require('./_object-create')
, gOPNExt = require('./_object-gopn-ext')
, $GOPD = require('./_object-gopd')
, $DP = require('./_object-dp')
, $keys = require('./_object-keys')
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
require('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
require('./_object-pie').f = $propertyIsEnumerable;
require('./_object-gops').f = $getOwnPropertySymbols;
if(DESCRIPTORS && !require('./_library')){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || require('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./_an-object":10,"./_descriptors":31,"./_enum-keys":34,"./_export":35,"./_fails":37,"./_global":41,"./_has":42,"./_hide":43,"./_is-array":50,"./_keyof":60,"./_library":61,"./_meta":65,"./_object-create":69,"./_object-dp":71,"./_object-gopd":74,"./_object-gopn":76,"./_object-gopn-ext":75,"./_object-gops":77,"./_object-keys":80,"./_object-pie":81,"./_property-desc":89,"./_redefine":91,"./_set-to-string-tag":96,"./_shared":98,"./_to-iobject":111,"./_to-primitive":114,"./_uid":118,"./_wks":121,"./_wks-define":119,"./_wks-ext":120}],260:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, $typed = require('./_typed')
, buffer = require('./_typed-buffer')
, anObject = require('./_an-object')
, toIndex = require('./_to-index')
, toLength = require('./_to-length')
, isObject = require('./_is-object')
, TYPED_ARRAY = require('./_wks')('typed_array')
, ArrayBuffer = require('./_global').ArrayBuffer
, speciesConstructor = require('./_species-constructor')
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * require('./_fails')(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
require('./_set-species')(ARRAY_BUFFER);
},{"./_an-object":10,"./_export":35,"./_fails":37,"./_global":41,"./_is-object":52,"./_set-species":95,"./_species-constructor":99,"./_to-index":109,"./_to-length":112,"./_typed":117,"./_typed-buffer":116,"./_wks":121}],261:[function(require,module,exports){
var $export = require('./_export');
$export($export.G + $export.W + $export.F * !require('./_typed').ABV, {
DataView: require('./_typed-buffer').DataView
});
},{"./_export":35,"./_typed":117,"./_typed-buffer":116}],262:[function(require,module,exports){
require('./_typed-array')('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],263:[function(require,module,exports){
require('./_typed-array')('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],264:[function(require,module,exports){
require('./_typed-array')('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],265:[function(require,module,exports){
require('./_typed-array')('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],266:[function(require,module,exports){
require('./_typed-array')('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],267:[function(require,module,exports){
require('./_typed-array')('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],268:[function(require,module,exports){
require('./_typed-array')('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],269:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
},{"./_typed-array":115}],270:[function(require,module,exports){
require('./_typed-array')('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
},{"./_typed-array":115}],271:[function(require,module,exports){
'use strict';
var each = require('./_array-methods')(0)
, redefine = require('./_redefine')
, meta = require('./_meta')
, assign = require('./_object-assign')
, weak = require('./_collection-weak')
, isObject = require('./_is-object')
, has = require('./_has')
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = require('./_collection')('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"./_array-methods":15,"./_collection":25,"./_collection-weak":24,"./_has":42,"./_is-object":52,"./_meta":65,"./_object-assign":68,"./_redefine":91}],272:[function(require,module,exports){
'use strict';
var weak = require('./_collection-weak');
// 23.4 WeakSet Objects
require('./_collection')('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
},{"./_collection":25,"./_collection-weak":24}],273:[function(require,module,exports){
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = require('./_export')
, $includes = require('./_array-includes')(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
require('./_add-to-unscopables')('includes');
},{"./_add-to-unscopables":8,"./_array-includes":14,"./_export":35}],274:[function(require,module,exports){
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = require('./_export')
, microtask = require('./_microtask')()
, process = require('./_global').process
, isNode = require('./_cof')(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
},{"./_cof":21,"./_export":35,"./_global":41,"./_microtask":67}],275:[function(require,module,exports){
// https://github.com/ljharb/proposal-is-error
var $export = require('./_export')
, cof = require('./_cof');
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
},{"./_cof":21,"./_export":35}],276:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Map', {toJSON: require('./_collection-to-json')('Map')});
},{"./_collection-to-json":23,"./_export":35}],277:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
},{"./_export":35}],278:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
},{"./_export":35}],279:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
},{"./_export":35}],280:[function(require,module,exports){
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = require('./_export');
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
},{"./_export":35}],281:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, aFunction = require('./_a-function')
, $defineProperty = require('./_object-dp');
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
},{"./_a-function":6,"./_descriptors":31,"./_export":35,"./_object-dp":71,"./_object-forced-pam":73,"./_to-object":113}],282:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, aFunction = require('./_a-function')
, $defineProperty = require('./_object-dp');
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
},{"./_a-function":6,"./_descriptors":31,"./_export":35,"./_object-dp":71,"./_object-forced-pam":73,"./_to-object":113}],283:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export')
, $entries = require('./_object-to-array')(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
},{"./_export":35,"./_object-to-array":83}],284:[function(require,module,exports){
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = require('./_export')
, ownKeys = require('./_own-keys')
, toIObject = require('./_to-iobject')
, gOPD = require('./_object-gopd')
, createProperty = require('./_create-property');
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
},{"./_create-property":27,"./_export":35,"./_object-gopd":74,"./_own-keys":84,"./_to-iobject":111}],285:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive')
, getPrototypeOf = require('./_object-gpo')
, getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
},{"./_descriptors":31,"./_export":35,"./_object-forced-pam":73,"./_object-gopd":74,"./_object-gpo":78,"./_to-object":113,"./_to-primitive":114}],286:[function(require,module,exports){
'use strict';
var $export = require('./_export')
, toObject = require('./_to-object')
, toPrimitive = require('./_to-primitive')
, getPrototypeOf = require('./_object-gpo')
, getOwnPropertyDescriptor = require('./_object-gopd').f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
require('./_descriptors') && $export($export.P + require('./_object-forced-pam'), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
},{"./_descriptors":31,"./_export":35,"./_object-forced-pam":73,"./_object-gopd":74,"./_object-gpo":78,"./_to-object":113,"./_to-primitive":114}],287:[function(require,module,exports){
// https://github.com/tc39/proposal-object-values-entries
var $export = require('./_export')
, $values = require('./_object-to-array')(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
},{"./_export":35,"./_object-to-array":83}],288:[function(require,module,exports){
'use strict';
// https://github.com/zenparsing/es-observable
var $export = require('./_export')
, global = require('./_global')
, core = require('./_core')
, microtask = require('./_microtask')()
, OBSERVABLE = require('./_wks')('observable')
, aFunction = require('./_a-function')
, anObject = require('./_an-object')
, anInstance = require('./_an-instance')
, redefineAll = require('./_redefine-all')
, hide = require('./_hide')
, forOf = require('./_for-of')
, RETURN = forOf.RETURN;
var getMethod = function(fn){
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function(subscription){
var cleanup = subscription._c;
if(cleanup){
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function(subscription){
return subscription._o === undefined;
};
var closeSubscription = function(subscription){
if(!subscriptionClosed(subscription)){
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function(observer, subscriber){
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer)
, subscription = cleanup;
if(cleanup != null){
if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch(e){
observer.error(e);
return;
} if(subscriptionClosed(this))cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe(){ closeSubscription(this); }
});
var SubscriptionObserver = function(subscription){
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if(m)return m.call(observer, value);
} catch(e){
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value){
var subscription = this._s;
if(subscriptionClosed(subscription))throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if(!m)throw value;
value = m.call(observer, value);
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber){
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer){
return new Subscription(observer, this._f);
},
forEach: function forEach(fn){
var that = this;
return new (core.Promise || global.Promise)(function(resolve, reject){
aFunction(fn);
var subscription = that.subscribe({
next : function(value){
try {
return fn(value);
} catch(e){
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x){
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if(method){
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function(observer){
return observable.subscribe(observer);
});
}
return new C(function(observer){
var done = false;
microtask(function(){
if(!done){
try {
if(forOf(x, false, function(it){
observer.next(it);
if(done)return RETURN;
}) === RETURN)return;
} catch(e){
if(done)throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function(){ done = true; };
});
},
of: function of(){
for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function(observer){
var done = false;
microtask(function(){
if(!done){
for(var i = 0; i < items.length; ++i){
observer.next(items[i]);
if(done)return;
} observer.complete();
}
});
return function(){ done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function(){ return this; });
$export($export.G, {Observable: $Observable});
require('./_set-species')('Observable');
},{"./_a-function":6,"./_an-instance":9,"./_an-object":10,"./_core":26,"./_export":35,"./_for-of":40,"./_global":41,"./_hide":43,"./_microtask":67,"./_redefine-all":90,"./_set-species":95,"./_wks":121}],289:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
},{"./_an-object":10,"./_metadata":66}],290:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
},{"./_an-object":10,"./_metadata":66}],291:[function(require,module,exports){
var Set = require('./es6.set')
, from = require('./_array-from-iterable')
, metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"./_an-object":10,"./_array-from-iterable":13,"./_metadata":66,"./_object-gpo":78,"./es6.set":236}],292:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":10,"./_metadata":66,"./_object-gpo":78}],293:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
},{"./_an-object":10,"./_metadata":66}],294:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":10,"./_metadata":66}],295:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":10,"./_metadata":66,"./_object-gpo":78}],296:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
},{"./_an-object":10,"./_metadata":66}],297:[function(require,module,exports){
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, aFunction = require('./_a-function')
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
},{"./_a-function":6,"./_an-object":10,"./_metadata":66}],298:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = require('./_export');
$export($export.P + $export.R, 'Set', {toJSON: require('./_collection-to-json')('Set')});
},{"./_collection-to-json":23,"./_export":35}],299:[function(require,module,exports){
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = require('./_export')
, $at = require('./_string-at')(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
},{"./_export":35,"./_string-at":101}],300:[function(require,module,exports){
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = require('./_export')
, defined = require('./_defined')
, toLength = require('./_to-length')
, isRegExp = require('./_is-regexp')
, getFlags = require('./_flags')
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
require('./_iter-create')($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
},{"./_defined":30,"./_export":35,"./_flags":39,"./_is-regexp":53,"./_iter-create":55,"./_to-length":112}],301:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export')
, $pad = require('./_string-pad');
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
},{"./_export":35,"./_string-pad":104}],302:[function(require,module,exports){
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = require('./_export')
, $pad = require('./_string-pad');
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
},{"./_export":35,"./_string-pad":104}],303:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
},{"./_string-trim":106}],304:[function(require,module,exports){
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
require('./_string-trim')('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
},{"./_string-trim":106}],305:[function(require,module,exports){
require('./_wks-define')('asyncIterator');
},{"./_wks-define":119}],306:[function(require,module,exports){
require('./_wks-define')('observable');
},{"./_wks-define":119}],307:[function(require,module,exports){
// https://github.com/ljharb/proposal-global
var $export = require('./_export');
$export($export.S, 'System', {global: require('./_global')});
},{"./_export":35,"./_global":41}],308:[function(require,module,exports){
var $iterators = require('./es6.array.iterator')
, redefine = require('./_redefine')
, global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, wks = require('./_wks')
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
},{"./_global":41,"./_hide":43,"./_iterators":59,"./_redefine":91,"./_wks":121,"./es6.array.iterator":146}],309:[function(require,module,exports){
var $export = require('./_export')
, $task = require('./_task');
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
},{"./_export":35,"./_task":108}],310:[function(require,module,exports){
// ie9- setTimeout & setInterval additional parameters fix
var global = require('./_global')
, $export = require('./_export')
, invoke = require('./_invoke')
, partial = require('./_partial')
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
},{"./_export":35,"./_global":41,"./_invoke":47,"./_partial":87}],311:[function(require,module,exports){
require('./modules/es6.symbol');
require('./modules/es6.object.create');
require('./modules/es6.object.define-property');
require('./modules/es6.object.define-properties');
require('./modules/es6.object.get-own-property-descriptor');
require('./modules/es6.object.get-prototype-of');
require('./modules/es6.object.keys');
require('./modules/es6.object.get-own-property-names');
require('./modules/es6.object.freeze');
require('./modules/es6.object.seal');
require('./modules/es6.object.prevent-extensions');
require('./modules/es6.object.is-frozen');
require('./modules/es6.object.is-sealed');
require('./modules/es6.object.is-extensible');
require('./modules/es6.object.assign');
require('./modules/es6.object.is');
require('./modules/es6.object.set-prototype-of');
require('./modules/es6.object.to-string');
require('./modules/es6.function.bind');
require('./modules/es6.function.name');
require('./modules/es6.function.has-instance');
require('./modules/es6.parse-int');
require('./modules/es6.parse-float');
require('./modules/es6.number.constructor');
require('./modules/es6.number.to-fixed');
require('./modules/es6.number.to-precision');
require('./modules/es6.number.epsilon');
require('./modules/es6.number.is-finite');
require('./modules/es6.number.is-integer');
require('./modules/es6.number.is-nan');
require('./modules/es6.number.is-safe-integer');
require('./modules/es6.number.max-safe-integer');
require('./modules/es6.number.min-safe-integer');
require('./modules/es6.number.parse-float');
require('./modules/es6.number.parse-int');
require('./modules/es6.math.acosh');
require('./modules/es6.math.asinh');
require('./modules/es6.math.atanh');
require('./modules/es6.math.cbrt');
require('./modules/es6.math.clz32');
require('./modules/es6.math.cosh');
require('./modules/es6.math.expm1');
require('./modules/es6.math.fround');
require('./modules/es6.math.hypot');
require('./modules/es6.math.imul');
require('./modules/es6.math.log10');
require('./modules/es6.math.log1p');
require('./modules/es6.math.log2');
require('./modules/es6.math.sign');
require('./modules/es6.math.sinh');
require('./modules/es6.math.tanh');
require('./modules/es6.math.trunc');
require('./modules/es6.string.from-code-point');
require('./modules/es6.string.raw');
require('./modules/es6.string.trim');
require('./modules/es6.string.iterator');
require('./modules/es6.string.code-point-at');
require('./modules/es6.string.ends-with');
require('./modules/es6.string.includes');
require('./modules/es6.string.repeat');
require('./modules/es6.string.starts-with');
require('./modules/es6.string.anchor');
require('./modules/es6.string.big');
require('./modules/es6.string.blink');
require('./modules/es6.string.bold');
require('./modules/es6.string.fixed');
require('./modules/es6.string.fontcolor');
require('./modules/es6.string.fontsize');
require('./modules/es6.string.italics');
require('./modules/es6.string.link');
require('./modules/es6.string.small');
require('./modules/es6.string.strike');
require('./modules/es6.string.sub');
require('./modules/es6.string.sup');
require('./modules/es6.date.now');
require('./modules/es6.date.to-json');
require('./modules/es6.date.to-iso-string');
require('./modules/es6.date.to-string');
require('./modules/es6.date.to-primitive');
require('./modules/es6.array.is-array');
require('./modules/es6.array.from');
require('./modules/es6.array.of');
require('./modules/es6.array.join');
require('./modules/es6.array.slice');
require('./modules/es6.array.sort');
require('./modules/es6.array.for-each');
require('./modules/es6.array.map');
require('./modules/es6.array.filter');
require('./modules/es6.array.some');
require('./modules/es6.array.every');
require('./modules/es6.array.reduce');
require('./modules/es6.array.reduce-right');
require('./modules/es6.array.index-of');
require('./modules/es6.array.last-index-of');
require('./modules/es6.array.copy-within');
require('./modules/es6.array.fill');
require('./modules/es6.array.find');
require('./modules/es6.array.find-index');
require('./modules/es6.array.species');
require('./modules/es6.array.iterator');
require('./modules/es6.regexp.constructor');
require('./modules/es6.regexp.to-string');
require('./modules/es6.regexp.flags');
require('./modules/es6.regexp.match');
require('./modules/es6.regexp.replace');
require('./modules/es6.regexp.search');
require('./modules/es6.regexp.split');
require('./modules/es6.promise');
require('./modules/es6.map');
require('./modules/es6.set');
require('./modules/es6.weak-map');
require('./modules/es6.weak-set');
require('./modules/es6.typed.array-buffer');
require('./modules/es6.typed.data-view');
require('./modules/es6.typed.int8-array');
require('./modules/es6.typed.uint8-array');
require('./modules/es6.typed.uint8-clamped-array');
require('./modules/es6.typed.int16-array');
require('./modules/es6.typed.uint16-array');
require('./modules/es6.typed.int32-array');
require('./modules/es6.typed.uint32-array');
require('./modules/es6.typed.float32-array');
require('./modules/es6.typed.float64-array');
require('./modules/es6.reflect.apply');
require('./modules/es6.reflect.construct');
require('./modules/es6.reflect.define-property');
require('./modules/es6.reflect.delete-property');
require('./modules/es6.reflect.enumerate');
require('./modules/es6.reflect.get');
require('./modules/es6.reflect.get-own-property-descriptor');
require('./modules/es6.reflect.get-prototype-of');
require('./modules/es6.reflect.has');
require('./modules/es6.reflect.is-extensible');
require('./modules/es6.reflect.own-keys');
require('./modules/es6.reflect.prevent-extensions');
require('./modules/es6.reflect.set');
require('./modules/es6.reflect.set-prototype-of');
require('./modules/es7.array.includes');
require('./modules/es7.string.at');
require('./modules/es7.string.pad-start');
require('./modules/es7.string.pad-end');
require('./modules/es7.string.trim-left');
require('./modules/es7.string.trim-right');
require('./modules/es7.string.match-all');
require('./modules/es7.symbol.async-iterator');
require('./modules/es7.symbol.observable');
require('./modules/es7.object.get-own-property-descriptors');
require('./modules/es7.object.values');
require('./modules/es7.object.entries');
require('./modules/es7.object.define-getter');
require('./modules/es7.object.define-setter');
require('./modules/es7.object.lookup-getter');
require('./modules/es7.object.lookup-setter');
require('./modules/es7.map.to-json');
require('./modules/es7.set.to-json');
require('./modules/es7.system.global');
require('./modules/es7.error.is-error');
require('./modules/es7.math.iaddh');
require('./modules/es7.math.isubh');
require('./modules/es7.math.imulh');
require('./modules/es7.math.umulh');
require('./modules/es7.reflect.define-metadata');
require('./modules/es7.reflect.delete-metadata');
require('./modules/es7.reflect.get-metadata');
require('./modules/es7.reflect.get-metadata-keys');
require('./modules/es7.reflect.get-own-metadata');
require('./modules/es7.reflect.get-own-metadata-keys');
require('./modules/es7.reflect.has-metadata');
require('./modules/es7.reflect.has-own-metadata');
require('./modules/es7.reflect.metadata');
require('./modules/es7.asap');
require('./modules/es7.observable');
require('./modules/web.timers');
require('./modules/web.immediate');
require('./modules/web.dom.iterable');
module.exports = require('./modules/_core');
},{"./modules/_core":26,"./modules/es6.array.copy-within":136,"./modules/es6.array.every":137,"./modules/es6.array.fill":138,"./modules/es6.array.filter":139,"./modules/es6.array.find":141,"./modules/es6.array.find-index":140,"./modules/es6.array.for-each":142,"./modules/es6.array.from":143,"./modules/es6.array.index-of":144,"./modules/es6.array.is-array":145,"./modules/es6.array.iterator":146,"./modules/es6.array.join":147,"./modules/es6.array.last-index-of":148,"./modules/es6.array.map":149,"./modules/es6.array.of":150,"./modules/es6.array.reduce":152,"./modules/es6.array.reduce-right":151,"./modules/es6.array.slice":153,"./modules/es6.array.some":154,"./modules/es6.array.sort":155,"./modules/es6.array.species":156,"./modules/es6.date.now":157,"./modules/es6.date.to-iso-string":158,"./modules/es6.date.to-json":159,"./modules/es6.date.to-primitive":160,"./modules/es6.date.to-string":161,"./modules/es6.function.bind":162,"./modules/es6.function.has-instance":163,"./modules/es6.function.name":164,"./modules/es6.map":165,"./modules/es6.math.acosh":166,"./modules/es6.math.asinh":167,"./modules/es6.math.atanh":168,"./modules/es6.math.cbrt":169,"./modules/es6.math.clz32":170,"./modules/es6.math.cosh":171,"./modules/es6.math.expm1":172,"./modules/es6.math.fround":173,"./modules/es6.math.hypot":174,"./modules/es6.math.imul":175,"./modules/es6.math.log10":176,"./modules/es6.math.log1p":177,"./modules/es6.math.log2":178,"./modules/es6.math.sign":179,"./modules/es6.math.sinh":180,"./modules/es6.math.tanh":181,"./modules/es6.math.trunc":182,"./modules/es6.number.constructor":183,"./modules/es6.number.epsilon":184,"./modules/es6.number.is-finite":185,"./modules/es6.number.is-integer":186,"./modules/es6.number.is-nan":187,"./modules/es6.number.is-safe-integer":188,"./modules/es6.number.max-safe-integer":189,"./modules/es6.number.min-safe-integer":190,"./modules/es6.number.parse-float":191,"./modules/es6.number.parse-int":192,"./modules/es6.number.to-fixed":193,"./modules/es6.number.to-precision":194,"./modules/es6.object.assign":195,"./modules/es6.object.create":196,"./modules/es6.object.define-properties":197,"./modules/es6.object.define-property":198,"./modules/es6.object.freeze":199,"./modules/es6.object.get-own-property-descriptor":200,"./modules/es6.object.get-own-property-names":201,"./modules/es6.object.get-prototype-of":202,"./modules/es6.object.is":206,"./modules/es6.object.is-extensible":203,"./modules/es6.object.is-frozen":204,"./modules/es6.object.is-sealed":205,"./modules/es6.object.keys":207,"./modules/es6.object.prevent-extensions":208,"./modules/es6.object.seal":209,"./modules/es6.object.set-prototype-of":210,"./modules/es6.object.to-string":211,"./modules/es6.parse-float":212,"./modules/es6.parse-int":213,"./modules/es6.promise":214,"./modules/es6.reflect.apply":215,"./modules/es6.reflect.construct":216,"./modules/es6.reflect.define-property":217,"./modules/es6.reflect.delete-property":218,"./modules/es6.reflect.enumerate":219,"./modules/es6.reflect.get":222,"./modules/es6.reflect.get-own-property-descriptor":220,"./modules/es6.reflect.get-prototype-of":221,"./modules/es6.reflect.has":223,"./modules/es6.reflect.is-extensible":224,"./modules/es6.reflect.own-keys":225,"./modules/es6.reflect.prevent-extensions":226,"./modules/es6.reflect.set":228,"./modules/es6.reflect.set-prototype-of":227,"./modules/es6.regexp.constructor":229,"./modules/es6.regexp.flags":230,"./modules/es6.regexp.match":231,"./modules/es6.regexp.replace":232,"./modules/es6.regexp.search":233,"./modules/es6.regexp.split":234,"./modules/es6.regexp.to-string":235,"./modules/es6.set":236,"./modules/es6.string.anchor":237,"./modules/es6.string.big":238,"./modules/es6.string.blink":239,"./modules/es6.string.bold":240,"./modules/es6.string.code-point-at":241,"./modules/es6.string.ends-with":242,"./modules/es6.string.fixed":243,"./modules/es6.string.fontcolor":244,"./modules/es6.string.fontsize":245,"./modules/es6.string.from-code-point":246,"./modules/es6.string.includes":247,"./modules/es6.string.italics":248,"./modules/es6.string.iterator":249,"./modules/es6.string.link":250,"./modules/es6.string.raw":251,"./modules/es6.string.repeat":252,"./modules/es6.string.small":253,"./modules/es6.string.starts-with":254,"./modules/es6.string.strike":255,"./modules/es6.string.sub":256,"./modules/es6.string.sup":257,"./modules/es6.string.trim":258,"./modules/es6.symbol":259,"./modules/es6.typed.array-buffer":260,"./modules/es6.typed.data-view":261,"./modules/es6.typed.float32-array":262,"./modules/es6.typed.float64-array":263,"./modules/es6.typed.int16-array":264,"./modules/es6.typed.int32-array":265,"./modules/es6.typed.int8-array":266,"./modules/es6.typed.uint16-array":267,"./modules/es6.typed.uint32-array":268,"./modules/es6.typed.uint8-array":269,"./modules/es6.typed.uint8-clamped-array":270,"./modules/es6.weak-map":271,"./modules/es6.weak-set":272,"./modules/es7.array.includes":273,"./modules/es7.asap":274,"./modules/es7.error.is-error":275,"./modules/es7.map.to-json":276,"./modules/es7.math.iaddh":277,"./modules/es7.math.imulh":278,"./modules/es7.math.isubh":279,"./modules/es7.math.umulh":280,"./modules/es7.object.define-getter":281,"./modules/es7.object.define-setter":282,"./modules/es7.object.entries":283,"./modules/es7.object.get-own-property-descriptors":284,"./modules/es7.object.lookup-getter":285,"./modules/es7.object.lookup-setter":286,"./modules/es7.object.values":287,"./modules/es7.observable":288,"./modules/es7.reflect.define-metadata":289,"./modules/es7.reflect.delete-metadata":290,"./modules/es7.reflect.get-metadata":292,"./modules/es7.reflect.get-metadata-keys":291,"./modules/es7.reflect.get-own-metadata":294,"./modules/es7.reflect.get-own-metadata-keys":293,"./modules/es7.reflect.has-metadata":295,"./modules/es7.reflect.has-own-metadata":296,"./modules/es7.reflect.metadata":297,"./modules/es7.set.to-json":298,"./modules/es7.string.at":299,"./modules/es7.string.match-all":300,"./modules/es7.string.pad-end":301,"./modules/es7.string.pad-start":302,"./modules/es7.string.trim-left":303,"./modules/es7.string.trim-right":304,"./modules/es7.symbol.async-iterator":305,"./modules/es7.symbol.observable":306,"./modules/es7.system.global":307,"./modules/web.dom.iterable":308,"./modules/web.immediate":309,"./modules/web.timers":310}],312:[function(require,module,exports){
/*!
Copyright (C) 2013-2015 by Andrea Giammarchi - @WebReflection
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function(window){'use strict';
/* jshint loopfunc: true, noempty: false*/
// http://www.w3.org/TR/dom/#element
function createDocumentFragment() {
return document.createDocumentFragment();
}
function createElement(nodeName) {
return document.createElement(nodeName);
}
function enoughArguments(length, name) {
if (!length) throw new Error(
'Failed to construct ' +
name +
': 1 argument required, but only 0 present.'
);
}
function mutationMacro(nodes) {
if (nodes.length === 1) {
return textNodeIfString(nodes[0]);
}
for (var
fragment = createDocumentFragment(),
list = slice.call(nodes),
i = 0; i < nodes.length; i++
) {
fragment.appendChild(textNodeIfString(list[i]));
}
return fragment;
}
function textNodeIfString(node) {
return typeof node === 'string' ? document.createTextNode(node) : node;
}
for(var
head,
property,
TemporaryPrototype,
TemporaryTokenList,
wrapVerifyToken,
document = window.document,
hOP = Object.prototype.hasOwnProperty,
defineProperty = Object.defineProperty || function (object, property, descriptor) {
if (hOP.call(descriptor, 'value')) {
object[property] = descriptor.value;
} else {
if (hOP.call(descriptor, 'get'))
object.__defineGetter__(property, descriptor.get);
if (hOP.call(descriptor, 'set'))
object.__defineSetter__(property, descriptor.set);
}
return object;
},
indexOf = [].indexOf || function indexOf(value){
var length = this.length;
while(length--) {
if (this[length] === value) {
break;
}
}
return length;
},
// http://www.w3.org/TR/domcore/#domtokenlist
verifyToken = function (token) {
if (!token) {
throw 'SyntaxError';
} else if (spaces.test(token)) {
throw 'InvalidCharacterError';
}
return token;
},
DOMTokenList = function (node) {
var
noClassName = typeof node.className === 'undefined',
className = noClassName ?
(node.getAttribute('class') || '') : node.className,
isSVG = noClassName || typeof className === 'object',
value = (isSVG ?
(noClassName ? className : className.baseVal) :
className
).replace(trim, '')
;
if (value.length) {
properties.push.apply(
this,
value.split(spaces)
);
}
this._isSVG = isSVG;
this._ = node;
},
classListDescriptor = {
get: function get() {
return new DOMTokenList(this);
},
set: function(){}
},
uid = 'dom4-tmp-'.concat(Math.random() * +new Date()).replace('.','-'),
trim = /^\s+|\s+$/g,
spaces = /\s+/,
SPACE = '\x20',
CLASS_LIST = 'classList',
toggle = function toggle(token, force) {
if (this.contains(token)) {
if (!force) {
// force is not true (either false or omitted)
this.remove(token);
}
} else if(force === undefined || force) {
force = true;
this.add(token);
}
return !!force;
},
DocumentFragmentPrototype = window.DocumentFragment && DocumentFragment.prototype,
Node = window.Node,
NodePrototype = (Node || Element).prototype,
CharacterData = window.CharacterData || Node,
CharacterDataPrototype = CharacterData && CharacterData.prototype,
DocumentType = window.DocumentType,
DocumentTypePrototype = DocumentType && DocumentType.prototype,
ElementPrototype = (window.Element || Node || window.HTMLElement).prototype,
HTMLSelectElement = window.HTMLSelectElement || createElement('select').constructor,
selectRemove = HTMLSelectElement.prototype.remove,
ShadowRoot = window.ShadowRoot,
SVGElement = window.SVGElement,
// normalizes multiple ids as CSS query
idSpaceFinder = / /g,
idSpaceReplacer = '\\ ',
createQueryMethod = function (methodName) {
var createArray = methodName === 'querySelectorAll';
return function (css) {
var a, i, id, query, nl, selectors, node = this.parentNode;
if (node) {
for (
id = this.getAttribute('id') || uid,
query = id === uid ? id : id.replace(idSpaceFinder, idSpaceReplacer),
selectors = css.split(','),
i = 0; i < selectors.length; i++
) {
selectors[i] = '#' + query + ' ' + selectors[i];
}
css = selectors.join(',');
}
if (id === uid) this.setAttribute('id', id);
nl = (node || this)[methodName](css);
if (id === uid) this.removeAttribute('id');
// return a list
if (createArray) {
i = nl.length;
a = new Array(i);
while (i--) a[i] = nl[i];
}
// return node or null
else {
a = nl;
}
return a;
};
},
addQueryAndAll = function (where) {
if (!('query' in where)) {
where.query = ElementPrototype.query;
}
if (!('queryAll' in where)) {
where.queryAll = ElementPrototype.queryAll;
}
},
properties = [
'matches', (
ElementPrototype.matchesSelector ||
ElementPrototype.webkitMatchesSelector ||
ElementPrototype.khtmlMatchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector ||
ElementPrototype.oMatchesSelector ||
function matches(selector) {
var parentNode = this.parentNode;
return !!parentNode && -1 < indexOf.call(
parentNode.querySelectorAll(selector),
this
);
}
),
'closest', function closest(selector) {
var parentNode = this, matches;
while (
// document has no .matches
(matches = parentNode && parentNode.matches) &&
!parentNode.matches(selector)
) {
parentNode = parentNode.parentNode;
}
return matches ? parentNode : null;
},
'prepend', function prepend() {
var firstChild = this.firstChild,
node = mutationMacro(arguments);
if (firstChild) {
this.insertBefore(node, firstChild);
} else {
this.appendChild(node);
}
},
'append', function append() {
this.appendChild(mutationMacro(arguments));
},
'before', function before() {
var parentNode = this.parentNode;
if (parentNode) {
parentNode.insertBefore(
mutationMacro(arguments), this
);
}
},
'after', function after() {
var parentNode = this.parentNode,
nextSibling = this.nextSibling,
node = mutationMacro(arguments);
if (parentNode) {
if (nextSibling) {
parentNode.insertBefore(node, nextSibling);
} else {
parentNode.appendChild(node);
}
}
},
// WARNING - DEPRECATED - use .replaceWith() instead
'replace', function replace() {
this.replaceWith.apply(this, arguments);
},
'replaceWith', function replaceWith() {
var parentNode = this.parentNode;
if (parentNode) {
parentNode.replaceChild(
mutationMacro(arguments),
this
);
}
},
'remove', function remove() {
var parentNode = this.parentNode;
if (parentNode) {
parentNode.removeChild(this);
}
},
'query', createQueryMethod('querySelector'),
'queryAll', createQueryMethod('querySelectorAll')
],
slice = properties.slice,
i = properties.length; i; i -= 2
) {
property = properties[i - 2];
if (!(property in ElementPrototype)) {
ElementPrototype[property] = properties[i - 1];
}
if (property === 'remove') {
// see https://github.com/WebReflection/dom4/issues/19
HTMLSelectElement.prototype[property] = function () {
return 0 < arguments.length ?
selectRemove.apply(this, arguments) :
ElementPrototype.remove.call(this);
};
}
// see https://github.com/WebReflection/dom4/issues/18
if (/^(?:before|after|replace|replaceWith|remove)$/.test(property)) {
if (CharacterData && !(property in CharacterDataPrototype)) {
CharacterDataPrototype[property] = properties[i - 1];
}
if (DocumentType && !(property in DocumentTypePrototype)) {
DocumentTypePrototype[property] = properties[i - 1];
}
}
// see https://github.com/WebReflection/dom4/pull/26
if (/^(?:append|prepend)$/.test(property)) {
if (DocumentFragmentPrototype) {
if (!(property in DocumentFragmentPrototype)) {
DocumentFragmentPrototype[property] = properties[i - 1];
}
} else {
try {
createDocumentFragment().constructor.prototype[property] = properties[i - 1];
} catch(o_O) {}
}
}
}
// bring query and queryAll to the document too
addQueryAndAll(document);
// brings query and queryAll to fragments as well
if (DocumentFragmentPrototype) {
addQueryAndAll(DocumentFragmentPrototype);
} else {
try {
addQueryAndAll(createDocumentFragment().constructor.prototype);
} catch(o_O) {}
}
// bring query and queryAll to the ShadowRoot too
if (ShadowRoot) {
addQueryAndAll(ShadowRoot.prototype);
}
// most likely an IE9 only issue
// see https://github.com/WebReflection/dom4/issues/6
if (!createElement('a').matches('a')) {
ElementPrototype[property] = function(matches){
return function (selector) {
return matches.call(
this.parentNode ?
this :
createDocumentFragment().appendChild(this),
selector
);
};
}(ElementPrototype[property]);
}
// used to fix both old webkit and SVG
DOMTokenList.prototype = {
length: 0,
add: function add() {
for(var j = 0, token; j < arguments.length; j++) {
token = arguments[j];
if(!this.contains(token)) {
properties.push.call(this, property);
}
}
if (this._isSVG) {
this._.setAttribute('class', '' + this);
} else {
this._.className = '' + this;
}
},
contains: (function(indexOf){
return function contains(token) {
i = indexOf.call(this, property = verifyToken(token));
return -1 < i;
};
}([].indexOf || function (token) {
i = this.length;
while(i-- && this[i] !== token){}
return i;
})),
item: function item(i) {
return this[i] || null;
},
remove: function remove() {
for(var j = 0, token; j < arguments.length; j++) {
token = arguments[j];
if(this.contains(token)) {
properties.splice.call(this, i, 1);
}
}
if (this._isSVG) {
this._.setAttribute('class', '' + this);
} else {
this._.className = '' + this;
}
},
toggle: toggle,
toString: function toString() {
return properties.join.call(this, SPACE);
}
};
if (SVGElement && !(CLASS_LIST in SVGElement.prototype)) {
defineProperty(SVGElement.prototype, CLASS_LIST, classListDescriptor);
}
// http://www.w3.org/TR/dom/#domtokenlist
// iOS 5.1 has completely screwed this property
// classList in ElementPrototype is false
// but it's actually there as getter
if (!(CLASS_LIST in document.documentElement)) {
defineProperty(ElementPrototype, CLASS_LIST, classListDescriptor);
} else {
// iOS 5.1 and Nokia ASHA do not support multiple add or remove
// trying to detect and fix that in here
TemporaryTokenList = createElement('div')[CLASS_LIST];
TemporaryTokenList.add('a', 'b', 'a');
if ('a\x20b' != TemporaryTokenList) {
// no other way to reach original methods in iOS 5.1
TemporaryPrototype = TemporaryTokenList.constructor.prototype;
if (!('add' in TemporaryPrototype)) {
// ASHA double fails in here
TemporaryPrototype = window.TemporaryTokenList.prototype;
}
wrapVerifyToken = function (original) {
return function () {
var i = 0;
while (i < arguments.length) {
original.call(this, arguments[i++]);
}
};
};
TemporaryPrototype.add = wrapVerifyToken(TemporaryPrototype.add);
TemporaryPrototype.remove = wrapVerifyToken(TemporaryPrototype.remove);
// toggle is broken too ^_^ ... let's fix it
TemporaryPrototype.toggle = toggle;
}
}
if (!('contains' in NodePrototype)) {
defineProperty(NodePrototype, 'contains', {
value: function (el) {
while (el && el !== this) el = el.parentNode;
return this === el;
}
});
}
if (!('head' in document)) {
defineProperty(document, 'head', {
get: function () {
return head || (
head = document.getElementsByTagName('head')[0]
);
}
});
}
// requestAnimationFrame partial polyfill
(function () {
for (var
raf,
rAF = window.requestAnimationFrame,
cAF = window.cancelAnimationFrame,
prefixes = ['o', 'ms', 'moz', 'webkit'],
i = prefixes.length;
!cAF && i--;
) {
rAF = rAF || window[prefixes[i] + 'RequestAnimationFrame'];
cAF = window[prefixes[i] + 'CancelAnimationFrame'] ||
window[prefixes[i] + 'CancelRequestAnimationFrame'];
}
if (!cAF) {
// some FF apparently implemented rAF but no cAF
if (rAF) {
raf = rAF;
rAF = function (callback) {
var goOn = true;
raf(function () {
if (goOn) callback.apply(this, arguments);
});
return function () {
goOn = false;
};
};
cAF = function (id) {
id();
};
} else {
rAF = function (callback) {
return setTimeout(callback, 15, 15);
};
cAF = function (id) {
clearTimeout(id);
};
}
}
window.requestAnimationFrame = rAF;
window.cancelAnimationFrame = cAF;
}());
// http://www.w3.org/TR/dom/#customevent
try{new window.CustomEvent('?');}catch(o_O){
window.CustomEvent = function(
eventName,
defaultInitDict
){
// the infamous substitute
function CustomEvent(type, eventInitDict) {
/*jshint eqnull:true */
var event = document.createEvent(eventName);
if (typeof type != 'string') {
throw new Error('An event name must be provided');
}
if (eventName == 'Event') {
event.initCustomEvent = initCustomEvent;
}
if (eventInitDict == null) {
eventInitDict = defaultInitDict;
}
event.initCustomEvent(
type,
eventInitDict.bubbles,
eventInitDict.cancelable,
eventInitDict.detail
);
return event;
}
// attached at runtime
function initCustomEvent(
type, bubbles, cancelable, detail
) {
/*jshint validthis:true*/
this.initEvent(type, bubbles, cancelable);
this.detail = detail;
}
// that's it
return CustomEvent;
}(
// is this IE9 or IE10 ?
// where CustomEvent is there
// but not usable as construtor ?
window.CustomEvent ?
// use the CustomEvent interface in such case
'CustomEvent' : 'Event',
// otherwise the common compatible one
{
bubbles: false,
cancelable: false,
detail: null
}
);
}
// window.Event as constructor
try { new Event('_'); } catch (o_O) {
/* jshint -W022 */
o_O = (function ($Event) {
function Event(type, init) {
enoughArguments(arguments.length, 'Event');
var out = document.createEvent('Event');
if (!init) init = {};
out.initEvent(
type,
!!init.bubbles,
!!init.cancelable
);
return out;
}
Event.prototype = $Event.prototype;
return Event;
}(window.Event || function Event() {}));
defineProperty(window, 'Event', {value: o_O});
// Android 4 gotcha
if (Event !== o_O) Event = o_O;
}
// window.KeyboardEvent as constructor
try { new KeyboardEvent('_', {}); } catch (o_O) {
/* jshint -W022 */
o_O = (function ($KeyboardEvent) {
// code inspired by https://gist.github.com/termi/4654819
var
initType = 0,
defaults = {
char: '',
key: '',
location: 0,
ctrlKey: false,
shiftKey: false,
altKey: false,
metaKey: false,
altGraphKey: false,
repeat: false,
locale: navigator.language,
detail: 0,
bubbles: false,
cancelable: false,
keyCode: 0,
charCode: 0,
which: 0
},
eventType
;
try {
var e = document.createEvent('KeyboardEvent');
e.initKeyboardEvent(
'keyup', false, false, window, '+', 3,
true, false, true, false, false
);
initType = (
(e.keyIdentifier || e.key) == '+' &&
(e.keyLocation || e.location) == 3
) && (
e.ctrlKey ? e.altKey ? 1 : 3 : e.shiftKey ? 2 : 4
) || 9;
} catch(o_O) {}
eventType = 0 < initType ? 'KeyboardEvent' : 'Event';
function getModifier(init) {
for (var
out = [],
keys = [
'ctrlKey',
'Control',
'shiftKey',
'Shift',
'altKey',
'Alt',
'metaKey',
'Meta',
'altGraphKey',
'AltGraph'
],
i = 0; i < keys.length; i += 2
) {
if (init[keys[i]])
out.push(keys[i + 1]);
}
return out.join(' ');
}
function withDefaults(target, source) {
for (var key in source) {
if (
source.hasOwnProperty(key) &&
!source.hasOwnProperty.call(target, key)
) target[key] = source[key];
}
return target;
}
function withInitValues(key, out, init) {
try {
out[key] = init[key];
} catch(o_O) {}
}
function KeyboardEvent(type, init) {
enoughArguments(arguments.length, 'KeyboardEvent');
init = withDefaults(init || {}, defaults);
var
out = document.createEvent(eventType),
ctrlKey = init.ctrlKey,
shiftKey = init.shiftKey,
altKey = init.altKey,
metaKey = init.metaKey,
altGraphKey = init.altGraphKey,
modifiers = initType > 3 ? getModifier(init) : null,
key = String(init.key),
chr = String(init.char),
location = init.location,
keyCode = init.keyCode || (
(init.keyCode = key) &&
key.charCodeAt(0)
) || 0,
charCode = init.charCode || (
(init.charCode = chr) &&
chr.charCodeAt(0)
) || 0,
bubbles = init.bubbles,
cancelable = init.cancelable,
repeat = init.repeat,
locale = init.locale,
view = init.view || window,
args
;
if (!init.which) init.which = init.keyCode;
if ('initKeyEvent' in out) {
out.initKeyEvent(
type, bubbles, cancelable, view,
ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode
);
} else if (0 < initType && 'initKeyboardEvent' in out) {
args = [type, bubbles, cancelable, view];
switch (initType) {
case 1:
args.push(key, location, ctrlKey, shiftKey, altKey, metaKey, altGraphKey);
break;
case 2:
args.push(ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode);
break;
case 3:
args.push(key, location, ctrlKey, altKey, shiftKey, metaKey, altGraphKey);
break;
case 4:
args.push(key, location, modifiers, repeat, locale);
break;
default:
args.push(char, key, location, modifiers, repeat, locale);
}
out.initKeyboardEvent.apply(out, args);
} else {
out.initEvent(type, bubbles, cancelable);
}
for (key in out) {
if (defaults.hasOwnProperty(key) && out[key] !== init[key]) {
withInitValues(key, out, init);
}
}
return out;
}
KeyboardEvent.prototype = $KeyboardEvent.prototype;
return KeyboardEvent;
}(window.KeyboardEvent || function KeyboardEvent() {}));
defineProperty(window, 'KeyboardEvent', {value: o_O});
// Android 4 gotcha
if (KeyboardEvent !== o_O) KeyboardEvent = o_O;
}
// window.MouseEvent as constructor
try { new MouseEvent('_', {}); } catch (o_O) {
/* jshint -W022 */
o_O = (function ($MouseEvent) {
function MouseEvent(type, init) {
enoughArguments(arguments.length, 'MouseEvent');
var out = document.createEvent('MouseEvent');
if (!init) init = {};
out.initMouseEvent(
type,
!!init.bubbles,
!!init.cancelable,
init.view || window,
init.detail || 1,
init.screenX || 0,
init.screenY || 0,
init.clientX || 0,
init.clientY || 0,
!!init.ctrlKey,
!!init.altKey,
!!init.shiftKey,
!!init.metaKey,
init.button || 0,
init.relatedTarget || null
);
return out;
}
MouseEvent.prototype = $MouseEvent.prototype;
return MouseEvent;
}(window.MouseEvent || function MouseEvent() {}));
defineProperty(window, 'MouseEvent', {value: o_O});
// Android 4 gotcha
if (MouseEvent !== o_O) MouseEvent = o_O;
}
}(window));(function (global){'use strict';
// a WeakMap fallback for DOM nodes only used as key
var DOMMap = global.WeakMap || (function () {
var
counter = 0,
dispatched = false,
drop = false,
value
;
function dispatch(key, ce, shouldDrop) {
drop = shouldDrop;
dispatched = false;
value = undefined;
key.dispatchEvent(ce);
}
function Handler(value) {
this.value = value;
}
Handler.prototype.handleEvent = function handleEvent(e) {
dispatched = true;
if (drop) {
e.currentTarget.removeEventListener(e.type, this, false);
} else {
value = this.value;
}
};
function DOMMap() {
counter++; // make id clashing highly improbable
this.__ce__ = new Event(('@DOMMap:' + counter) + Math.random());
}
DOMMap.prototype = {
'constructor': DOMMap,
'delete': function del(key) {
return dispatch(key, this.__ce__, true), dispatched;
},
'get': function get(key) {
dispatch(key, this.__ce__, false);
var v = value;
value = undefined;
return v;
},
'has': function has(key) {
return dispatch(key, this.__ce__, false), dispatched;
},
'set': function set(key, value) {
dispatch(key, this.__ce__, true);
key.addEventListener(this.__ce__.type, new Handler(value), false);
return this;
},
};
return DOMMap;
}());
function Dict() {}
Dict.prototype = (Object.create || Object)(null);
// https://dom.spec.whatwg.org/#interface-eventtarget
function createEventListener(type, callback, options) {
function eventListener(e) {
if (eventListener.once) {
e.currentTarget.removeEventListener(
e.type,
callback,
eventListener
);
eventListener.removed = true;
}
if (eventListener.passive) {
e.preventDefault = createEventListener.preventDefault;
}
if (typeof eventListener.callback === 'function') {
/* jshint validthis: true */
eventListener.callback.call(this, e);
} else if (eventListener.callback) {
eventListener.callback.handleEvent(e);
}
if (eventListener.passive) {
delete e.preventDefault;
}
}
eventListener.type = type;
eventListener.callback = callback;
eventListener.capture = !!options.capture;
eventListener.passive = !!options.passive;
eventListener.once = !!options.once;
// currently pointless but specs say to use it, so ...
eventListener.removed = false;
return eventListener;
}
createEventListener.preventDefault = function preventDefault() {};
var
Event = global.CustomEvent,
hOP = Object.prototype.hasOwnProperty,
dE = global.dispatchEvent,
aEL = global.addEventListener,
rEL = global.removeEventListener,
counter = 0,
increment = function () { counter++; },
indexOf = [].indexOf || function indexOf(value){
var length = this.length;
while(length--) {
if (this[length] === value) {
break;
}
}
return length;
},
getListenerKey = function (options) {
return ''.concat(
options.capture ? '1' : '0',
options.passive ? '1' : '0',
options.once ? '1' : '0'
);
},
augment, proto
;
try {
aEL('_', increment, {once: true});
dE(new Event('_'));
dE(new Event('_'));
rEL('_', increment, {once: true});
} catch(o_O) {}
if (counter !== 1) {
(function () {
var dm = new DOMMap();
function createAEL(aEL) {
return function addEventListener(type, handler, options) {
if (options && typeof options !== 'boolean') {
var
info = dm.get(this),
key = getListenerKey(options),
i, tmp, wrap
;
if (!info) dm.set(this, (info = new Dict()));
if (!(type in info)) info[type] = {
handler: [],
wrap: []
};
tmp = info[type];
i = indexOf.call(tmp.handler, handler);
if (i < 0) {
i = tmp.handler.push(handler) - 1;
tmp.wrap[i] = (wrap = new Dict());
} else {
wrap = tmp.wrap[i];
}
if (!(key in wrap)) {
wrap[key] = createEventListener(type, handler, options);
aEL.call(this, type, wrap[key], wrap[key].capture);
}
} else {
aEL.call(this, type, handler, options);
}
};
}
function createREL(rEL) {
return function removeEventListener(type, handler, options) {
if (options && typeof options !== 'boolean') {
var
info = dm.get(this),
key, i, tmp, wrap
;
if (info && (type in info)) {
tmp = info[type];
i = indexOf.call(tmp.handler, handler);
if (-1 < i) {
key = getListenerKey(options);
wrap = tmp.wrap[i];
if (key in wrap) {
rEL.call(this, type, wrap[key], wrap[key].capture);
delete wrap[key];
// return if there are other wraps
for (key in wrap) return;
// otherwise remove all the things
tmp.handler.splice(i, 1);
tmp.wrap.splice(i, 1);
// if there are no other handlers
if (tmp.handler.length === 0)
// drop the info[type] entirely
delete info[type];
}
}
}
} else {
rEL.call(this, type, handler, options);
}
};
}
augment = function (Constructor) {
if (!Constructor) return;
var proto = Constructor.prototype;
proto.addEventListener = createAEL(proto.addEventListener);
proto.removeEventListener = createREL(proto.removeEventListener);
};
if (global.EventTarget) {
augment(EventTarget);
} else {
augment(global.Text);
augment(global.Element || global.HTMLElement);
augment(global.HTMLDocument);
augment(global.Window || {prototype:global});
augment(global.XMLHttpRequest);
}
}());
}
}(self));
},{}],313:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],314:[function(require,module,exports){
/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
(function (root, definition) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(definition);
} else if (typeof module === 'object' && module.exports) {
module.exports = definition();
} else {
root.log = definition();
}
}(this, function () {
"use strict";
var noop = function() {};
var undefinedType = "undefined";
function realMethod(methodName) {
if (typeof console === undefinedType) {
return false; // We can't build a real method without a console to log to
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
// these private functions always need `this` to be set properly
function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
return function () {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this, level, loggerName);
this[methodName].apply(this, arguments);
}
};
}
function replaceLoggingMethods(level, loggerName) {
/*jshint validthis:true */
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = (i < level) ?
noop :
this.methodFactory(methodName, level, loggerName);
}
}
function defaultMethodFactory(methodName, level, loggerName) {
/*jshint validthis:true */
return realMethod(methodName) ||
enableLoggingWhenConsoleArrives.apply(this, arguments);
}
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
function Logger(name, defaultLevel, factory) {
var self = this;
var currentLevel;
var storageKey = "loglevel";
if (name) {
storageKey += ":" + name;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
// Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
if (typeof storedLevel === undefinedType) {
try {
var cookie = window.document.cookie;
var location = cookie.indexOf(
encodeURIComponent(storageKey) + "=");
if (location) {
storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
}
} catch (ignore) {}
}
// If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
/*
*
* Public API
*
*/
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
return currentLevel;
};
self.setLevel = function (level, persist) {
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
currentLevel = level;
if (persist !== false) { // defaults to true
persistLevelIfPossible(level);
}
replaceLoggingMethods.call(self, level, name);
if (typeof console === undefinedType && level < self.levels.SILENT) {
return "No console available for logging";
}
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.setDefaultLevel = function (level) {
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
// Initialize with the right level
var initialLevel = getPersistedLevel();
if (initialLevel == null) {
initialLevel = defaultLevel == null ? "WARN" : defaultLevel;
}
self.setLevel(initialLevel, false);
}
/*
*
* Package-level API
*
*/
var defaultLogger = new Logger();
var _loggersByName = {};
defaultLogger.getLogger = function getLogger(name) {
if (typeof name !== "string" || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(
name, defaultLogger.getLevel(), defaultLogger.methodFactory);
}
return logger;
};
// Grab the current global log variable in case of overwrite
var _log = (typeof window !== undefinedType) ? window.log : undefined;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType &&
window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
return defaultLogger;
}));
},{}],315:[function(require,module,exports){
(function (root, factory) {
'use strict';
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.MersenneTwister = factory();
}
}(this, function () {
/**
* A standalone, pure JavaScript implementation of the Mersenne Twister pseudo random number generator. Compatible
* with Node.js, requirejs and browser environments. Packages are available for npm, Jam and Bower.
*
* @module MersenneTwister
* @author Raphael Pigulla <pigulla@four66.com>
* @license See the attached LICENSE file.
* @version 0.2.3
*/
/*
* Most comments were stripped from the source. If needed you can still find them in the original C code:
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
*
* The original port to JavaScript, on which this file is based, was done by Sean McCullough. It can be found at:
* https://gist.github.com/banksean/300494
*/
'use strict';
var MAX_INT = 4294967296.0,
N = 624,
M = 397,
UPPER_MASK = 0x80000000,
LOWER_MASK = 0x7fffffff,
MATRIX_A = 0x9908b0df;
/**
* Instantiates a new Mersenne Twister.
*
* @constructor
* @alias module:MersenneTwister
* @since 0.1.0
* @param {number=} seed The initial seed value.
*/
var MersenneTwister = function (seed) {
if (typeof seed === 'undefined') {
seed = new Date().getTime();
}
this.mt = new Array(N);
this.mti = N + 1;
this.seed(seed);
};
/**
* Initializes the state vector by using one unsigned 32-bit integer "seed", which may be zero.
*
* @since 0.1.0
* @param {number} seed The seed value.
*/
MersenneTwister.prototype.seed = function (seed) {
var s;
this.mt[0] = seed >>> 0;
for (this.mti = 1; this.mti < N; this.mti++) {
s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
this.mt[this.mti] =
(((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti;
this.mt[this.mti] >>>= 0;
}
};
/**
* Initializes the state vector by using an array key[] of unsigned 32-bit integers of the specified length. If
* length is smaller than 624, then each array of 32-bit integers gives distinct initial state vector. This is
* useful if you want a larger seed space than 32-bit word.
*
* @since 0.1.0
* @param {array} vector The seed vector.
*/
MersenneTwister.prototype.seedArray = function (vector) {
var i = 1,
j = 0,
k = N > vector.length ? N : vector.length,
s;
this.seed(19650218);
for (; k > 0; k--) {
s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525))) +
vector[j] + j;
this.mt[i] >>>= 0;
i++;
j++;
if (i >= N) {
this.mt[0] = this.mt[N - 1];
i = 1;
}
if (j >= vector.length) {
j = 0;
}
}
for (k = N - 1; k; k--) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i;
this.mt[i] >>>= 0;
i++;
if (i >= N) {
this.mt[0] = this.mt[N - 1];
i = 1;
}
}
this.mt[0] = 0x80000000;
};
/**
* Generates a random unsigned 32-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.int = function () {
var y,
kk,
mag01 = new Array(0, MATRIX_A);
if (this.mti >= N) {
if (this.mti === N + 1) {
this.seed(5489);
}
for (kk = 0; kk < N - M; kk++) {
y = (this.mt[kk] & UPPER_MASK) | (this.mt[kk + 1] & LOWER_MASK);
this.mt[kk] = this.mt[kk + M] ^ (y >>> 1) ^ mag01[y & 1];
}
for (; kk < N - 1; kk++) {
y = (this.mt[kk] & UPPER_MASK) | (this.mt[kk + 1] & LOWER_MASK);
this.mt[kk] = this.mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 1];
}
y = (this.mt[N - 1] & UPPER_MASK) | (this.mt[0] & LOWER_MASK);
this.mt[N - 1] = this.mt[M - 1] ^ (y >>> 1) ^ mag01[y & 1];
this.mti = 0;
}
y = this.mt[this.mti++];
y ^= (y >>> 11);
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= (y >>> 18);
return y >>> 0;
};
/**
* Generates a random unsigned 31-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.int31 = function () {
return this.int() >>> 1;
};
/**
* Generates a random real in the interval [0;1] with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.real = function () {
return this.int() * (1.0 / (MAX_INT - 1));
};
/**
* Generates a random real in the interval ]0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.realx = function () {
return (this.int() + 0.5) * (1.0 / MAX_INT);
};
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.rnd = function () {
return this.int() * (1.0 / MAX_INT);
};
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* Same as .rnd() method - for consistency with Math.random() interface.
*
* @since 0.2.0
* @returns {number}
*/
MersenneTwister.prototype.random = MersenneTwister.prototype.rnd;
/**
* Generates a random real in the interval [0;1[ with 53-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
MersenneTwister.prototype.rndHiRes = function () {
var a = this.int() >>> 5,
b = this.int() >>> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
};
var instance = new MersenneTwister();
/**
* A static version of [rnd]{@link module:MersenneTwister#rnd} on a randomly seeded instance.
*
* @static
* @function random
* @memberof module:MersenneTwister
* @returns {number}
*/
MersenneTwister.random = function () {
return instance.rnd();
};
return MersenneTwister;
}));
},{}],316:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = LinkedList;
/**
* Doubly linked list
* @constructor
*/
function LinkedList() {
this.head = null;
this.length = 0;
}
/**
* Add a node to the end of the list
* @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add
*/
LinkedList.prototype.add = function(x) {
if(this.head !== null) {
this.head.prev = x;
x.next = this.head;
}
this.head = x;
++this.length;
};
/**
* Remove the provided node from the list
* @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove
*/
LinkedList.prototype.remove = function(x) {
--this.length;
if(x === this.head) {
this.head = this.head.next;
}
if(x.next !== null) {
x.next.prev = x.prev;
x.next = null;
}
if(x.prev !== null) {
x.prev.next = x.next;
x.prev = null;
}
};
/**
* @returns {boolean} true iff there are no nodes in the list
*/
LinkedList.prototype.isEmpty = function() {
return this.length === 0;
};
/**
* Dispose all nodes
* @returns {Promise} promise that fulfills when all nodes have been disposed,
* or rejects if an error occurs while disposing
*/
LinkedList.prototype.dispose = function() {
if(this.isEmpty()) {
return Promise.resolve();
}
var promises = [];
var x = this.head;
this.head = null;
this.length = 0;
while(x !== null) {
promises.push(x.dispose());
x = x.next;
}
return Promise.all(promises);
};
},{}],317:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
exports.isPromise = isPromise;
function isPromise(p) {
return p !== null && typeof p === 'object' && typeof p.then === 'function';
}
},{}],318:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
// Based on https://github.com/petkaantonov/deque
module.exports = Queue;
function Queue(capPow2) {
this._capacity = capPow2||32;
this._length = 0;
this._head = 0;
}
Queue.prototype.push = function (x) {
var len = this._length;
this._checkCapacity(len + 1);
var i = (this._head + len) & (this._capacity - 1);
this[i] = x;
this._length = len + 1;
};
Queue.prototype.shift = function () {
var head = this._head;
var x = this[head];
this[head] = void 0;
this._head = (head + 1) & (this._capacity - 1);
this._length--;
return x;
};
Queue.prototype.isEmpty = function() {
return this._length === 0;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._ensureCapacity(this._capacity << 1);
}
};
Queue.prototype._ensureCapacity = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var last = this._head + this._length;
if (last > oldCapacity) {
copy(this, 0, this, oldCapacity, last & (oldCapacity - 1));
}
};
function copy(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
},{}],319:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = Stream;
function Stream(source) {
this.source = source;
}
},{}],320:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Pipe = require('../sink/Pipe');
var runSource = require('../runSource').withDefaultScheduler;
var dispose = require('../disposable/dispose');
var PropagateTask = require('../scheduler/PropagateTask');
exports.scan = scan;
exports.reduce = reduce;
/**
* Create a stream containing successive reduce results of applying f to
* the previous reduce result and the current stream item.
* @param {function(result:*, x:*):*} f reducer function
* @param {*} initial initial value
* @param {Stream} stream stream to scan
* @returns {Stream} new stream containing successive reduce results
*/
function scan(f, initial, stream) {
return new Stream(new Scan(f, initial, stream.source));
}
function Scan(f, z, source) {
this.source = source;
this.f = f;
this.value = z;
}
Scan.prototype.run = function(sink, scheduler) {
var d1 = scheduler.asap(PropagateTask.event(this.value, sink));
var d2 = this.source.run(new ScanSink(this.f, this.value, sink), scheduler);
return dispose.all([d1, d2]);
};
function ScanSink(f, z, sink) {
this.f = f;
this.value = z;
this.sink = sink;
}
ScanSink.prototype.event = function(t, x) {
var f = this.f;
this.value = f(this.value, x);
this.sink.event(t, this.value);
};
ScanSink.prototype.error = Pipe.prototype.error;
ScanSink.prototype.end = Pipe.prototype.end;
/**
* Reduce a stream to produce a single result. Note that reducing an infinite
* stream will return a Promise that never fulfills, but that may reject if an error
* occurs.
* @param {function(result:*, x:*):*} f reducer function
* @param {*} initial initial value
* @param {Stream} stream to reduce
* @returns {Promise} promise for the file result of the reduce
*/
function reduce(f, initial, stream) {
return runSource(new Reduce(f, initial, stream.source));
}
function Reduce(f, z, source) {
this.source = source;
this.f = f;
this.value = z;
}
Reduce.prototype.run = function(sink, scheduler) {
return this.source.run(new ReduceSink(this.f, this.value, sink), scheduler);
};
function ReduceSink(f, z, sink) {
this.f = f;
this.value = z;
this.sink = sink;
}
ReduceSink.prototype.event = function(t, x) {
var f = this.f;
this.value = f(this.value, x);
this.sink.event(t, this.value);
};
ReduceSink.prototype.error = Pipe.prototype.error;
ReduceSink.prototype.end = function(t) {
this.sink.end(t, this.value);
};
function noop() {}
},{"../Stream":319,"../disposable/dispose":348,"../runSource":358,"../scheduler/PropagateTask":359,"../sink/Pipe":366}],321:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var combine = require('./combine').combine;
var apply = require('@most/prelude').apply;
exports.ap = ap;
/**
* Assume fs is a stream containing functions, and apply the latest function
* in fs to the latest value in xs.
* fs: --f---------g--------h------>
* xs: -a-------b-------c-------d-->
* ap(fs, xs): --fa-----fb-gb---gc--hc--hd->
* @param {Stream} fs stream of functions to apply to the latest x
* @param {Stream} xs stream of values to which to apply all the latest f
* @returns {Stream} stream containing all the applications of fs to xs
*/
function ap(fs, xs) {
return combine(apply, fs, xs);
}
},{"./combine":323,"@most/prelude":4}],322:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var streamOf = require('../source/core').of;
var continueWith = require('./continueWith').continueWith;
exports.concat = concat;
exports.cycle = cycle;
exports.cons = cons;
/**
* @param {*} x value to prepend
* @param {Stream} stream
* @returns {Stream} new stream with x prepended
*/
function cons(x, stream) {
return concat(streamOf(x), stream);
}
/**
* @param {Stream} left
* @param {Stream} right
* @returns {Stream} new stream containing all events in left followed by all
* events in right. This *timeshifts* right to the end of left.
*/
function concat(left, right) {
return continueWith(function() {
return right;
}, left);
}
/**
* @deprecated
* Tie stream into a circle, creating an infinite stream
* @param {Stream} stream
* @returns {Stream} new infinite stream
*/
function cycle(stream) {
return continueWith(function cycleNext() {
return cycle(stream);
}, stream);
}
},{"../source/core":370,"./continueWith":325}],323:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var transform = require('./transform');
var core = require('../source/core');
var Pipe = require('../sink/Pipe');
var IndexSink = require('../sink/IndexSink');
var dispose = require('../disposable/dispose');
var base = require('@most/prelude');
var invoke = require('../invoke');
var map = base.map;
var tail = base.tail;
exports.combineArray = combineArray;
exports.combine = combine;
/**
* Combine latest events from all input streams
* @param {function(...events):*} f function to combine most recent events
* @returns {Stream} stream containing the result of applying f to the most recent
* event of each input stream, whenever a new event arrives on any stream.
*/
function combine(f /*, ...streams */) {
return combineArray(f, tail(arguments));
}
/**
* Combine latest events from all input streams
* @param {function(...events):*} f function to combine most recent events
* @param {[Stream]} streams most recent events
* @returns {Stream} stream containing the result of applying f to the most recent
* event of each input stream, whenever a new event arrives on any stream.
*/
function combineArray(f, streams) {
var l = streams.length;
return l === 0 ? core.empty()
: l === 1 ? transform.map(f, streams[0])
: new Stream(combineSources(f, streams));
}
function combineSources(f, streams) {
return new Combine(f, map(getSource, streams))
}
function getSource(stream) {
return stream.source;
}
function Combine(f, sources) {
this.f = f;
this.sources = sources;
}
Combine.prototype.run = function(sink, scheduler) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var mergeSink = new CombineSink(disposables, sinks, sink, this.f);
for(var indexSink, i=0; i<l; ++i) {
indexSink = sinks[i] = new IndexSink(i, mergeSink);
disposables[i] = this.sources[i].run(indexSink, scheduler);
}
return dispose.all(disposables);
};
function CombineSink(disposables, sinks, sink, f) {
this.sink = sink;
this.disposables = disposables;
this.sinks = sinks;
this.f = f;
var l = sinks.length;
this.awaiting = l;
this.values = new Array(l);
this.hasValue = new Array(l);
for(var i = 0; i < l; ++i) {
this.hasValue[i] = false;
}
this.activeCount = sinks.length;
}
CombineSink.prototype.error = Pipe.prototype.error;
CombineSink.prototype.event = function(t, indexedValue) {
var i = indexedValue.index;
var awaiting = this._updateReady(i);
this.values[i] = indexedValue.value;
if(awaiting === 0) {
this.sink.event(t, invoke(this.f, this.values));
}
};
CombineSink.prototype._updateReady = function(index) {
if(this.awaiting > 0) {
if(!this.hasValue[index]) {
this.hasValue[index] = true
this.awaiting -= 1
}
}
return this.awaiting;
}
CombineSink.prototype.end = function(t, indexedValue) {
dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink);
if(--this.activeCount === 0) {
this.sink.end(t, indexedValue.value);
}
};
},{"../Stream":319,"../disposable/dispose":348,"../invoke":353,"../sink/IndexSink":365,"../sink/Pipe":366,"../source/core":370,"./transform":343,"@most/prelude":4}],324:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var mergeMapConcurrently = require('./mergeConcurrently').mergeMapConcurrently;
exports.concatMap = concatMap;
/**
* Map each value in stream to a new stream, and concatenate them all
* stream: -a---b---cX
* f(a): 1-1-1-1X
* f(b): -2-2-2-2X
* f(c): -3-3-3-3X
* stream.concatMap(f): -1-1-1-1-2-2-2-2-3-3-3-3X
* @param {function(x:*):Stream} f function to map each value to a stream
* @param {Stream} stream
* @returns {Stream} new stream containing all events from each stream returned by f
*/
function concatMap(f, stream) {
return mergeMapConcurrently(f, 1, stream);
}
},{"./mergeConcurrently":333}],325:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var isPromise = require('../Promise').isPromise;
exports.continueWith = continueWith;
function continueWith(f, stream) {
return new Stream(new ContinueWith(f, stream.source));
}
function ContinueWith(f, source) {
this.f = f;
this.source = source;
}
ContinueWith.prototype.run = function(sink, scheduler) {
return new ContinueWithSink(this.f, this.source, sink, scheduler);
};
function ContinueWithSink(f, source, sink, scheduler) {
this.f = f;
this.sink = sink;
this.scheduler = scheduler;
this.active = true;
this.disposable = dispose.once(source.run(this, scheduler));
}
ContinueWithSink.prototype.error = Sink.prototype.error;
ContinueWithSink.prototype.event = function(t, x) {
if(!this.active) {
return;
}
this.sink.event(t, x);
};
ContinueWithSink.prototype.end = function(t, x) {
if(!this.active) {
return;
}
dispose.tryDispose(t, this.disposable, this.sink);
this._startNext(t, x, this.sink);
};
ContinueWithSink.prototype._startNext = function(t, x, sink) {
try {
this.disposable = this._continue(this.f, x, sink);
} catch(e) {
sink.error(t, e);
}
};
ContinueWithSink.prototype._continue = function(f, x, sink) {
return f(x).source.run(sink, this.scheduler);
};
ContinueWithSink.prototype.dispose = function() {
this.active = false;
return this.disposable.dispose();
};
},{"../Promise":317,"../Stream":319,"../disposable/dispose":348,"../sink/Pipe":366}],326:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var PropagateTask = require('../scheduler/PropagateTask');
exports.delay = delay;
/**
* @param {Number} delayTime milliseconds to delay each item
* @param {Stream} stream
* @returns {Stream} new stream containing the same items, but delayed by ms
*/
function delay(delayTime, stream) {
return delayTime <= 0 ? stream
: new Stream(new Delay(delayTime, stream.source));
}
function Delay(dt, source) {
this.dt = dt;
this.source = source;
}
Delay.prototype.run = function(sink, scheduler) {
var delaySink = new DelaySink(this.dt, sink, scheduler);
return dispose.all([delaySink, this.source.run(delaySink, scheduler)]);
};
function DelaySink(dt, sink, scheduler) {
this.dt = dt;
this.sink = sink;
this.scheduler = scheduler;
}
DelaySink.prototype.dispose = function() {
var self = this;
this.scheduler.cancelAll(function(task) {
return task.sink === self.sink;
});
};
DelaySink.prototype.event = function(t, x) {
this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink));
};
DelaySink.prototype.end = function(t, x) {
this.scheduler.delay(this.dt, PropagateTask.end(x, this.sink));
};
DelaySink.prototype.error = Sink.prototype.error;
},{"../Stream":319,"../disposable/dispose":348,"../scheduler/PropagateTask":359,"../sink/Pipe":366}],327:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var SafeSink = require('../sink/SafeSink');
var Pipe = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var tryEvent = require('../source/tryEvent');
var isPromise = require('../Promise').isPromise;
var PropagateTask = require('../scheduler/PropagateTask');
exports.flatMapError = recoverWith;
exports.recoverWith = recoverWith;
exports.throwError = throwError;
/**
* If stream encounters an error, recover and continue with items from stream
* returned by f.
* @param {function(error:*):Stream} f function which returns a new stream
* @param {Stream} stream
* @returns {Stream} new stream which will recover from an error by calling f
*/
function recoverWith(f, stream) {
return new Stream(new RecoverWith(f, stream.source));
}
/**
* Create a stream containing only an error
* @param {*} e error value, preferably an Error or Error subtype
* @returns {Stream} new stream containing only an error
*/
function throwError(e) {
return new Stream(new ErrorSource(e));
}
function ErrorSource(e) {
this.value = e;
}
ErrorSource.prototype.run = function(sink, scheduler) {
return scheduler.asap(new PropagateTask(runError, this.value, sink));
};
function runError(t, e, sink) {
sink.error(t, e);
}
function RecoverWith(f, source) {
this.f = f;
this.source = source;
}
RecoverWith.prototype.run = function(sink, scheduler) {
return new RecoverWithSink(this.f, this.source, sink, scheduler);
};
function RecoverWithSink(f, source, sink, scheduler) {
this.f = f;
this.sink = new SafeSink(sink);
this.scheduler = scheduler;
this.disposable = source.run(this, scheduler);
}
RecoverWithSink.prototype.event = function(t, x) {
tryEvent.tryEvent(t, x, this.sink);
}
RecoverWithSink.prototype.end = function(t, x) {
tryEvent.tryEnd(t, x, this.sink);
}
RecoverWithSink.prototype.error = function(t, e) {
var nextSink = this.sink.disable();
dispose.tryDispose(t, this.disposable, this.sink);
this._startNext(t, e, nextSink);
};
RecoverWithSink.prototype._startNext = function(t, x, sink) {
try {
this.disposable = this._continue(this.f, x, sink);
} catch(e) {
sink.error(t, e);
}
};
RecoverWithSink.prototype._continue = function(f, x, sink) {
var stream = f(x);
return stream.source.run(sink, this.scheduler);
};
RecoverWithSink.prototype.dispose = function() {
return this.disposable.dispose();
};
},{"../Promise":317,"../Stream":319,"../disposable/dispose":348,"../scheduler/PropagateTask":359,"../sink/Pipe":366,"../sink/SafeSink":367,"../source/tryEvent":379}],328:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
var Filter = require('../fusion/Filter');
exports.filter = filter;
exports.skipRepeats = skipRepeats;
exports.skipRepeatsWith = skipRepeatsWith;
/**
* Retain only items matching a predicate
* @param {function(x:*):boolean} p filtering predicate called for each item
* @param {Stream} stream stream to filter
* @returns {Stream} stream containing only items for which predicate returns truthy
*/
function filter(p, stream) {
return new Stream(Filter.create(p, stream.source));
}
/**
* Skip repeated events, using === to detect duplicates
* @param {Stream} stream stream from which to omit repeated events
* @returns {Stream} stream without repeated events
*/
function skipRepeats(stream) {
return skipRepeatsWith(same, stream);
}
/**
* Skip repeated events using the provided equals function to detect duplicates
* @param {function(a:*, b:*):boolean} equals optional function to compare items
* @param {Stream} stream stream from which to omit repeated events
* @returns {Stream} stream without repeated events
*/
function skipRepeatsWith(equals, stream) {
return new Stream(new SkipRepeats(equals, stream.source));
}
function SkipRepeats(equals, source) {
this.equals = equals;
this.source = source;
}
SkipRepeats.prototype.run = function(sink, scheduler) {
return this.source.run(new SkipRepeatsSink(this.equals, sink), scheduler);
};
function SkipRepeatsSink(equals, sink) {
this.equals = equals;
this.sink = sink;
this.value = void 0;
this.init = true;
}
SkipRepeatsSink.prototype.end = Sink.prototype.end;
SkipRepeatsSink.prototype.error = Sink.prototype.error;
SkipRepeatsSink.prototype.event = function(t, x) {
if(this.init) {
this.init = false;
this.value = x;
this.sink.event(t, x);
} else if(!this.equals(this.value, x)) {
this.value = x;
this.sink.event(t, x);
}
};
function same(a, b) {
return a === b;
}
},{"../Stream":319,"../fusion/Filter":350,"../sink/Pipe":366}],329:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var mergeConcurrently = require('./mergeConcurrently').mergeConcurrently;
var mergeMapConcurrently = require('./mergeConcurrently').mergeMapConcurrently;
exports.flatMap = flatMap;
exports.join = join;
/**
* Map each value in the stream to a new stream, and merge it into the
* returned outer stream. Event arrival times are preserved.
* @param {function(x:*):Stream} f chaining function, must return a Stream
* @param {Stream} stream
* @returns {Stream} new stream containing all events from each stream returned by f
*/
function flatMap(f, stream) {
return mergeMapConcurrently(f, Infinity, stream);
}
/**
* Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner
* streams to the outer. Event arrival times are preserved.
* @param {Stream<Stream<X>>} stream stream of streams
* @returns {Stream<X>} new stream containing all events of all inner streams
*/
function join(stream) {
return mergeConcurrently(Infinity, stream);
}
},{"./mergeConcurrently":333}],330:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var PropagateTask = require('../scheduler/PropagateTask');
var Map = require('../fusion/Map');
exports.throttle = throttle;
exports.debounce = debounce;
/**
* Limit the rate of events by suppressing events that occur too often
* @param {Number} period time to suppress events
* @param {Stream} stream
* @returns {Stream}
*/
function throttle(period, stream) {
return new Stream(throttleSource(period, stream.source));
}
function throttleSource(period, source) {
return source instanceof Map ? commuteMapThrottle(period, source)
: source instanceof Throttle ? fuseThrottle(period, source)
: new Throttle(period, source)
}
function commuteMapThrottle(period, source) {
return Map.create(source.f, throttleSource(period, source.source))
}
function fuseThrottle(period, source) {
return new Throttle(Math.max(period, source.period), source.source)
}
function Throttle(period, source) {
this.period = period;
this.source = source;
}
Throttle.prototype.run = function(sink, scheduler) {
return this.source.run(new ThrottleSink(this.period, sink), scheduler);
};
function ThrottleSink(period, sink) {
this.time = 0;
this.period = period;
this.sink = sink;
}
ThrottleSink.prototype.event = function(t, x) {
if(t >= this.time) {
this.time = t + this.period;
this.sink.event(t, x);
}
};
ThrottleSink.prototype.end = Sink.prototype.end;
ThrottleSink.prototype.error = Sink.prototype.error;
/**
* Wait for a burst of events to subside and emit only the last event in the burst
* @param {Number} period events occuring more frequently than this
* will be suppressed
* @param {Stream} stream stream to debounce
* @returns {Stream} new debounced stream
*/
function debounce(period, stream) {
return new Stream(new Debounce(period, stream.source));
}
function Debounce(dt, source) {
this.dt = dt;
this.source = source;
}
Debounce.prototype.run = function(sink, scheduler) {
return new DebounceSink(this.dt, this.source, sink, scheduler);
};
function DebounceSink(dt, source, sink, scheduler) {
this.dt = dt;
this.sink = sink;
this.scheduler = scheduler;
this.value = void 0;
this.timer = null;
var sourceDisposable = source.run(this, scheduler);
this.disposable = dispose.all([this, sourceDisposable]);
}
DebounceSink.prototype.event = function(t, x) {
this._clearTimer();
this.value = x;
this.timer = this.scheduler.delay(this.dt, PropagateTask.event(x, this.sink));
};
DebounceSink.prototype.end = function(t, x) {
if(this._clearTimer()) {
this.sink.event(t, this.value);
this.value = void 0;
}
this.sink.end(t, x);
};
DebounceSink.prototype.error = function(t, x) {
this._clearTimer();
this.sink.error(t, x);
};
DebounceSink.prototype.dispose = function() {
this._clearTimer();
};
DebounceSink.prototype._clearTimer = function() {
if(this.timer === null) {
return false;
}
this.timer.dispose();
this.timer = null;
return true;
};
},{"../Stream":319,"../disposable/dispose":348,"../fusion/Map":352,"../scheduler/PropagateTask":359,"../sink/Pipe":366}],331:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Pipe = require('../sink/Pipe');
exports.loop = loop;
/**
* Generalized feedback loop. Call a stepper function for each event. The stepper
* will be called with 2 params: the current seed and the an event value. It must
* return a new { seed, value } pair. The `seed` will be fed back into the next
* invocation of stepper, and the `value` will be propagated as the event value.
* @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function
* @param {*} seed initial seed value passed to first stepper call
* @param {Stream} stream event stream
* @returns {Stream} new stream whose values are the `value` field of the objects
* returned by the stepper
*/
function loop(stepper, seed, stream) {
return new Stream(new Loop(stepper, seed, stream.source));
}
function Loop(stepper, seed, source) {
this.step = stepper;
this.seed = seed;
this.source = source;
}
Loop.prototype.run = function(sink, scheduler) {
return this.source.run(new LoopSink(this.step, this.seed, sink), scheduler);
};
function LoopSink(stepper, seed, sink) {
this.step = stepper;
this.seed = seed;
this.sink = sink;
}
LoopSink.prototype.error = Pipe.prototype.error;
LoopSink.prototype.event = function(t, x) {
var result = this.step(this.seed, x);
this.seed = result.seed;
this.sink.event(t, result.value);
};
LoopSink.prototype.end = function(t) {
this.sink.end(t, this.seed);
};
},{"../Stream":319,"../sink/Pipe":366}],332:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Pipe = require('../sink/Pipe');
var IndexSink = require('../sink/IndexSink');
var empty = require('../source/core').empty;
var dispose = require('../disposable/dispose');
var base = require('@most/prelude');
var copy = base.copy;
var reduce = base.reduce;
exports.merge = merge;
exports.mergeArray = mergeArray;
/**
* @returns {Stream} stream containing events from all streams in the argument
* list in time order. If two events are simultaneous they will be merged in
* arbitrary order.
*/
function merge(/*...streams*/) {
return mergeArray(copy(arguments));
}
/**
* @param {Array} streams array of stream to merge
* @returns {Stream} stream containing events from all input observables
* in time order. If two events are simultaneous they will be merged in
* arbitrary order.
*/
function mergeArray(streams) {
var l = streams.length;
return l === 0 ? empty()
: l === 1 ? streams[0]
: new Stream(mergeSources(streams));
}
/**
* This implements fusion/flattening for merge. It will
* fuse adjacent merge operations. For example:
* - a.merge(b).merge(c) effectively becomes merge(a, b, c)
* - merge(a, merge(b, c)) effectively becomes merge(a, b, c)
* It does this by concatenating the sources arrays of
* any nested Merge sources, in effect "flattening" nested
* merge operations into a single merge.
*/
function mergeSources(streams) {
return new Merge(reduce(appendSources, [], streams))
}
function appendSources(sources, stream) {
var source = stream.source;
return source instanceof Merge
? sources.concat(source.sources)
: sources.concat(source)
}
function Merge(sources) {
this.sources = sources;
}
Merge.prototype.run = function(sink, scheduler) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var mergeSink = new MergeSink(disposables, sinks, sink);
for(var indexSink, i=0; i<l; ++i) {
indexSink = sinks[i] = new IndexSink(i, mergeSink);
disposables[i] = this.sources[i].run(indexSink, scheduler);
}
return dispose.all(disposables);
};
function MergeSink(disposables, sinks, sink) {
this.sink = sink;
this.disposables = disposables;
this.activeCount = sinks.length;
}
MergeSink.prototype.error = Pipe.prototype.error;
MergeSink.prototype.event = function(t, indexValue) {
this.sink.event(t, indexValue.value);
};
MergeSink.prototype.end = function(t, indexedValue) {
dispose.tryDispose(t, this.disposables[indexedValue.index], this.sink);
if(--this.activeCount === 0) {
this.sink.end(t, indexedValue.value);
}
};
},{"../Stream":319,"../disposable/dispose":348,"../sink/IndexSink":365,"../sink/Pipe":366,"../source/core":370,"@most/prelude":4}],333:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var dispose = require('../disposable/dispose');
var LinkedList = require('../LinkedList');
var identity = require('@most/prelude').id;
exports.mergeConcurrently = mergeConcurrently;
exports.mergeMapConcurrently = mergeMapConcurrently;
function mergeConcurrently(concurrency, stream) {
return mergeMapConcurrently(identity, concurrency, stream);
}
function mergeMapConcurrently(f, concurrency, stream) {
return new Stream(new MergeConcurrently(f, concurrency, stream.source));
}
function MergeConcurrently(f, concurrency, source) {
this.f = f;
this.concurrency = concurrency;
this.source = source;
}
MergeConcurrently.prototype.run = function(sink, scheduler) {
return new Outer(this.f, this.concurrency, this.source, sink, scheduler);
};
function Outer(f, concurrency, source, sink, scheduler) {
this.f = f;
this.concurrency = concurrency;
this.sink = sink;
this.scheduler = scheduler;
this.pending = [];
this.current = new LinkedList();
this.disposable = dispose.once(source.run(this, scheduler));
this.active = true;
}
Outer.prototype.event = function(t, x) {
this._addInner(t, x);
};
Outer.prototype._addInner = function(t, x) {
if(this.current.length < this.concurrency) {
this._startInner(t, x);
} else {
this.pending.push(x);
}
};
Outer.prototype._startInner = function(t, x) {
try {
this._initInner(t, x);
} catch(e) {
this.error(t, e);
}
};
Outer.prototype._initInner = function(t, x) {
var innerSink = new Inner(t, this, this.sink);
innerSink.disposable = mapAndRun(this.f, x, innerSink, this.scheduler);
this.current.add(innerSink);
}
function mapAndRun(f, x, sink, scheduler) {
return f(x).source.run(sink, scheduler);
}
Outer.prototype.end = function(t, x) {
this.active = false;
dispose.tryDispose(t, this.disposable, this.sink);
this._checkEnd(t, x);
};
Outer.prototype.error = function(t, e) {
this.active = false;
this.sink.error(t, e);
};
Outer.prototype.dispose = function() {
this.active = false;
this.pending.length = 0;
return Promise.all([this.disposable.dispose(), this.current.dispose()]);
};
Outer.prototype._endInner = function(t, x, inner) {
this.current.remove(inner);
dispose.tryDispose(t, inner, this);
if(this.pending.length === 0) {
this._checkEnd(t, x);
} else {
this._startInner(t, this.pending.shift());
}
};
Outer.prototype._checkEnd = function(t, x) {
if(!this.active && this.current.isEmpty()) {
this.sink.end(t, x);
}
};
function Inner(time, outer, sink) {
this.prev = this.next = null;
this.time = time;
this.outer = outer;
this.sink = sink;
this.disposable = void 0;
}
Inner.prototype.event = function(t, x) {
this.sink.event(Math.max(t, this.time), x);
};
Inner.prototype.end = function(t, x) {
this.outer._endInner(Math.max(t, this.time), x, this);
};
Inner.prototype.error = function(t, e) {
this.outer.error(Math.max(t, this.time), e);
};
Inner.prototype.dispose = function() {
return this.disposable.dispose();
};
},{"../LinkedList":316,"../Stream":319,"../disposable/dispose":348,"@most/prelude":4}],334:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var run = require('../runSource').withDefaultScheduler;
var tap = require('./transform').tap;
exports.observe = observe;
exports.drain = drain;
/**
* Observe all the event values in the stream in time order. The
* provided function `f` will be called for each event value
* @param {function(x:T):*} f function to call with each event value
* @param {Stream<T>} stream stream to observe
* @return {Promise} promise that fulfills after the stream ends without
* an error, or rejects if the stream ends with an error.
*/
function observe(f, stream) {
return drain(tap(f, stream));
}
var defaultScheduler = require('../scheduler/defaultScheduler');
var dispose = require('../disposable/dispose');
/**
* "Run" a stream by creating demand and consuming all events
* @param {Stream<T>} stream stream to drain
* @return {Promise} promise that fulfills after the stream ends without
* an error, or rejects if the stream ends with an error.
*/
function drain(stream) {
return run(stream.source);
}
},{"../disposable/dispose":348,"../runSource":358,"../scheduler/defaultScheduler":361,"./transform":343}],335:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var fatal = require('../fatalError');
var just = require('../source/core').of;
exports.fromPromise = fromPromise;
exports.awaitPromises = awaitPromises;
/**
* Create a stream containing only the promise's fulfillment
* value at the time it fulfills.
* @param {Promise<T>} p promise
* @return {Stream<T>} stream containing promise's fulfillment value.
* If the promise rejects, the stream will error
*/
function fromPromise(p) {
return awaitPromises(just(p));
}
/**
* Turn a Stream<Promise<T>> into Stream<T> by awaiting each promise.
* Event order is preserved.
* @param {Stream<Promise<T>>} stream
* @return {Stream<T>} stream of fulfillment values. The stream will
* error if any promise rejects.
*/
function awaitPromises(stream) {
return new Stream(new Await(stream.source));
}
function Await(source) {
this.source = source;
}
Await.prototype.run = function(sink, scheduler) {
return this.source.run(new AwaitSink(sink, scheduler), scheduler);
};
function AwaitSink(sink, scheduler) {
this.sink = sink;
this.scheduler = scheduler;
this.queue = Promise.resolve();
var self = this;
// Pre-create closures, to avoid creating them per event
this._eventBound = function(x) {
self.sink.event(self.scheduler.now(), x);
};
this._endBound = function(x) {
self.sink.end(self.scheduler.now(), x);
};
this._errorBound = function(e) {
self.sink.error(self.scheduler.now(), e);
};
}
AwaitSink.prototype.event = function(t, promise) {
var self = this;
this.queue = this.queue.then(function() {
return self._event(promise);
}).catch(this._errorBound);
};
AwaitSink.prototype.end = function(t, x) {
var self = this;
this.queue = this.queue.then(function() {
return self._end(x);
}).catch(this._errorBound);
};
AwaitSink.prototype.error = function(t, e) {
var self = this;
// Don't resolve error values, propagate directly
this.queue = this.queue.then(function() {
return self._errorBound(e);
}).catch(fatal);
};
AwaitSink.prototype._event = function(promise) {
return promise.then(this._eventBound);
};
AwaitSink.prototype._end = function(x) {
return Promise.resolve(x).then(this._endBound);
};
},{"../Stream":319,"../fatalError":349,"../source/core":370}],336:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Pipe = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var base = require('@most/prelude');
var invoke = require('../invoke');
exports.sample = sample;
exports.sampleWith = sampleWith;
exports.sampleArray = sampleArray;
/**
* When an event arrives on sampler, emit the result of calling f with the latest
* values of all streams being sampled
* @param {function(...values):*} f function to apply to each set of sampled values
* @param {Stream} sampler streams will be sampled whenever an event arrives
* on sampler
* @returns {Stream} stream of sampled and transformed values
*/
function sample(f, sampler /*, ...streams */) {
return sampleArray(f, sampler, base.drop(2, arguments));
}
/**
* When an event arrives on sampler, emit the latest event value from stream.
* @param {Stream} sampler stream of events at whose arrival time
* stream's latest value will be propagated
* @param {Stream} stream stream of values
* @returns {Stream} sampled stream of values
*/
function sampleWith(sampler, stream) {
return new Stream(new Sampler(base.id, sampler.source, [stream.source]));
}
function sampleArray(f, sampler, streams) {
return new Stream(new Sampler(f, sampler.source, base.map(getSource, streams)));
}
function getSource(stream) {
return stream.source;
}
function Sampler(f, sampler, sources) {
this.f = f;
this.sampler = sampler;
this.sources = sources;
}
Sampler.prototype.run = function(sink, scheduler) {
var l = this.sources.length;
var disposables = new Array(l+1);
var sinks = new Array(l);
var sampleSink = new SampleSink(this.f, sinks, sink);
for(var hold, i=0; i<l; ++i) {
hold = sinks[i] = new Hold(sampleSink);
disposables[i] = this.sources[i].run(hold, scheduler);
}
disposables[i] = this.sampler.run(sampleSink, scheduler);
return dispose.all(disposables);
};
function Hold(sink) {
this.sink = sink;
this.hasValue = false;
}
Hold.prototype.event = function(t, x) {
this.value = x;
this.hasValue = true;
this.sink._notify(this);
};
Hold.prototype.end = function () {};
Hold.prototype.error = Pipe.prototype.error;
function SampleSink(f, sinks, sink) {
this.f = f;
this.sinks = sinks;
this.sink = sink;
this.active = false;
}
SampleSink.prototype._notify = function() {
if(!this.active) {
this.active = this.sinks.every(hasValue);
}
};
SampleSink.prototype.event = function(t) {
if(this.active) {
this.sink.event(t, invoke(this.f, base.map(getValue, this.sinks)));
}
};
SampleSink.prototype.end = Pipe.prototype.end;
SampleSink.prototype.error = Pipe.prototype.error;
function hasValue(hold) {
return hold.hasValue;
}
function getValue(hold) {
return hold.value;
}
},{"../Stream":319,"../disposable/dispose":348,"../invoke":353,"../sink/Pipe":366,"@most/prelude":4}],337:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
var core = require('../source/core');
var dispose = require('../disposable/dispose');
var Map = require('../fusion/Map');
exports.take = take;
exports.skip = skip;
exports.slice = slice;
exports.takeWhile = takeWhile;
exports.skipWhile = skipWhile;
/**
* @param {number} n
* @param {Stream} stream
* @returns {Stream} new stream containing only up to the first n items from stream
*/
function take(n, stream) {
return slice(0, n, stream);
}
/**
* @param {number} n
* @param {Stream} stream
* @returns {Stream} new stream with the first n items removed
*/
function skip(n, stream) {
return slice(n, Infinity, stream);
}
/**
* Slice a stream by index. Negative start/end indexes are not supported
* @param {number} start
* @param {number} end
* @param {Stream} stream
* @returns {Stream} stream containing items where start <= index < end
*/
function slice(start, end, stream) {
return end <= start ? core.empty()
: new Stream(sliceSource(start, end, stream.source));
}
function sliceSource(start, end, source) {
return source instanceof Map ? commuteMapSlice(start, end, source)
: source instanceof Slice ? fuseSlice(start, end, source)
: new Slice(start, end, source);
}
function commuteMapSlice(start, end, source) {
return Map.create(source.f, sliceSource(start, end, source.source))
}
function fuseSlice(start, end, source) {
start += source.min;
end = Math.min(end + source.min, source.max);
return new Slice(start, end, source.source);
}
function Slice(min, max, source) {
this.source = source;
this.min = min;
this.max = max;
}
Slice.prototype.run = function(sink, scheduler) {
return new SliceSink(this.min, this.max - this.min, this.source, sink, scheduler);
};
function SliceSink(skip, take, source, sink, scheduler) {
this.sink = sink;
this.skip = skip;
this.take = take;
this.disposable = dispose.once(source.run(this, scheduler));
}
SliceSink.prototype.end = Sink.prototype.end;
SliceSink.prototype.error = Sink.prototype.error;
SliceSink.prototype.event = function(t, x) {
if(this.skip > 0) {
this.skip -= 1;
return;
}
if(this.take === 0) {
return;
}
this.take -= 1;
this.sink.event(t, x);
if(this.take === 0) {
this.dispose();
this.sink.end(t, x);
}
};
SliceSink.prototype.dispose = function() {
return this.disposable.dispose();
};
function takeWhile(p, stream) {
return new Stream(new TakeWhile(p, stream.source));
}
function TakeWhile(p, source) {
this.p = p;
this.source = source;
}
TakeWhile.prototype.run = function(sink, scheduler) {
return new TakeWhileSink(this.p, this.source, sink, scheduler);
};
function TakeWhileSink(p, source, sink, scheduler) {
this.p = p;
this.sink = sink;
this.active = true;
this.disposable = dispose.once(source.run(this, scheduler));
}
TakeWhileSink.prototype.end = Sink.prototype.end;
TakeWhileSink.prototype.error = Sink.prototype.error;
TakeWhileSink.prototype.event = function(t, x) {
if(!this.active) {
return;
}
var p = this.p;
this.active = p(x);
if(this.active) {
this.sink.event(t, x);
} else {
this.dispose();
this.sink.end(t, x);
}
};
TakeWhileSink.prototype.dispose = function() {
return this.disposable.dispose();
};
function skipWhile(p, stream) {
return new Stream(new SkipWhile(p, stream.source));
}
function SkipWhile(p, source) {
this.p = p;
this.source = source;
}
SkipWhile.prototype.run = function(sink, scheduler) {
return this.source.run(new SkipWhileSink(this.p, sink), scheduler);
};
function SkipWhileSink(p, sink) {
this.p = p;
this.sink = sink;
this.skipping = true;
}
SkipWhileSink.prototype.end = Sink.prototype.end;
SkipWhileSink.prototype.error = Sink.prototype.error;
SkipWhileSink.prototype.event = function(t, x) {
if(this.skipping) {
var p = this.p;
this.skipping = p(x);
if(this.skipping) {
return;
}
}
this.sink.event(t, x);
};
},{"../Stream":319,"../disposable/dispose":348,"../fusion/Map":352,"../sink/Pipe":366,"../source/core":370}],338:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var dispose = require('../disposable/dispose');
exports.switch = switchLatest;
/**
* Given a stream of streams, return a new stream that adopts the behavior
* of the most recent inner stream.
* @param {Stream} stream of streams on which to switch
* @returns {Stream} switching stream
*/
function switchLatest(stream) {
return new Stream(new Switch(stream.source));
}
function Switch(source) {
this.source = source;
}
Switch.prototype.run = function(sink, scheduler) {
var switchSink = new SwitchSink(sink, scheduler);
return dispose.all(switchSink, this.source.run(switchSink, scheduler));
};
function SwitchSink(sink, scheduler) {
this.sink = sink;
this.scheduler = scheduler;
this.current = null;
this.ended = false;
}
SwitchSink.prototype.event = function(t, stream) {
this._disposeCurrent(t); // TODO: capture the result of this dispose
this.current = new Segment(t, Infinity, this, this.sink);
this.current.disposable = stream.source.run(this.current, this.scheduler);
};
SwitchSink.prototype.end = function(t, x) {
this.ended = true;
this._checkEnd(t, x);
};
SwitchSink.prototype.error = function(t, e) {
this.ended = true;
this.sink.error(t, e);
};
SwitchSink.prototype.dispose = function() {
return this._disposeCurrent(0);
};
SwitchSink.prototype._disposeCurrent = function(t) {
if(this.current !== null) {
return this.current._dispose(t);
}
};
SwitchSink.prototype._disposeInner = function(t, inner) {
inner._dispose(t); // TODO: capture the result of this dispose
if(inner === this.current) {
this.current = null;
}
};
SwitchSink.prototype._checkEnd = function(t, x) {
if(this.ended && this.current === null) {
this.sink.end(t, x);
}
};
SwitchSink.prototype._endInner = function(t, x, inner) {
this._disposeInner(t, inner);
this._checkEnd(t, x);
};
SwitchSink.prototype._errorInner = function(t, e, inner) {
this._disposeInner(t, inner);
this.sink.error(t, e);
};
function Segment(min, max, outer, sink) {
this.min = min;
this.max = max;
this.outer = outer;
this.sink = sink;
this.disposable = dispose.empty();
}
Segment.prototype.event = function(t, x) {
if(t < this.max) {
this.sink.event(Math.max(t, this.min), x);
}
};
Segment.prototype.end = function(t, x) {
this.outer._endInner(Math.max(t, this.min), x, this);
};
Segment.prototype.error = function(t, e) {
this.outer._errorInner(Math.max(t, this.min), e, this);
};
Segment.prototype._dispose = function(t) {
this.max = t;
dispose.tryDispose(t, this.disposable, this.sink)
};
},{"../Stream":319,"../disposable/dispose":348}],339:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
exports.thru = function thru(f, stream) {
return f(stream);
}
},{}],340:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Pipe = require('../sink/Pipe');
var dispose = require('../disposable/dispose');
var join = require('../combinator/flatMap').join;
exports.during = during;
exports.takeUntil = takeUntil;
exports.skipUntil = skipUntil;
function takeUntil(signal, stream) {
return new Stream(new Until(signal.source, stream.source));
}
function skipUntil(signal, stream) {
return new Stream(new Since(signal.source, stream.source));
}
function during(timeWindow, stream) {
return takeUntil(join(timeWindow), skipUntil(timeWindow, stream));
}
function Until(maxSignal, source) {
this.maxSignal = maxSignal;
this.source = source;
}
Until.prototype.run = function(sink, scheduler) {
var min = new Bound(-Infinity, sink);
var max = new UpperBound(this.maxSignal, sink, scheduler);
var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler);
return dispose.all([min, max, disposable]);
};
function Since(minSignal, source) {
this.minSignal = minSignal;
this.source = source;
}
Since.prototype.run = function(sink, scheduler) {
var min = new LowerBound(this.minSignal, sink, scheduler);
var max = new Bound(Infinity, sink);
var disposable = this.source.run(new TimeWindowSink(min, max, sink), scheduler);
return dispose.all([min, max, disposable]);
};
function Bound(value, sink) {
this.value = value;
this.sink = sink;
}
Bound.prototype.error = Pipe.prototype.error;
Bound.prototype.event = noop;
Bound.prototype.end = noop;
Bound.prototype.dispose = noop;
function TimeWindowSink(min, max, sink) {
this.min = min;
this.max = max;
this.sink = sink;
}
TimeWindowSink.prototype.event = function(t, x) {
if(t >= this.min.value && t < this.max.value) {
this.sink.event(t, x);
}
};
TimeWindowSink.prototype.error = Pipe.prototype.error;
TimeWindowSink.prototype.end = Pipe.prototype.end;
function LowerBound(signal, sink, scheduler) {
this.value = Infinity;
this.sink = sink;
this.disposable = signal.run(this, scheduler);
}
LowerBound.prototype.event = function(t /*, x */) {
if(t < this.value) {
this.value = t;
}
};
LowerBound.prototype.end = noop;
LowerBound.prototype.error = Pipe.prototype.error;
LowerBound.prototype.dispose = function() {
return this.disposable.dispose();
};
function UpperBound(signal, sink, scheduler) {
this.value = Infinity;
this.sink = sink;
this.disposable = signal.run(this, scheduler);
}
UpperBound.prototype.event = function(t, x) {
if(t < this.value) {
this.value = t;
this.sink.end(t, x);
}
};
UpperBound.prototype.end = noop;
UpperBound.prototype.error = Pipe.prototype.error;
UpperBound.prototype.dispose = function() {
return this.disposable.dispose();
};
function noop() {}
},{"../Stream":319,"../combinator/flatMap":329,"../disposable/dispose":348,"../sink/Pipe":366}],341:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Sink = require('../sink/Pipe');
exports.timestamp = timestamp;
function timestamp(stream) {
return new Stream(new Timestamp(stream.source));
}
function Timestamp(source) {
this.source = source;
}
Timestamp.prototype.run = function(sink, scheduler) {
return this.source.run(new TimestampSink(sink), scheduler);
};
function TimestampSink(sink) {
this.sink = sink;
}
TimestampSink.prototype.end = Sink.prototype.end;
TimestampSink.prototype.error = Sink.prototype.error;
TimestampSink.prototype.event = function(t, x) {
this.sink.event(t, { time: t, value: x });
};
},{"../Stream":319,"../sink/Pipe":366}],342:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
exports.transduce = transduce;
/**
* Transform a stream by passing its events through a transducer.
* @param {function} transducer transducer function
* @param {Stream} stream stream whose events will be passed through the
* transducer
* @return {Stream} stream of events transformed by the transducer
*/
function transduce(transducer, stream) {
return new Stream(new Transduce(transducer, stream.source));
}
function Transduce(transducer, source) {
this.transducer = transducer;
this.source = source;
}
Transduce.prototype.run = function(sink, scheduler) {
var xf = this.transducer(new Transformer(sink));
return this.source.run(new TransduceSink(getTxHandler(xf), sink), scheduler);
};
function TransduceSink(adapter, sink) {
this.xf = adapter;
this.sink = sink;
}
TransduceSink.prototype.event = function(t, x) {
var next = this.xf.step(t, x);
return this.xf.isReduced(next)
? this.sink.end(t, this.xf.getResult(next))
: next;
};
TransduceSink.prototype.end = function(t, x) {
return this.xf.result(x);
};
TransduceSink.prototype.error = function(t, e) {
return this.sink.error(t, e);
};
function Transformer(sink) {
this.time = -Infinity;
this.sink = sink;
}
Transformer.prototype['@@transducer/init'] = Transformer.prototype.init = function() {};
Transformer.prototype['@@transducer/step'] = Transformer.prototype.step = function(t, x) {
if(!isNaN(t)) {
this.time = Math.max(t, this.time);
}
return this.sink.event(this.time, x);
};
Transformer.prototype['@@transducer/result'] = Transformer.prototype.result = function(x) {
return this.sink.end(this.time, x);
};
/**
* Given an object supporting the new or legacy transducer protocol,
* create an adapter for it.
* @param {object} tx transform
* @returns {TxAdapter|LegacyTxAdapter}
*/
function getTxHandler(tx) {
return typeof tx['@@transducer/step'] === 'function'
? new TxAdapter(tx)
: new LegacyTxAdapter(tx);
}
/**
* Adapter for new official transducer protocol
* @param {object} tx transform
* @constructor
*/
function TxAdapter(tx) {
this.tx = tx;
}
TxAdapter.prototype.step = function(t, x) {
return this.tx['@@transducer/step'](t, x);
};
TxAdapter.prototype.result = function(x) {
return this.tx['@@transducer/result'](x);
};
TxAdapter.prototype.isReduced = function(x) {
return x != null && x['@@transducer/reduced'];
};
TxAdapter.prototype.getResult = function(x) {
return x['@@transducer/value'];
};
/**
* Adapter for older transducer protocol
* @param {object} tx transform
* @constructor
*/
function LegacyTxAdapter(tx) {
this.tx = tx;
}
LegacyTxAdapter.prototype.step = function(t, x) {
return this.tx.step(t, x);
};
LegacyTxAdapter.prototype.result = function(x) {
return this.tx.result(x);
};
LegacyTxAdapter.prototype.isReduced = function(x) {
return x != null && x.__transducers_reduced__;
};
LegacyTxAdapter.prototype.getResult = function(x) {
return x.value;
};
},{"../Stream":319}],343:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var Map = require('../fusion/Map');
var Pipe = require('../sink/Pipe');
exports.map = map;
exports.constant = constant;
exports.tap = tap;
/**
* Transform each value in the stream by applying f to each
* @param {function(*):*} f mapping function
* @param {Stream} stream stream to map
* @returns {Stream} stream containing items transformed by f
*/
function map(f, stream) {
return new Stream(Map.create(f, stream.source));
}
/**
* Replace each value in the stream with x
* @param {*} x
* @param {Stream} stream
* @returns {Stream} stream containing items replaced with x
*/
function constant(x, stream) {
return map(function() {
return x;
}, stream);
}
/**
* Perform a side effect for each item in the stream
* @param {function(x:*):*} f side effect to execute for each item. The
* return value will be discarded.
* @param {Stream} stream stream to tap
* @returns {Stream} new stream containing the same items as this stream
*/
function tap(f, stream) {
return new Stream(new Tap(f, stream.source));
}
function Tap(f, source) {
this.source = source;
this.f = f;
}
Tap.prototype.run = function(sink, scheduler) {
return this.source.run(new TapSink(this.f, sink), scheduler);
}
function TapSink(f, sink) {
this.sink = sink;
this.f = f;
}
TapSink.prototype.end = Pipe.prototype.end;
TapSink.prototype.error = Pipe.prototype.error;
TapSink.prototype.event = function(t, x) {
var f = this.f;
f(x);
this.sink.event(t, x);
}
},{"../Stream":319,"../fusion/Map":352,"../sink/Pipe":366}],344:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var transform = require('./transform');
var core = require('../source/core');
var Sink = require('../sink/Pipe');
var IndexSink = require('../sink/IndexSink');
var dispose = require('../disposable/dispose');
var base = require('@most/prelude');
var invoke = require('../invoke');
var Queue = require('../Queue');
var map = base.map;
var tail = base.tail;
exports.zip = zip;
exports.zipArray = zipArray;
/**
* Combine streams pairwise (or tuple-wise) by index by applying f to values
* at corresponding indices. The returned stream ends when any of the input
* streams ends.
* @param {function} f function to combine values
* @returns {Stream} new stream with items at corresponding indices combined
* using f
*/
function zip(f /*,...streams */) {
return zipArray(f, tail(arguments));
}
/**
* Combine streams pairwise (or tuple-wise) by index by applying f to values
* at corresponding indices. The returned stream ends when any of the input
* streams ends.
* @param {function} f function to combine values
* @param {[Stream]} streams streams to zip using f
* @returns {Stream} new stream with items at corresponding indices combined
* using f
*/
function zipArray(f, streams) {
return streams.length === 0 ? core.empty()
: streams.length === 1 ? transform.map(f, streams[0])
: new Stream(new Zip(f, map(getSource, streams)));
}
function getSource(stream) {
return stream.source;
}
function Zip(f, sources) {
this.f = f;
this.sources = sources;
}
Zip.prototype.run = function(sink, scheduler) {
var l = this.sources.length;
var disposables = new Array(l);
var sinks = new Array(l);
var buffers = new Array(l);
var zipSink = new ZipSink(this.f, buffers, sinks, sink);
for(var indexSink, i=0; i<l; ++i) {
buffers[i] = new Queue();
indexSink = sinks[i] = new IndexSink(i, zipSink);
disposables[i] = this.sources[i].run(indexSink, scheduler);
}
return dispose.all(disposables);
};
function ZipSink(f, buffers, sinks, sink) {
this.f = f;
this.sinks = sinks;
this.sink = sink;
this.buffers = buffers;
}
ZipSink.prototype.event = function(t, indexedValue) {
var buffers = this.buffers;
var buffer = buffers[indexedValue.index];
buffer.push(indexedValue.value);
if(buffer.length() === 1) {
if(!ready(this.buffers)) {
return;
}
emitZipped(this.f, t, buffers, this.sink);
if (ended(this.buffers, this.sinks)) {
this.sink.end(t, void 0);
}
}
};
ZipSink.prototype.end = function(t, indexedValue) {
var buffer = this.buffers[indexedValue.index];
if(buffer.isEmpty()) {
this.sink.end(t, indexedValue.value);
}
};
ZipSink.prototype.error = Sink.prototype.error;
function emitZipped (f, t, buffers, sink) {
sink.event(t, invoke(f, map(head, buffers)));
}
function head(buffer) {
return buffer.shift();
}
function ended(buffers, sinks) {
for(var i=0, l=buffers.length; i<l; ++i) {
if(buffers[i].isEmpty() && !sinks[i].active) {
return true;
}
}
return false;
}
function ready(buffers) {
for(var i=0, l=buffers.length; i<l; ++i) {
if(buffers[i].isEmpty()) {
return false;
}
}
return true;
}
},{"../Queue":318,"../Stream":319,"../disposable/dispose":348,"../invoke":353,"../sink/IndexSink":365,"../sink/Pipe":366,"../source/core":370,"./transform":343,"@most/prelude":4}],345:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = defer;
function defer(task) {
return Promise.resolve(task).then(runTask);
}
function runTask(task) {
try {
return task.run();
} catch(e) {
return task.error(e);
}
}
},{}],346:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = Disposable;
/**
* Create a new Disposable which will dispose its underlying resource.
* @param {function} dispose function
* @param {*?} data any data to be passed to disposer function
* @constructor
*/
function Disposable(dispose, data) {
this._dispose = dispose;
this._data = data;
}
Disposable.prototype.dispose = function() {
return this._dispose(this._data);
};
},{}],347:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = SettableDisposable;
function SettableDisposable() {
this.disposable = void 0;
this.disposed = false;
this._resolve = void 0;
var self = this;
this.result = new Promise(function(resolve) {
self._resolve = resolve;
});
}
SettableDisposable.prototype.setDisposable = function(disposable) {
if(this.disposable !== void 0) {
throw new Error('setDisposable called more than once');
}
this.disposable = disposable;
if(this.disposed) {
this._resolve(disposable.dispose());
}
};
SettableDisposable.prototype.dispose = function() {
if(this.disposed) {
return this.result;
}
this.disposed = true;
if(this.disposable !== void 0) {
this.result = this.disposable.dispose();
}
return this.result;
};
},{}],348:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Disposable = require('./Disposable');
var SettableDisposable = require('./SettableDisposable');
var isPromise = require('../Promise').isPromise;
var base = require('@most/prelude');
var map = base.map;
var identity = base.id;
exports.tryDispose = tryDispose;
exports.create = create;
exports.once = once;
exports.empty = empty;
exports.all = all;
exports.settable = settable;
exports.promised = promised;
/**
* Call disposable.dispose. If it returns a promise, catch promise
* error and forward it through the provided sink.
* @param {number} t time
* @param {{dispose: function}} disposable
* @param {{error: function}} sink
* @return {*} result of disposable.dispose
*/
function tryDispose(t, disposable, sink) {
var result = disposeSafely(disposable);
return isPromise(result)
? result.catch(function (e) {
sink.error(t, e);
})
: result;
}
/**
* Create a new Disposable which will dispose its underlying resource
* at most once.
* @param {function} dispose function
* @param {*?} data any data to be passed to disposer function
* @return {Disposable}
*/
function create(dispose, data) {
return once(new Disposable(dispose, data));
}
/**
* Create a noop disposable. Can be used to satisfy a Disposable
* requirement when no actual resource needs to be disposed.
* @return {Disposable|exports|module.exports}
*/
function empty() {
return new Disposable(identity, void 0);
}
/**
* Create a disposable that will dispose all input disposables in parallel.
* @param {Array<Disposable>} disposables
* @return {Disposable}
*/
function all(disposables) {
return create(disposeAll, disposables);
}
function disposeAll(disposables) {
return Promise.all(map(disposeSafely, disposables));
}
function disposeSafely(disposable) {
try {
return disposable.dispose();
} catch(e) {
return Promise.reject(e);
}
}
/**
* Create a disposable from a promise for another disposable
* @param {Promise<Disposable>} disposablePromise
* @return {Disposable}
*/
function promised(disposablePromise) {
return create(disposePromise, disposablePromise);
}
function disposePromise(disposablePromise) {
return disposablePromise.then(disposeOne);
}
function disposeOne(disposable) {
return disposable.dispose();
}
/**
* Create a disposable proxy that allows its underlying disposable to
* be set later.
* @return {SettableDisposable}
*/
function settable() {
return new SettableDisposable();
}
/**
* Wrap an existing disposable (which may not already have been once()d)
* so that it will only dispose its underlying resource at most once.
* @param {{ dispose: function() }} disposable
* @return {Disposable} wrapped disposable
*/
function once(disposable) {
return new Disposable(disposeMemoized, memoized(disposable));
}
function disposeMemoized(memoized) {
if(!memoized.disposed) {
memoized.disposed = true;
memoized.value = disposeSafely(memoized.disposable);
memoized.disposable = void 0;
}
return memoized.value;
}
function memoized(disposable) {
return { disposed: false, disposable: disposable, value: void 0 };
}
},{"../Promise":317,"./Disposable":346,"./SettableDisposable":347,"@most/prelude":4}],349:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = fatalError;
function fatalError (e) {
setTimeout(function() {
throw e;
}, 0);
}
},{}],350:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Pipe = require('../sink/Pipe');
module.exports = Filter;
function Filter(p, source) {
this.p = p;
this.source = source;
}
/**
* Create a filtered source, fusing adjacent filter.filter if possible
* @param {function(x:*):boolean} p filtering predicate
* @param {{run:function}} source source to filter
* @returns {Filter} filtered source
*/
Filter.create = function createFilter(p, source) {
if (source instanceof Filter) {
return new Filter(and(source.p, p), source.source);
}
return new Filter(p, source);
};
Filter.prototype.run = function(sink, scheduler) {
return this.source.run(new FilterSink(this.p, sink), scheduler);
};
function FilterSink(p, sink) {
this.p = p;
this.sink = sink;
}
FilterSink.prototype.end = Pipe.prototype.end;
FilterSink.prototype.error = Pipe.prototype.error;
FilterSink.prototype.event = function(t, x) {
var p = this.p;
p(x) && this.sink.event(t, x);
};
function and(p, q) {
return function(x) {
return p(x) && q(x);
};
}
},{"../sink/Pipe":366}],351:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Pipe = require('../sink/Pipe');
module.exports = FilterMap;
function FilterMap(p, f, source) {
this.p = p;
this.f = f;
this.source = source;
}
FilterMap.prototype.run = function(sink, scheduler) {
return this.source.run(new FilterMapSink(this.p, this.f, sink), scheduler);
};
function FilterMapSink(p, f, sink) {
this.p = p;
this.f = f;
this.sink = sink;
}
FilterMapSink.prototype.event = function(t, x) {
var f = this.f;
var p = this.p;
p(x) && this.sink.event(t, f(x));
};
FilterMapSink.prototype.end = Pipe.prototype.end;
FilterMapSink.prototype.error = Pipe.prototype.error;
},{"../sink/Pipe":366}],352:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Pipe = require('../sink/Pipe');
var Filter = require('./Filter');
var FilterMap = require('./FilterMap');
var base = require('@most/prelude');
module.exports = Map;
function Map(f, source) {
this.f = f;
this.source = source;
}
/**
* Create a mapped source, fusing adjacent map.map, filter.map,
* and filter.map.map if possible
* @param {function(*):*} f mapping function
* @param {{run:function}} source source to map
* @returns {Map|FilterMap} mapped source, possibly fused
*/
Map.create = function createMap(f, source) {
if(source instanceof Map) {
return new Map(base.compose(f, source.f), source.source);
}
if(source instanceof Filter) {
return new FilterMap(source.p, f, source.source);
}
return new Map(f, source);
};
Map.prototype.run = function(sink, scheduler) {
return this.source.run(new MapSink(this.f, sink), scheduler);
};
function MapSink(f, sink) {
this.f = f;
this.sink = sink;
}
MapSink.prototype.end = Pipe.prototype.end;
MapSink.prototype.error = Pipe.prototype.error;
MapSink.prototype.event = function(t, x) {
var f = this.f;
this.sink.event(t, f(x));
};
},{"../sink/Pipe":366,"./Filter":350,"./FilterMap":351,"@most/prelude":4}],353:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = invoke;
function invoke(f, args) {
/*eslint complexity: [2,7]*/
switch(args.length) {
case 0: return f();
case 1: return f(args[0]);
case 2: return f(args[0], args[1]);
case 3: return f(args[0], args[1], args[2]);
case 4: return f(args[0], args[1], args[2], args[3]);
case 5: return f(args[0], args[1], args[2], args[3], args[4]);
default:
return f.apply(void 0, args);
}
}
},{}],354:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
exports.isIterable = isIterable;
exports.getIterator = getIterator;
exports.makeIterable = makeIterable;
/*global Set, Symbol*/
var iteratorSymbol;
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
if (typeof Set === 'function' && typeof new Set()['@@iterator'] === 'function') {
iteratorSymbol = '@@iterator';
} else {
iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator ||
'_es6shim_iterator_';
}
function isIterable(o) {
return typeof o[iteratorSymbol] === 'function';
}
function getIterator(o) {
return o[iteratorSymbol]();
}
function makeIterable(f, o) {
o[iteratorSymbol] = f;
return o;
}
},{}],355:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var dispose = require('../disposable/dispose');
exports.fromObservable = fromObservable;
exports.ObservableSource = ObservableSource;
exports.SubscriberSink = SubscriberSink;
function fromObservable(observable) {
return new Stream(new ObservableSource(observable));
}
function ObservableSource(observable) {
this.observable = observable;
}
ObservableSource.prototype.run = function(sink, scheduler) {
var sub = this.observable.subscribe(new SubscriberSink(sink, scheduler));
if(typeof sub === 'function') {
return dispose.create(sub);
} else if(sub && typeof sub.unsubscribe === 'function') {
return dispose.create(unsubscribe, sub);
}
throw new TypeError('Observable returned invalid subscription ' + String(sub));
}
function SubscriberSink(sink, scheduler) {
this.sink = sink;
this.scheduler = scheduler;
}
SubscriberSink.prototype.next = function(x) {
this.sink.event(this.scheduler.now(), x);
}
SubscriberSink.prototype.complete = function(x) {
this.sink.end(this.scheduler.now(), x);
}
SubscriberSink.prototype.error = function(e) {
this.sink.error(this.scheduler.now(), e);
}
function unsubscribe(subscription) {
return subscription.unsubscribe();
}
},{"../Stream":319,"../disposable/dispose":348}],356:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var symbolObservable = require('symbol-observable');
module.exports = getObservable;
function getObservable(o) {
var obs = null;
if(o != null && typeof o === 'object') {
var method = o[symbolObservable];
if(typeof method === 'function') {
obs = method.call(o);
if(obs == null || typeof obs !== 'object') {
throw new TypeError('invalid observable ' + obs);
}
}
}
return obs;
}
},{"symbol-observable":384}],357:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var defaultScheduler = require('../scheduler/defaultScheduler');
var dispose = require('../disposable/dispose');
var fatalError = require('../fatalError');
exports.subscribe = subscribe;
exports.SubscribeObserver = SubscribeObserver;
exports.Subscription = Subscription;
function subscribe(subscriber, stream) {
if(subscriber == null || typeof subscriber !== 'object') {
throw new TypeError('subscriber must be an object');
}
var disposable = dispose.settable();
var observer = new SubscribeObserver(fatalError, subscriber, disposable);
disposable.setDisposable(stream.source.run(observer, defaultScheduler));
return new Subscription(disposable);
}
function SubscribeObserver(fatalError, subscriber, disposable) {
this.fatalError = fatalError;
this.subscriber = subscriber;
this.disposable = disposable;
}
SubscribeObserver.prototype.event = function(t, x) {
if(typeof this.subscriber.next === 'function') {
this.subscriber.next(x);
}
};
SubscribeObserver.prototype.end = function(t, x) {
var s = this.subscriber;
doDispose(this.fatalError, s, s.complete, s.error, this.disposable, x);
};
SubscribeObserver.prototype.error = function(t, e) {
var s = this.subscriber;
doDispose(this.fatalError, s, s.error, s.error, this.disposable, e);
};
function Subscription(disposable) {
this.disposable = disposable;
}
Subscription.prototype.unsubscribe = function() {
this.disposable.dispose();
}
function doDispose(fatal, subscriber, complete, error, disposable, x) {
Promise.resolve(disposable.dispose()).then(function () {
if(typeof complete === 'function') {
complete.call(subscriber, x);
}
}).catch(function(e) {
if(typeof error === 'function') {
error.call(subscriber, e);
}
}).catch(fatal);
}
},{"../disposable/dispose":348,"../fatalError":349,"../scheduler/defaultScheduler":361}],358:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var dispose = require('./disposable/dispose');
var defaultScheduler = require('./scheduler/defaultScheduler');
exports.withDefaultScheduler = withDefaultScheduler;
exports.withScheduler = withScheduler;
function withDefaultScheduler(source) {
return withScheduler(source, defaultScheduler);
}
function withScheduler(source, scheduler) {
return new Promise(function (resolve, reject) {
runSource(source, scheduler, resolve, reject);
});
}
function runSource(source, scheduler, resolve, reject) {
var disposable = dispose.settable();
var observer = new Drain(resolve, reject, disposable);
disposable.setDisposable(source.run(observer, scheduler));
}
function Drain(end, error, disposable) {
this._end = end;
this._error = error;
this._disposable = disposable;
this.active = true;
}
Drain.prototype.event = function(t, x) {};
Drain.prototype.end = function(t, x) {
if (!this.active) {
return;
}
this.active = false;
disposeThen(this._end, this._error, this._disposable, x);
};
Drain.prototype.error = function(t, e) {
this.active = false;
disposeThen(this._error, this._error, this._disposable, e);
};
function disposeThen(end, error, disposable, x) {
Promise.resolve(disposable.dispose()).then(function () {
end(x);
}, error);
}
},{"./disposable/dispose":348,"./scheduler/defaultScheduler":361}],359:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var fatal = require('../fatalError');
module.exports = PropagateTask;
function PropagateTask(run, value, sink) {
this._run = run;
this.value = value;
this.sink = sink;
this.active = true;
}
PropagateTask.event = function(value, sink) {
return new PropagateTask(emit, value, sink);
};
PropagateTask.end = function(value, sink) {
return new PropagateTask(end, value, sink);
};
PropagateTask.error = function(value, sink) {
return new PropagateTask(error, value, sink);
};
PropagateTask.prototype.dispose = function() {
this.active = false;
};
PropagateTask.prototype.run = function(t) {
if(!this.active) {
return;
}
this._run(t, this.value, this.sink);
};
PropagateTask.prototype.error = function(t, e) {
if(!this.active) {
return fatal(e);
}
this.sink.error(t, e);
};
function error(t, e, sink) {
sink.error(t, e);
}
function emit(t, x, sink) {
sink.event(t, x);
}
function end(t, x, sink) {
sink.end(t, x);
}
},{"../fatalError":349}],360:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var base = require('@most/prelude');
module.exports = Scheduler;
function ScheduledTask(delay, period, task, scheduler) {
this.time = delay;
this.period = period;
this.task = task;
this.scheduler = scheduler;
this.active = true;
}
ScheduledTask.prototype.run = function() {
return this.task.run(this.time);
};
ScheduledTask.prototype.error = function(e) {
return this.task.error(this.time, e);
};
ScheduledTask.prototype.dispose = function() {
this.scheduler.cancel(this);
return this.task.dispose();
};
function runTask(task) {
try {
return task.run();
} catch(e) {
return task.error(e);
}
}
function Scheduler(timer) {
this.timer = timer;
this._timer = null;
this._nextArrival = 0;
this._tasks = [];
var self = this;
this._runReadyTasksBound = function() {
self._runReadyTasks(self.now());
};
}
Scheduler.prototype.now = function() {
return this.timer.now();
};
Scheduler.prototype.asap = function(task) {
return this.schedule(0, -1, task);
};
Scheduler.prototype.delay = function(delay, task) {
return this.schedule(delay, -1, task);
};
Scheduler.prototype.periodic = function(period, task) {
return this.schedule(0, period, task);
};
Scheduler.prototype.schedule = function(delay, period, task) {
var now = this.now();
var st = new ScheduledTask(now + Math.max(0, delay), period, task, this);
insertByTime(st, this._tasks);
this._scheduleNextRun(now);
return st;
};
Scheduler.prototype.cancel = function(task) {
task.active = false;
var i = binarySearch(task.time, this._tasks);
if(i >= 0 && i < this._tasks.length) {
var at = base.findIndex(task, this._tasks[i].events);
if(at >= 0) {
this._tasks[i].events.splice(at, 1);
this._reschedule();
}
}
};
Scheduler.prototype.cancelAll = function(f) {
for(var i=0; i<this._tasks.length; ++i) {
removeAllFrom(f, this._tasks[i]);
}
this._reschedule();
};
function removeAllFrom(f, timeslot) {
timeslot.events = base.removeAll(f, timeslot.events);
}
Scheduler.prototype._reschedule = function() {
if(this._tasks.length === 0) {
this._unschedule();
} else {
this._scheduleNextRun(this.now());
}
};
Scheduler.prototype._unschedule = function() {
this.timer.clearTimer(this._timer);
this._timer = null;
};
Scheduler.prototype._scheduleNextRun = function(now) {
if(this._tasks.length === 0) {
return;
}
var nextArrival = this._tasks[0].time;
if(this._timer === null) {
this._scheduleNextArrival(nextArrival, now);
} else if(nextArrival < this._nextArrival) {
this._unschedule();
this._scheduleNextArrival(nextArrival, now);
}
};
Scheduler.prototype._scheduleNextArrival = function(nextArrival, now) {
this._nextArrival = nextArrival;
var delay = Math.max(0, nextArrival - now);
this._timer = this.timer.setTimer(this._runReadyTasksBound, delay);
};
Scheduler.prototype._runReadyTasks = function(now) {
this._timer = null;
this._tasks = this._findAndRunTasks(now);
this._scheduleNextRun(this.now());
};
Scheduler.prototype._findAndRunTasks = function(now) {
var tasks = this._tasks;
var l = tasks.length;
var i = 0;
while(i < l && tasks[i].time <= now) {
++i;
}
this._tasks = tasks.slice(i);
// Run all ready tasks
for (var j = 0; j < i; ++j) {
this._tasks = runTasks(tasks[j], this._tasks);
}
return this._tasks;
};
function runTasks(timeslot, tasks) {
var events = timeslot.events;
for(var i=0; i<events.length; ++i) {
var task = events[i];
if(task.active) {
runTask(task);
// Reschedule periodic repeating tasks
// Check active again, since a task may have canceled itself
if(task.period >= 0) {
task.time = task.time + task.period;
insertByTime(task, tasks);
}
}
}
return tasks;
}
function insertByTime(task, timeslots) {
var l = timeslots.length;
if(l === 0) {
timeslots.push(newTimeslot(task.time, [task]));
return;
}
var i = binarySearch(task.time, timeslots);
if(i >= l) {
timeslots.push(newTimeslot(task.time, [task]));
} else if(task.time === timeslots[i].time) {
timeslots[i].events.push(task);
} else {
timeslots.splice(i, 0, newTimeslot(task.time, [task]));
}
}
function binarySearch(t, sortedArray) {
var lo = 0;
var hi = sortedArray.length;
var mid, y;
while (lo < hi) {
mid = Math.floor((lo + hi) / 2);
y = sortedArray[mid];
if (t === y.time) {
return mid;
} else if (t < y.time) {
hi = mid;
} else {
lo = mid + 1;
}
}
return hi;
}
function newTimeslot(t, events) {
return { time: t, events: events };
}
},{"@most/prelude":4}],361:[function(require,module,exports){
(function (process){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Scheduler = require('./Scheduler');
var setTimeoutTimer = require('./timeoutTimer');
var nodeTimer = require('./nodeTimer');
var isNode = typeof process === 'object'
&& typeof process.nextTick === 'function';
module.exports = new Scheduler(isNode ? nodeTimer : setTimeoutTimer);
}).call(this,require('_process'))
},{"./Scheduler":360,"./nodeTimer":362,"./timeoutTimer":363,"_process":382}],362:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var defer = require('../defer');
/*global setTimeout, clearTimeout*/
function Task(f) {
this.f = f;
this.active = true;
}
Task.prototype.run = function() {
if(!this.active) {
return;
}
var f = this.f;
return f();
};
Task.prototype.error = function(e) {
throw e;
};
Task.prototype.cancel = function() {
this.active = false;
};
function runAsTask(f) {
var task = new Task(f);
defer(task);
return task;
}
module.exports = {
now: Date.now,
setTimer: function(f, dt) {
return dt <= 0 ? runAsTask(f) : setTimeout(f, dt);
},
clearTimer: function(t) {
return t instanceof Task ? t.cancel() : clearTimeout(t);
}
};
},{"../defer":345}],363:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
/*global setTimeout, clearTimeout*/
module.exports = {
now: Date.now,
setTimer: function(f, dt) {
return setTimeout(f, dt);
},
clearTimer: function(t) {
return clearTimeout(t);
}
};
},{}],364:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var defer = require('../defer');
module.exports = DeferredSink;
function DeferredSink(sink) {
this.sink = sink;
this.events = [];
this.active = true;
}
DeferredSink.prototype.event = function(t, x) {
if(!this.active) {
return;
}
if(this.events.length === 0) {
defer(new PropagateAllTask(this.sink, this.events));
}
this.events.push({ time: t, value: x });
};
DeferredSink.prototype.error = function(t, e) {
this._end(new ErrorTask(t, e, this.sink));
};
DeferredSink.prototype.end = function(t, x) {
this._end(new EndTask(t, x, this.sink));
};
DeferredSink.prototype._end = function(task) {
this.active = false;
this.events = void 0;
defer(task);
}
function PropagateAllTask(sink, events) {
this.sink = sink;
this.events = events;
}
PropagateAllTask.prototype.run = function() {
var events = this.events;
var sink = this.sink;
var event;
for(var i = 0, l = events.length; i<l; ++i) {
event = events[i];
sink.event(event.time, event.value);
}
events.length = 0;
};
PropagateAllTask.prototype.error = function(e) {
this.sink.error(0, e);
};
function EndTask(t, x, sink) {
this.time = t;
this.value = x;
this.sink = sink;
}
EndTask.prototype.run = function() {
this.sink.end(this.time, this.value);
};
EndTask.prototype.error = function(e) {
this.sink.error(this.time, e);
};
function ErrorTask(t, e, sink) {
this.time = t;
this.value = e;
this.sink = sink;
}
ErrorTask.prototype.run = function() {
this.sink.error(this.time, this.value);
};
ErrorTask.prototype.error = function(e) {
throw e;
};
},{"../defer":345}],365:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Sink = require('./Pipe');
module.exports = IndexSink;
function IndexSink(i, sink) {
this.sink = sink;
this.index = i;
this.active = true;
this.value = void 0;
}
IndexSink.prototype.event = function(t, x) {
if(!this.active) {
return;
}
this.value = x;
this.sink.event(t, this);
};
IndexSink.prototype.end = function(t, x) {
if(!this.active) {
return;
}
this.active = false;
this.sink.end(t, { index: this.index, value: x });
};
IndexSink.prototype.error = Sink.prototype.error;
},{"./Pipe":366}],366:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = Pipe;
/**
* A sink mixin that simply forwards event, end, and error to
* another sink.
* @param sink
* @constructor
*/
function Pipe(sink) {
this.sink = sink;
}
Pipe.prototype.event = function(t, x) {
return this.sink.event(t, x);
};
Pipe.prototype.end = function(t, x) {
return this.sink.end(t, x);
};
Pipe.prototype.error = function(t, e) {
return this.sink.error(t, e);
};
},{}],367:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
module.exports = SafeSink;
function SafeSink(sink) {
this.sink = sink;
this.active = true;
}
SafeSink.prototype.event = function(t, x) {
if(!this.active) {
return;
}
this.sink.event(t, x);
};
SafeSink.prototype.end = function(t, x) {
if(!this.active) {
return;
}
this.disable();
this.sink.end(t, x);
};
SafeSink.prototype.error = function(t, e) {
this.disable();
this.sink.error(t, e);
};
SafeSink.prototype.disable = function() {
this.active = false;
return this.sink;
}
},{}],368:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var DeferredSink = require('../sink/DeferredSink');
var dispose = require('../disposable/dispose');
var tryEvent = require('./tryEvent');
module.exports = EventEmitterSource;
function EventEmitterSource(event, source) {
this.event = event;
this.source = source;
}
EventEmitterSource.prototype.run = function(sink, scheduler) {
// NOTE: Because EventEmitter allows events in the same call stack as
// a listener is added, use a DeferredSink to buffer events
// until the stack clears, then propagate. This maintains most.js's
// invariant that no event will be delivered in the same call stack
// as an observer begins observing.
var dsink = new DeferredSink(sink);
function addEventVariadic(a) {
var l = arguments.length;
if(l > 1) {
var arr = new Array(l);
for(var i=0; i<l; ++i) {
arr[i] = arguments[i];
}
tryEvent.tryEvent(scheduler.now(), arr, dsink);
} else {
tryEvent.tryEvent(scheduler.now(), a, dsink);
}
}
this.source.addListener(this.event, addEventVariadic);
return dispose.create(disposeEventEmitter, { target: this, addEvent: addEventVariadic });
};
function disposeEventEmitter(info) {
var target = info.target;
target.source.removeListener(target.event, info.addEvent);
}
},{"../disposable/dispose":348,"../sink/DeferredSink":364,"./tryEvent":379}],369:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var dispose = require('../disposable/dispose');
var tryEvent = require('./tryEvent');
module.exports = EventTargetSource;
function EventTargetSource(event, source, capture) {
this.event = event;
this.source = source;
this.capture = capture;
}
EventTargetSource.prototype.run = function(sink, scheduler) {
function addEvent(e) {
tryEvent.tryEvent(scheduler.now(), e, sink);
}
this.source.addEventListener(this.event, addEvent, this.capture);
return dispose.create(disposeEventTarget,
{ target: this, addEvent: addEvent });
};
function disposeEventTarget(info) {
var target = info.target;
target.source.removeEventListener(target.event, info.addEvent, target.capture);
}
},{"../disposable/dispose":348,"./tryEvent":379}],370:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var dispose = require('../disposable/dispose');
var PropagateTask = require('../scheduler/PropagateTask');
exports.of = streamOf;
exports.empty = empty;
exports.never = never;
/**
* Stream containing only x
* @param {*} x
* @returns {Stream}
*/
function streamOf(x) {
return new Stream(new Just(x));
}
function Just(x) {
this.value = x;
}
Just.prototype.run = function(sink, scheduler) {
return scheduler.asap(new PropagateTask(runJust, this.value, sink));
};
function runJust(t, x, sink) {
sink.event(t, x);
sink.end(t, void 0);
}
/**
* Stream containing no events and ends immediately
* @returns {Stream}
*/
function empty() {
return EMPTY;
}
function EmptySource() {}
EmptySource.prototype.run = function(sink, scheduler) {
var task = PropagateTask.end(void 0, sink);
scheduler.asap(task);
return dispose.create(disposeEmpty, task);
};
function disposeEmpty(task) {
return task.dispose();
}
var EMPTY = new Stream(new EmptySource());
/**
* Stream containing no events and never ends
* @returns {Stream}
*/
function never() {
return NEVER;
}
function NeverSource() {}
NeverSource.prototype.run = function() {
return dispose.empty();
};
var NEVER = new Stream(new NeverSource());
},{"../Stream":319,"../disposable/dispose":348,"../scheduler/PropagateTask":359}],371:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var MulticastSource = require('@most/multicast').MulticastSource;
var DeferredSink = require('../sink/DeferredSink');
var tryEvent = require('./tryEvent');
exports.create = create;
/**
* @deprecated
*/
function create(run) {
return new Stream(new MulticastSource(new SubscriberSource(run)));
}
function SubscriberSource(subscribe) {
this._subscribe = subscribe;
}
SubscriberSource.prototype.run = function(sink, scheduler) {
return new Subscription(new DeferredSink(sink), scheduler, this._subscribe);
};
function Subscription(sink, scheduler, subscribe) {
this.sink = sink;
this.scheduler = scheduler;
this.active = true;
this._unsubscribe = this._init(subscribe);
}
Subscription.prototype._init = function(subscribe) {
var s = this;
try {
return subscribe(add, end, error);
} catch(e) {
error(e);
}
function add(x) {
s._add(x);
}
function end(x) {
s._end(x);
}
function error(e) {
s._error(e);
}
};
Subscription.prototype._add = function(x) {
if(!this.active) {
return;
}
tryEvent.tryEvent(this.scheduler.now(), x, this.sink);
};
Subscription.prototype._end = function(x) {
if(!this.active) {
return;
}
this.active = false;
tryEvent.tryEnd(this.scheduler.now(), x, this.sink);
};
Subscription.prototype._error = function(x) {
this.active = false;
this.sink.error(this.scheduler.now(), x);
};
Subscription.prototype.dispose = function() {
this.active = false;
if(typeof this._unsubscribe === 'function') {
return this._unsubscribe.call(void 0);
}
};
},{"../Stream":319,"../sink/DeferredSink":364,"./tryEvent":379,"@most/multicast":3}],372:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var fromArray = require('./fromArray').fromArray;
var isIterable = require('../iterable').isIterable;
var fromIterable = require('./fromIterable').fromIterable;
var getObservable = require('../observable/getObservable');
var fromObservable = require('../observable/fromObservable').fromObservable;
var isArrayLike = require('@most/prelude').isArrayLike;
exports.from = from;
function from(a) { // eslint-disable-line complexity
if(a instanceof Stream) {
return a;
}
var observable = getObservable(a);
if(observable != null) {
return fromObservable(observable);
}
if(Array.isArray(a) || isArrayLike(a)) {
return fromArray(a);
}
if(isIterable(a)) {
return fromIterable(a);
}
throw new TypeError('from(x) must be observable, iterable, or array-like: ' + a);
}
},{"../Stream":319,"../iterable":354,"../observable/fromObservable":355,"../observable/getObservable":356,"./fromArray":373,"./fromIterable":375,"@most/prelude":4}],373:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var PropagateTask = require('../scheduler/PropagateTask');
exports.fromArray = fromArray;
function fromArray (a) {
return new Stream(new ArraySource(a));
}
function ArraySource(a) {
this.array = a;
}
ArraySource.prototype.run = function(sink, scheduler) {
return scheduler.asap(new PropagateTask(runProducer, this.array, sink));
};
function runProducer(t, array, sink) {
for(var i=0, l=array.length; i<l && this.active; ++i) {
sink.event(t, array[i]);
}
this.active && end(t);
function end(t) {
sink.end(t);
}
}
},{"../Stream":319,"../scheduler/PropagateTask":359}],374:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var MulticastSource = require('@most/multicast').MulticastSource;
var EventTargetSource = require('./EventTargetSource');
var EventEmitterSource = require('./EventEmitterSource');
exports.fromEvent = fromEvent;
/**
* Create a stream from an EventTarget, such as a DOM Node, or EventEmitter.
* @param {String} event event type name, e.g. 'click'
* @param {EventTarget|EventEmitter} source EventTarget or EventEmitter
* @param {boolean?} useCapture for DOM events, whether to use
* capturing--passed as 3rd parameter to addEventListener.
* @returns {Stream} stream containing all events of the specified type
* from the source.
*/
function fromEvent(event, source /*, useCapture = false */) {
var s;
if(typeof source.addEventListener === 'function' && typeof source.removeEventListener === 'function') {
var capture = arguments.length > 2 && !!arguments[2];
s = new MulticastSource(new EventTargetSource(event, source, capture));
} else if(typeof source.addListener === 'function' && typeof source.removeListener === 'function') {
s = new EventEmitterSource(event, source);
} else {
throw new Error('source must support addEventListener/removeEventListener or addListener/removeListener');
}
return new Stream(s);
}
},{"../Stream":319,"./EventEmitterSource":368,"./EventTargetSource":369,"@most/multicast":3}],375:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var getIterator = require('../iterable').getIterator;
var PropagateTask = require('../scheduler/PropagateTask');
exports.fromIterable = fromIterable;
function fromIterable(iterable) {
return new Stream(new IterableSource(iterable));
}
function IterableSource(iterable) {
this.iterable = iterable;
}
IterableSource.prototype.run = function(sink, scheduler) {
return new IteratorProducer(getIterator(this.iterable), sink, scheduler);
};
function IteratorProducer(iterator, sink, scheduler) {
this.scheduler = scheduler;
this.iterator = iterator;
this.task = new PropagateTask(runProducer, this, sink);
scheduler.asap(this.task);
}
IteratorProducer.prototype.dispose = function() {
return this.task.dispose();
};
function runProducer(t, producer, sink) {
var x = producer.iterator.next();
if(x.done) {
sink.end(t, x.value);
} else {
sink.event(t, x.value);
}
producer.scheduler.asap(producer.task);
}
},{"../Stream":319,"../iterable":354,"../scheduler/PropagateTask":359}],376:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var base = require('@most/prelude');
exports.generate = generate;
/**
* Compute a stream using an *async* generator, which yields promises
* to control event times.
* @param f
* @returns {Stream}
*/
function generate(f /*, ...args */) {
return new Stream(new GenerateSource(f, base.tail(arguments)));
}
function GenerateSource(f, args) {
this.f = f;
this.args = args;
}
GenerateSource.prototype.run = function(sink, scheduler) {
return new Generate(this.f.apply(void 0, this.args), sink, scheduler);
};
function Generate(iterator, sink, scheduler) {
this.iterator = iterator;
this.sink = sink;
this.scheduler = scheduler;
this.active = true;
var self = this;
function err(e) {
self.sink.error(self.scheduler.now(), e);
}
Promise.resolve(this).then(next).catch(err);
}
function next(generate, x) {
return generate.active ? handle(generate, generate.iterator.next(x)) : x;
}
function handle(generate, result) {
if (result.done) {
return generate.sink.end(generate.scheduler.now(), result.value);
}
return Promise.resolve(result.value).then(function (x) {
return emit(generate, x);
}, function(e) {
return error(generate, e);
});
}
function emit(generate, x) {
generate.sink.event(generate.scheduler.now(), x);
return next(generate, x);
}
function error(generate, e) {
return handle(generate, generate.iterator.throw(e));
}
Generate.prototype.dispose = function() {
this.active = false;
};
},{"../Stream":319,"@most/prelude":4}],377:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
exports.iterate = iterate;
/**
* Compute a stream by iteratively calling f to produce values
* Event times may be controlled by returning a Promise from f
* @param {function(x:*):*|Promise<*>} f
* @param {*} x initial value
* @returns {Stream}
*/
function iterate(f, x) {
return new Stream(new IterateSource(f, x));
}
function IterateSource(f, x) {
this.f = f;
this.value = x;
}
IterateSource.prototype.run = function(sink, scheduler) {
return new Iterate(this.f, this.value, sink, scheduler);
};
function Iterate(f, initial, sink, scheduler) {
this.f = f;
this.sink = sink;
this.scheduler = scheduler;
this.active = true;
var x = initial;
var self = this;
function err(e) {
self.sink.error(self.scheduler.now(), e);
}
function start(iterate) {
return stepIterate(iterate, x);
}
Promise.resolve(this).then(start).catch(err);
}
Iterate.prototype.dispose = function() {
this.active = false;
};
function stepIterate(iterate, x) {
iterate.sink.event(iterate.scheduler.now(), x);
if(!iterate.active) {
return x;
}
var f = iterate.f;
return Promise.resolve(f(x)).then(function(y) {
return continueIterate(iterate, y);
});
}
function continueIterate(iterate, x) {
return !iterate.active ? iterate.value : stepIterate(iterate, x);
}
},{"../Stream":319}],378:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
var dispose = require('../disposable/dispose');
var MulticastSource = require('@most/multicast').MulticastSource;
var PropagateTask = require('../scheduler/PropagateTask');
exports.periodic = periodic;
/**
* Create a stream that emits the current time periodically
* @param {Number} period periodicity of events in millis
* @param {*) value value to emit each period
* @returns {Stream} new stream that emits the current time every period
*/
function periodic(period, value) {
return new Stream(new MulticastSource(new Periodic(period, value)));
}
function Periodic(period, value) {
this.period = period;
this.value = value;
}
Periodic.prototype.run = function(sink, scheduler) {
return scheduler.periodic(this.period, new PropagateTask(emit, this.value, sink));
};
function emit(t, x, sink) {
sink.event(t, x);
}
},{"../Stream":319,"../disposable/dispose":348,"../scheduler/PropagateTask":359,"@most/multicast":3}],379:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
exports.tryEvent = tryEvent;
exports.tryEnd = tryEnd;
function tryEvent(t, x, sink) {
try {
sink.event(t, x);
} catch(e) {
sink.error(t, e);
}
}
function tryEnd(t, x, sink) {
try {
sink.end(t, x);
} catch(e) {
sink.error(t, e);
}
}
},{}],380:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('../Stream');
exports.unfold = unfold;
/**
* Compute a stream by unfolding tuples of future values from a seed value
* Event times may be controlled by returning a Promise from f
* @param {function(seed:*):{value:*, seed:*, done:boolean}|Promise<{value:*, seed:*, done:boolean}>} f unfolding function accepts
* a seed and returns a new tuple with a value, new seed, and boolean done flag.
* If tuple.done is true, the stream will end.
* @param {*} seed seed value
* @returns {Stream} stream containing all value of all tuples produced by the
* unfolding function.
*/
function unfold(f, seed) {
return new Stream(new UnfoldSource(f, seed));
}
function UnfoldSource(f, seed) {
this.f = f;
this.value = seed;
}
UnfoldSource.prototype.run = function(sink, scheduler) {
return new Unfold(this.f, this.value, sink, scheduler);
};
function Unfold(f, x, sink, scheduler) {
this.f = f;
this.sink = sink;
this.scheduler = scheduler;
this.active = true;
var self = this;
function err(e) {
self.sink.error(self.scheduler.now(), e);
}
function start(unfold) {
return stepUnfold(unfold, x);
}
Promise.resolve(this).then(start).catch(err);
}
Unfold.prototype.dispose = function() {
this.active = false;
};
function stepUnfold(unfold, x) {
var f = unfold.f;
return Promise.resolve(f(x)).then(function(tuple) {
return continueUnfold(unfold, tuple);
});
}
function continueUnfold(unfold, tuple) {
if(tuple.done) {
unfold.sink.end(unfold.scheduler.now(), tuple.value);
return tuple.value;
}
unfold.sink.event(unfold.scheduler.now(), tuple.value);
if(!unfold.active) {
return tuple.value;
}
return stepUnfold(unfold, tuple.seed);
}
},{"../Stream":319}],381:[function(require,module,exports){
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
var Stream = require('./lib/Stream');
var base = require('@most/prelude');
var core = require('./lib/source/core');
var from = require('./lib/source/from').from;
var periodic = require('./lib/source/periodic').periodic;
var symbolObservable = require('symbol-observable');
/**
* Core stream type
* @type {Stream}
*/
exports.Stream = Stream;
// Add of and empty to constructor for fantasy-land compat
exports.of = Stream.of = core.of;
exports.just = core.of; // easier ES6 import alias
exports.empty = Stream.empty = core.empty;
exports.never = core.never;
exports.from = from;
exports.periodic = periodic;
//-----------------------------------------------------------------------
// Draft ES Observable proposal interop
// https://github.com/zenparsing/es-observable
var subscribe = require('./lib/observable/subscribe').subscribe;
Stream.prototype.subscribe = function(subscriber) {
return subscribe(subscriber, this);
};
Stream.prototype[symbolObservable] = function() {
return this;
}
//-----------------------------------------------------------------------
// Fluent adapter
var thru = require('./lib/combinator/thru').thru;
/**
* Adapt a functional stream transform to fluent style.
* It applies f to the this stream object
* @param {function(s: Stream): Stream} f function that
* receives the stream itself and must return a new stream
* @return {Stream}
*/
Stream.prototype.thru = function(f) {
return thru(f, this);
}
//-----------------------------------------------------------------------
// Creating
var create = require('./lib/source/create');
/**
* @deprecated
* Create a stream by imperatively pushing events.
* @param {function(add:function(x), end:function(e)):function} run function
* that will receive 2 functions as arguments, the first to add new values to the
* stream and the second to end the stream. It may *return* a function that
* will be called once all consumers have stopped observing the stream.
* @returns {Stream} stream containing all events added by run before end
*/
exports.create = create.create;
//-----------------------------------------------------------------------
// Adapting other sources
var events = require('./lib/source/fromEvent');
/**
* Create a stream of events from the supplied EventTarget or EventEmitter
* @param {String} event event name
* @param {EventTarget|EventEmitter} source EventTarget or EventEmitter. The source
* must support either addEventListener/removeEventListener (w3c EventTarget:
* http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget),
* or addListener/removeListener (node EventEmitter: http://nodejs.org/api/events.html)
* @returns {Stream} stream of events of the specified type from the source
*/
exports.fromEvent = events.fromEvent;
//-----------------------------------------------------------------------
// Observing
var observe = require('./lib/combinator/observe');
exports.observe = observe.observe;
exports.forEach = observe.observe;
exports.drain = observe.drain;
/**
* Process all the events in the stream
* @returns {Promise} promise that fulfills when the stream ends, or rejects
* if the stream fails with an unhandled error.
*/
Stream.prototype.observe = Stream.prototype.forEach = function(f) {
return observe.observe(f, this);
};
/**
* Consume all events in the stream, without providing a function to process each.
* This causes a stream to become active and begin emitting events, and is useful
* in cases where all processing has been setup upstream via other combinators, and
* there is no need to process the terminal events.
* @returns {Promise} promise that fulfills when the stream ends, or rejects
* if the stream fails with an unhandled error.
*/
Stream.prototype.drain = function() {
return observe.drain(this);
};
//-------------------------------------------------------
var loop = require('./lib/combinator/loop').loop;
exports.loop = loop;
/**
* Generalized feedback loop. Call a stepper function for each event. The stepper
* will be called with 2 params: the current seed and the an event value. It must
* return a new { seed, value } pair. The `seed` will be fed back into the next
* invocation of stepper, and the `value` will be propagated as the event value.
* @param {function(seed:*, value:*):{seed:*, value:*}} stepper loop step function
* @param {*} seed initial seed value passed to first stepper call
* @returns {Stream} new stream whose values are the `value` field of the objects
* returned by the stepper
*/
Stream.prototype.loop = function(stepper, seed) {
return loop(stepper, seed, this);
};
//-------------------------------------------------------
var accumulate = require('./lib/combinator/accumulate');
exports.scan = accumulate.scan;
exports.reduce = accumulate.reduce;
/**
* Create a stream containing successive reduce results of applying f to
* the previous reduce result and the current stream item.
* @param {function(result:*, x:*):*} f reducer function
* @param {*} initial initial value
* @returns {Stream} new stream containing successive reduce results
*/
Stream.prototype.scan = function(f, initial) {
return accumulate.scan(f, initial, this);
};
/**
* Reduce the stream to produce a single result. Note that reducing an infinite
* stream will return a Promise that never fulfills, but that may reject if an error
* occurs.
* @param {function(result:*, x:*):*} f reducer function
* @param {*} initial optional initial value
* @returns {Promise} promise for the file result of the reduce
*/
Stream.prototype.reduce = function(f, initial) {
return accumulate.reduce(f, initial, this);
};
//-----------------------------------------------------------------------
// Building and extending
var unfold = require('./lib/source/unfold');
var iterate = require('./lib/source/iterate');
var generate = require('./lib/source/generate');
var build = require('./lib/combinator/build');
exports.unfold = unfold.unfold;
exports.iterate = iterate.iterate;
exports.generate = generate.generate;
exports.cycle = build.cycle;
exports.concat = build.concat;
exports.startWith = build.cons;
/**
* @deprecated
* Tie this stream into a circle, thus creating an infinite stream
* @returns {Stream} new infinite stream
*/
Stream.prototype.cycle = function() {
return build.cycle(this);
};
/**
* @param {Stream} tail
* @returns {Stream} new stream containing all items in this followed by
* all items in tail
*/
Stream.prototype.concat = function(tail) {
return build.concat(this, tail);
};
/**
* @param {*} x value to prepend
* @returns {Stream} a new stream with x prepended
*/
Stream.prototype.startWith = function(x) {
return build.cons(x, this);
};
//-----------------------------------------------------------------------
// Transforming
var transform = require('./lib/combinator/transform');
var applicative = require('./lib/combinator/applicative');
exports.map = transform.map;
exports.constant = transform.constant;
exports.tap = transform.tap;
exports.ap = applicative.ap;
/**
* Transform each value in the stream by applying f to each
* @param {function(*):*} f mapping function
* @returns {Stream} stream containing items transformed by f
*/
Stream.prototype.map = function(f) {
return transform.map(f, this);
};
/**
* Assume this stream contains functions, and apply each function to each item
* in the provided stream. This generates, in effect, a cross product.
* @param {Stream} xs stream of items to which
* @returns {Stream} stream containing the cross product of items
*/
Stream.prototype.ap = function(xs) {
return applicative.ap(this, xs);
};
/**
* Replace each value in the stream with x
* @param {*} x
* @returns {Stream} stream containing items replaced with x
*/
Stream.prototype.constant = function(x) {
return transform.constant(x, this);
};
/**
* Perform a side effect for each item in the stream
* @param {function(x:*):*} f side effect to execute for each item. The
* return value will be discarded.
* @returns {Stream} new stream containing the same items as this stream
*/
Stream.prototype.tap = function(f) {
return transform.tap(f, this);
};
//-----------------------------------------------------------------------
// Transducer support
var transduce = require('./lib/combinator/transduce');
exports.transduce = transduce.transduce;
/**
* Transform this stream by passing its events through a transducer.
* @param {function} transducer transducer function
* @return {Stream} stream of events transformed by the transducer
*/
Stream.prototype.transduce = function(transducer) {
return transduce.transduce(transducer, this);
};
//-----------------------------------------------------------------------
// FlatMapping
var flatMap = require('./lib/combinator/flatMap');
exports.flatMap = exports.chain = flatMap.flatMap;
exports.join = flatMap.join;
/**
* Map each value in the stream to a new stream, and merge it into the
* returned outer stream. Event arrival times are preserved.
* @param {function(x:*):Stream} f chaining function, must return a Stream
* @returns {Stream} new stream containing all events from each stream returned by f
*/
Stream.prototype.flatMap = Stream.prototype.chain = function(f) {
return flatMap.flatMap(f, this);
};
/**
* Monadic join. Flatten a Stream<Stream<X>> to Stream<X> by merging inner
* streams to the outer. Event arrival times are preserved.
* @returns {Stream<X>} new stream containing all events of all inner streams
*/
Stream.prototype.join = function() {
return flatMap.join(this);
};
var continueWith = require('./lib/combinator/continueWith').continueWith;
exports.continueWith = continueWith;
exports.flatMapEnd = continueWith;
/**
* Map the end event to a new stream, and begin emitting its values.
* @param {function(x:*):Stream} f function that receives the end event value,
* and *must* return a new Stream to continue with.
* @returns {Stream} new stream that emits all events from the original stream,
* followed by all events from the stream returned by f.
*/
Stream.prototype.continueWith = Stream.prototype.flatMapEnd = function(f) {
return continueWith(f, this);
};
var concatMap = require('./lib/combinator/concatMap').concatMap;
exports.concatMap = concatMap;
Stream.prototype.concatMap = function(f) {
return concatMap(f, this);
};
//-----------------------------------------------------------------------
// Concurrent merging
var mergeConcurrently = require('./lib/combinator/mergeConcurrently');
exports.mergeConcurrently = mergeConcurrently.mergeConcurrently;
/**
* Flatten a Stream<Stream<X>> to Stream<X> by merging inner
* streams to the outer, limiting the number of inner streams that may
* be active concurrently.
* @param {number} concurrency at most this many inner streams will be
* allowed to be active concurrently.
* @return {Stream<X>} new stream containing all events of all inner
* streams, with limited concurrency.
*/
Stream.prototype.mergeConcurrently = function(concurrency) {
return mergeConcurrently.mergeConcurrently(concurrency, this);
};
//-----------------------------------------------------------------------
// Merging
var merge = require('./lib/combinator/merge');
exports.merge = merge.merge;
exports.mergeArray = merge.mergeArray;
/**
* Merge this stream and all the provided streams
* @returns {Stream} stream containing items from this stream and s in time
* order. If two events are simultaneous they will be merged in
* arbitrary order.
*/
Stream.prototype.merge = function(/*...streams*/) {
return merge.mergeArray(base.cons(this, arguments));
};
//-----------------------------------------------------------------------
// Combining
var combine = require('./lib/combinator/combine');
exports.combine = combine.combine;
exports.combineArray = combine.combineArray;
/**
* Combine latest events from all input streams
* @param {function(...events):*} f function to combine most recent events
* @returns {Stream} stream containing the result of applying f to the most recent
* event of each input stream, whenever a new event arrives on any stream.
*/
Stream.prototype.combine = function(f /*, ...streams*/) {
return combine.combineArray(f, base.replace(this, 0, arguments));
};
//-----------------------------------------------------------------------
// Sampling
var sample = require('./lib/combinator/sample');
exports.sample = sample.sample;
exports.sampleWith = sample.sampleWith;
/**
* When an event arrives on sampler, emit the latest event value from stream.
* @param {Stream} sampler stream of events at whose arrival time
* signal's latest value will be propagated
* @returns {Stream} sampled stream of values
*/
Stream.prototype.sampleWith = function(sampler) {
return sample.sampleWith(sampler, this);
};
/**
* When an event arrives on this stream, emit the result of calling f with the latest
* values of all streams being sampled
* @param {function(...values):*} f function to apply to each set of sampled values
* @returns {Stream} stream of sampled and transformed values
*/
Stream.prototype.sample = function(f /* ...streams */) {
return sample.sampleArray(f, this, base.tail(arguments));
};
//-----------------------------------------------------------------------
// Zipping
var zip = require('./lib/combinator/zip');
exports.zip = zip.zip;
/**
* Pair-wise combine items with those in s. Given 2 streams:
* [1,2,3] zipWith f [4,5,6] -> [f(1,4),f(2,5),f(3,6)]
* Note: zip causes fast streams to buffer and wait for slow streams.
* @param {function(a:Stream, b:Stream, ...):*} f function to combine items
* @returns {Stream} new stream containing pairs
*/
Stream.prototype.zip = function(f /*, ...streams*/) {
return zip.zipArray(f, base.replace(this, 0, arguments));
};
//-----------------------------------------------------------------------
// Switching
var switchLatest = require('./lib/combinator/switch').switch;
exports.switch = switchLatest;
exports.switchLatest = switchLatest;
/**
* Given a stream of streams, return a new stream that adopts the behavior
* of the most recent inner stream.
* @returns {Stream} switching stream
*/
Stream.prototype.switch = Stream.prototype.switchLatest = function() {
return switchLatest(this);
};
//-----------------------------------------------------------------------
// Filtering
var filter = require('./lib/combinator/filter');
exports.filter = filter.filter;
exports.skipRepeats = exports.distinct = filter.skipRepeats;
exports.skipRepeatsWith = exports.distinctBy = filter.skipRepeatsWith;
/**
* Retain only items matching a predicate
* stream: -12345678-
* filter(x => x % 2 === 0, stream): --2-4-6-8-
* @param {function(x:*):boolean} p filtering predicate called for each item
* @returns {Stream} stream containing only items for which predicate returns truthy
*/
Stream.prototype.filter = function(p) {
return filter.filter(p, this);
};
/**
* Skip repeated events, using === to compare items
* stream: -abbcd-
* distinct(stream): -ab-cd-
* @returns {Stream} stream with no repeated events
*/
Stream.prototype.skipRepeats = function() {
return filter.skipRepeats(this);
};
/**
* Skip repeated events, using supplied equals function to compare items
* @param {function(a:*, b:*):boolean} equals function to compare items
* @returns {Stream} stream with no repeated events
*/
Stream.prototype.skipRepeatsWith = function(equals) {
return filter.skipRepeatsWith(equals, this);
};
//-----------------------------------------------------------------------
// Slicing
var slice = require('./lib/combinator/slice');
exports.take = slice.take;
exports.skip = slice.skip;
exports.slice = slice.slice;
exports.takeWhile = slice.takeWhile;
exports.skipWhile = slice.skipWhile;
/**
* stream: -abcd-
* take(2, stream): -ab|
* @param {Number} n take up to this many events
* @returns {Stream} stream containing at most the first n items from this stream
*/
Stream.prototype.take = function(n) {
return slice.take(n, this);
};
/**
* stream: -abcd->
* skip(2, stream): ---cd->
* @param {Number} n skip this many events
* @returns {Stream} stream not containing the first n events
*/
Stream.prototype.skip = function(n) {
return slice.skip(n, this);
};
/**
* Slice a stream by event index. Equivalent to, but more efficient than
* stream.take(end).skip(start);
* NOTE: Negative start and end are not supported
* @param {Number} start skip all events before the start index
* @param {Number} end allow all events from the start index to the end index
* @returns {Stream} stream containing items where start <= index < end
*/
Stream.prototype.slice = function(start, end) {
return slice.slice(start, end, this);
};
/**
* stream: -123451234->
* takeWhile(x => x < 5, stream): -1234|
* @param {function(x:*):boolean} p predicate
* @returns {Stream} stream containing items up to, but not including, the
* first item for which p returns falsy.
*/
Stream.prototype.takeWhile = function(p) {
return slice.takeWhile(p, this);
};
/**
* stream: -123451234->
* skipWhile(x => x < 5, stream): -----51234->
* @param {function(x:*):boolean} p predicate
* @returns {Stream} stream containing items following *and including* the
* first item for which p returns falsy.
*/
Stream.prototype.skipWhile = function(p) {
return slice.skipWhile(p, this);
};
//-----------------------------------------------------------------------
// Time slicing
var timeslice = require('./lib/combinator/timeslice');
exports.until = exports.takeUntil = timeslice.takeUntil;
exports.since = exports.skipUntil = timeslice.skipUntil;
exports.during = timeslice.during;
/**
* stream: -a-b-c-d-e-f-g->
* signal: -------x
* takeUntil(signal, stream): -a-b-c-|
* @param {Stream} signal retain only events in stream before the first
* event in signal
* @returns {Stream} new stream containing only events that occur before
* the first event in signal.
*/
Stream.prototype.until = Stream.prototype.takeUntil = function(signal) {
return timeslice.takeUntil(signal, this);
};
/**
* stream: -a-b-c-d-e-f-g->
* signal: -------x
* takeUntil(signal, stream): -------d-e-f-g->
* @param {Stream} signal retain only events in stream at or after the first
* event in signal
* @returns {Stream} new stream containing only events that occur after
* the first event in signal.
*/
Stream.prototype.since = Stream.prototype.skipUntil = function(signal) {
return timeslice.skipUntil(signal, this);
};
/**
* stream: -a-b-c-d-e-f-g->
* timeWindow: -----s
* s: -----t
* stream.during(timeWindow): -----c-d-e-|
* @param {Stream<Stream>} timeWindow a stream whose first event (s) represents
* the window start time. That event (s) is itself a stream whose first event (t)
* represents the window end time
* @returns {Stream} new stream containing only events within the provided timespan
*/
Stream.prototype.during = function(timeWindow) {
return timeslice.during(timeWindow, this);
};
//-----------------------------------------------------------------------
// Delaying
var delay = require('./lib/combinator/delay').delay;
exports.delay = delay;
/**
* @param {Number} delayTime milliseconds to delay each item
* @returns {Stream} new stream containing the same items, but delayed by ms
*/
Stream.prototype.delay = function(delayTime) {
return delay(delayTime, this);
};
//-----------------------------------------------------------------------
// Getting event timestamp
var timestamp = require('./lib/combinator/timestamp').timestamp;
exports.timestamp = timestamp;
/**
* Expose event timestamps into the stream. Turns a Stream<X> into
* Stream<{time:t, value:X}>
* @returns {Stream<{time:number, value:*}>}
*/
Stream.prototype.timestamp = function() {
return timestamp(this);
};
//-----------------------------------------------------------------------
// Rate limiting
var limit = require('./lib/combinator/limit');
exports.throttle = limit.throttle;
exports.debounce = limit.debounce;
/**
* Limit the rate of events
* stream: abcd----abcd----
* throttle(2, stream): a-c-----a-c-----
* @param {Number} period time to suppress events
* @returns {Stream} new stream that skips events for throttle period
*/
Stream.prototype.throttle = function(period) {
return limit.throttle(period, this);
};
/**
* Wait for a burst of events to subside and emit only the last event in the burst
* stream: abcd----abcd----
* debounce(2, stream): -----d-------d--
* @param {Number} period events occuring more frequently than this
* on the provided scheduler will be suppressed
* @returns {Stream} new debounced stream
*/
Stream.prototype.debounce = function(period) {
return limit.debounce(period, this);
};
//-----------------------------------------------------------------------
// Awaiting Promises
var promises = require('./lib/combinator/promises');
exports.fromPromise = promises.fromPromise;
exports.await = promises.awaitPromises;
/**
* Await promises, turning a Stream<Promise<X>> into Stream<X>. Preserves
* event order, but timeshifts events based on promise resolution time.
* @returns {Stream<X>} stream containing non-promise values
*/
Stream.prototype.await = function() {
return promises.awaitPromises(this);
};
//-----------------------------------------------------------------------
// Error handling
var errors = require('./lib/combinator/errors');
exports.recoverWith = errors.flatMapError;
exports.flatMapError = errors.flatMapError;
exports.throwError = errors.throwError;
/**
* If this stream encounters an error, recover and continue with items from stream
* returned by f.
* stream: -a-b-c-X-
* f(X): d-e-f-g-
* flatMapError(f, stream): -a-b-c-d-e-f-g-
* @param {function(error:*):Stream} f function which returns a new stream
* @returns {Stream} new stream which will recover from an error by calling f
*/
Stream.prototype.recoverWith = Stream.prototype.flatMapError = function(f) {
return errors.flatMapError(f, this);
};
//-----------------------------------------------------------------------
// Multicasting
var multicast = require('@most/multicast').default;
exports.multicast = multicast;
/**
* Transform the stream into multicast stream. That means that many subscribers
* to the stream will not cause multiple invocations of the internal machinery.
* @returns {Stream} new stream which will multicast events to all observers.
*/
Stream.prototype.multicast = function() {
return multicast(this);
};
},{"./lib/Stream":319,"./lib/combinator/accumulate":320,"./lib/combinator/applicative":321,"./lib/combinator/build":322,"./lib/combinator/combine":323,"./lib/combinator/concatMap":324,"./lib/combinator/continueWith":325,"./lib/combinator/delay":326,"./lib/combinator/errors":327,"./lib/combinator/filter":328,"./lib/combinator/flatMap":329,"./lib/combinator/limit":330,"./lib/combinator/loop":331,"./lib/combinator/merge":332,"./lib/combinator/mergeConcurrently":333,"./lib/combinator/observe":334,"./lib/combinator/promises":335,"./lib/combinator/sample":336,"./lib/combinator/slice":337,"./lib/combinator/switch":338,"./lib/combinator/thru":339,"./lib/combinator/timeslice":340,"./lib/combinator/timestamp":341,"./lib/combinator/transduce":342,"./lib/combinator/transform":343,"./lib/combinator/zip":344,"./lib/observable/subscribe":357,"./lib/source/core":370,"./lib/source/create":371,"./lib/source/from":372,"./lib/source/fromEvent":374,"./lib/source/generate":376,"./lib/source/iterate":377,"./lib/source/periodic":378,"./lib/source/unfold":380,"@most/multicast":3,"@most/prelude":4,"symbol-observable":384}],382:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],383:[function(require,module,exports){
// Ramda v0.21.0
// https://github.com/ramda/ramda
// (c) 2013-2016 Scott Sauyet, Michael Hurley, and David Chambers
// Ramda may be freely distributed under the MIT license.
;(function() {
'use strict';
/**
* A special placeholder value used to specify "gaps" within curried functions,
* allowing partial application of any combination of arguments, regardless of
* their positions.
*
* If `g` is a curried ternary function and `_` is `R.__`, the following are
* equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2, _)(1, 3)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @constant
* @memberOf R
* @since v0.6.0
* @category Function
* @example
*
* var greet = R.replace('{name}', R.__, 'Hello, {name}!');
* greet('Alice'); //=> 'Hello, Alice!'
*/
var __ = { '@@functional/placeholder': true };
/* eslint-disable no-unused-vars */
var _arity = function _arity(n, fn) {
/* eslint-disable no-unused-vars */
switch (n) {
case 0:
return function () {
return fn.apply(this, arguments);
};
case 1:
return function (a0) {
return fn.apply(this, arguments);
};
case 2:
return function (a0, a1) {
return fn.apply(this, arguments);
};
case 3:
return function (a0, a1, a2) {
return fn.apply(this, arguments);
};
case 4:
return function (a0, a1, a2, a3) {
return fn.apply(this, arguments);
};
case 5:
return function (a0, a1, a2, a3, a4) {
return fn.apply(this, arguments);
};
case 6:
return function (a0, a1, a2, a3, a4, a5) {
return fn.apply(this, arguments);
};
case 7:
return function (a0, a1, a2, a3, a4, a5, a6) {
return fn.apply(this, arguments);
};
case 8:
return function (a0, a1, a2, a3, a4, a5, a6, a7) {
return fn.apply(this, arguments);
};
case 9:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
return fn.apply(this, arguments);
};
case 10:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
return fn.apply(this, arguments);
};
default:
throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
}
};
var _arrayFromIterator = function _arrayFromIterator(iter) {
var list = [];
var next;
while (!(next = iter.next()).done) {
list.push(next.value);
}
return list;
};
var _arrayOf = function _arrayOf() {
return Array.prototype.slice.call(arguments);
};
var _cloneRegExp = function _cloneRegExp(pattern) {
return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : ''));
};
var _complement = function _complement(f) {
return function () {
return !f.apply(this, arguments);
};
};
/**
* Private `concat` function to merge two array-like objects.
*
* @private
* @param {Array|Arguments} [set1=[]] An array-like object.
* @param {Array|Arguments} [set2=[]] An array-like object.
* @return {Array} A new, merged array.
* @example
*
* _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
*/
var _concat = function _concat(set1, set2) {
set1 = set1 || [];
set2 = set2 || [];
var idx;
var len1 = set1.length;
var len2 = set2.length;
var result = [];
idx = 0;
while (idx < len1) {
result[result.length] = set1[idx];
idx += 1;
}
idx = 0;
while (idx < len2) {
result[result.length] = set2[idx];
idx += 1;
}
return result;
};
var _containsWith = function _containsWith(pred, x, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (pred(x, list[idx])) {
return true;
}
idx += 1;
}
return false;
};
var _filter = function _filter(fn, list) {
var idx = 0;
var len = list.length;
var result = [];
while (idx < len) {
if (fn(list[idx])) {
result[result.length] = list[idx];
}
idx += 1;
}
return result;
};
var _forceReduced = function _forceReduced(x) {
return {
'@@transducer/value': x,
'@@transducer/reduced': true
};
};
// String(x => x) evaluates to "x => x", so the pattern may not match.
var _functionName = function _functionName(f) {
// String(x => x) evaluates to "x => x", so the pattern may not match.
var match = String(f).match(/^function (\w*)/);
return match == null ? '' : match[1];
};
var _has = function _has(prop, obj) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
var _identity = function _identity(x) {
return x;
};
var _isArguments = function () {
var toString = Object.prototype.toString;
return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) {
return toString.call(x) === '[object Arguments]';
} : function _isArguments(x) {
return _has('callee', x);
};
}();
/**
* Tests whether or not an object is an array.
*
* @private
* @param {*} val The object to test.
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* _isArray([]); //=> true
* _isArray(null); //=> false
* _isArray({}); //=> false
*/
var _isArray = Array.isArray || function _isArray(val) {
return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';
};
var _isFunction = function _isNumber(x) {
return Object.prototype.toString.call(x) === '[object Function]';
};
/**
* Determine if the passed argument is an integer.
*
* @private
* @param {*} n
* @category Type
* @return {Boolean}
*/
var _isInteger = Number.isInteger || function _isInteger(n) {
return n << 0 === n;
};
var _isNumber = function _isNumber(x) {
return Object.prototype.toString.call(x) === '[object Number]';
};
var _isObject = function _isObject(x) {
return Object.prototype.toString.call(x) === '[object Object]';
};
var _isPlaceholder = function _isPlaceholder(a) {
return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true;
};
var _isRegExp = function _isRegExp(x) {
return Object.prototype.toString.call(x) === '[object RegExp]';
};
var _isString = function _isString(x) {
return Object.prototype.toString.call(x) === '[object String]';
};
var _isTransformer = function _isTransformer(obj) {
return typeof obj['@@transducer/step'] === 'function';
};
var _map = function _map(fn, functor) {
var idx = 0;
var len = functor.length;
var result = Array(len);
while (idx < len) {
result[idx] = fn(functor[idx]);
idx += 1;
}
return result;
};
// Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
var _objectAssign = function _objectAssign(target) {
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
var idx = 1;
var length = arguments.length;
while (idx < length) {
var source = arguments[idx];
if (source != null) {
for (var nextKey in source) {
if (_has(nextKey, source)) {
output[nextKey] = source[nextKey];
}
}
}
idx += 1;
}
return output;
};
var _of = function _of(x) {
return [x];
};
var _pipe = function _pipe(f, g) {
return function () {
return g.call(this, f.apply(this, arguments));
};
};
var _pipeP = function _pipeP(f, g) {
return function () {
var ctx = this;
return f.apply(ctx, arguments).then(function (x) {
return g.call(ctx, x);
});
};
};
// \b matches word boundary; [\b] matches backspace
var _quote = function _quote(s) {
var escaped = s.replace(/\\/g, '\\\\').replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace
.replace(/\f/g, '\\f').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/\v/g, '\\v').replace(/\0/g, '\\0');
return '"' + escaped.replace(/"/g, '\\"') + '"';
};
var _reduced = function _reduced(x) {
return x && x['@@transducer/reduced'] ? x : {
'@@transducer/value': x,
'@@transducer/reduced': true
};
};
/**
* An optimized, private array `slice` implementation.
*
* @private
* @param {Arguments|Array} args The array or arguments object to consider.
* @param {Number} [from=0] The array index to slice from, inclusive.
* @param {Number} [to=args.length] The array index to slice to, exclusive.
* @return {Array} A new, sliced array.
* @example
*
* _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3]
*
* var firstThreeArgs = function(a, b, c, d) {
* return _slice(arguments, 0, 3);
* };
* firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3]
*/
var _slice = function _slice(args, from, to) {
switch (arguments.length) {
case 1:
return _slice(args, 0, args.length);
case 2:
return _slice(args, from, args.length);
default:
var list = [];
var idx = 0;
var len = Math.max(0, Math.min(args.length, to) - from);
while (idx < len) {
list[idx] = args[from + idx];
idx += 1;
}
return list;
}
};
/**
* Polyfill from <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString>.
*/
var _toISOString = function () {
var pad = function pad(n) {
return (n < 10 ? '0' : '') + n;
};
return typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) {
return d.toISOString();
} : function _toISOString(d) {
return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
};
}();
var _xfBase = {
init: function () {
return this.xf['@@transducer/init']();
},
result: function (result) {
return this.xf['@@transducer/result'](result);
}
};
var _xwrap = function () {
function XWrap(fn) {
this.f = fn;
}
XWrap.prototype['@@transducer/init'] = function () {
throw new Error('init not implemented on XWrap');
};
XWrap.prototype['@@transducer/result'] = function (acc) {
return acc;
};
XWrap.prototype['@@transducer/step'] = function (acc, x) {
return this.f(acc, x);
};
return function _xwrap(fn) {
return new XWrap(fn);
};
}();
var _aperture = function _aperture(n, list) {
var idx = 0;
var limit = list.length - (n - 1);
var acc = new Array(limit >= 0 ? limit : 0);
while (idx < limit) {
acc[idx] = _slice(list, idx, idx + n);
idx += 1;
}
return acc;
};
var _assign = typeof Object.assign === 'function' ? Object.assign : _objectAssign;
/**
* Similar to hasMethod, this checks whether a function has a [methodname]
* function. If it isn't an array it will execute that function otherwise it
* will default to the ramda implementation.
*
* @private
* @param {Function} fn ramda implemtation
* @param {String} methodname property to check for a custom implementation
* @return {Object} Whatever the return value of the method is.
*/
var _checkForMethod = function _checkForMethod(methodname, fn) {
return function () {
var length = arguments.length;
if (length === 0) {
return fn();
}
var obj = arguments[length - 1];
return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, _slice(arguments, 0, length - 1));
};
};
/**
* Optimized internal one-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry1 = function _curry1(fn) {
return function f1(a) {
if (arguments.length === 0 || _isPlaceholder(a)) {
return f1;
} else {
return fn.apply(this, arguments);
}
};
};
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry2 = function _curry2(fn) {
return function f2(a, b) {
switch (arguments.length) {
case 0:
return f2;
case 1:
return _isPlaceholder(a) ? f2 : _curry1(function (_b) {
return fn(a, _b);
});
default:
return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {
return fn(_a, b);
}) : _isPlaceholder(b) ? _curry1(function (_b) {
return fn(a, _b);
}) : fn(a, b);
}
};
};
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curry3 = function _curry3(fn) {
return function f3(a, b, c) {
switch (arguments.length) {
case 0:
return f3;
case 1:
return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) {
return fn(a, _b, _c);
});
case 2:
return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) {
return fn(_a, b, _c);
}) : _isPlaceholder(b) ? _curry2(function (_b, _c) {
return fn(a, _b, _c);
}) : _curry1(function (_c) {
return fn(a, b, _c);
});
default:
return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) {
return fn(_a, _b, c);
}) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) {
return fn(_a, b, _c);
}) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) {
return fn(a, _b, _c);
}) : _isPlaceholder(a) ? _curry1(function (_a) {
return fn(_a, b, c);
}) : _isPlaceholder(b) ? _curry1(function (_b) {
return fn(a, _b, c);
}) : _isPlaceholder(c) ? _curry1(function (_c) {
return fn(a, b, _c);
}) : fn(a, b, c);
}
};
};
/**
* Internal curryN function.
*
* @private
* @category Function
* @param {Number} length The arity of the curried function.
* @param {Array} received An array of arguments received thus far.
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
var _curryN = function _curryN(length, received, fn) {
return function () {
var combined = [];
var argsIdx = 0;
var left = length;
var combinedIdx = 0;
while (combinedIdx < received.length || argsIdx < arguments.length) {
var result;
if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) {
result = received[combinedIdx];
} else {
result = arguments[argsIdx];
argsIdx += 1;
}
combined[combinedIdx] = result;
if (!_isPlaceholder(result)) {
left -= 1;
}
combinedIdx += 1;
}
return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn));
};
};
/**
* Returns a function that dispatches with different strategies based on the
* object in list position (last argument). If it is an array, executes [fn].
* Otherwise, if it has a function with [methodname], it will execute that
* function (functor case). Otherwise, if it is a transformer, uses transducer
* [xf] to return a new transformer (transducer case). Otherwise, it will
* default to executing [fn].
*
* @private
* @param {String} methodname property to check for a custom implementation
* @param {Function} xf transducer to initialize if object is transformer
* @param {Function} fn default ramda implementation
* @return {Function} A function that dispatches on object in list position
*/
var _dispatchable = function _dispatchable(methodname, xf, fn) {
return function () {
var length = arguments.length;
if (length === 0) {
return fn();
}
var obj = arguments[length - 1];
if (!_isArray(obj)) {
var args = _slice(arguments, 0, length - 1);
if (typeof obj[methodname] === 'function') {
return obj[methodname].apply(obj, args);
}
if (_isTransformer(obj)) {
var transducer = xf.apply(null, args);
return transducer(obj);
}
}
return fn.apply(this, arguments);
};
};
var _dropLastWhile = function dropLastWhile(pred, list) {
var idx = list.length - 1;
while (idx >= 0 && pred(list[idx])) {
idx -= 1;
}
return _slice(list, 0, idx + 1);
};
var _xall = function () {
function XAll(f, xf) {
this.xf = xf;
this.f = f;
this.all = true;
}
XAll.prototype['@@transducer/init'] = _xfBase.init;
XAll.prototype['@@transducer/result'] = function (result) {
if (this.all) {
result = this.xf['@@transducer/step'](result, true);
}
return this.xf['@@transducer/result'](result);
};
XAll.prototype['@@transducer/step'] = function (result, input) {
if (!this.f(input)) {
this.all = false;
result = _reduced(this.xf['@@transducer/step'](result, false));
}
return result;
};
return _curry2(function _xall(f, xf) {
return new XAll(f, xf);
});
}();
var _xany = function () {
function XAny(f, xf) {
this.xf = xf;
this.f = f;
this.any = false;
}
XAny.prototype['@@transducer/init'] = _xfBase.init;
XAny.prototype['@@transducer/result'] = function (result) {
if (!this.any) {
result = this.xf['@@transducer/step'](result, false);
}
return this.xf['@@transducer/result'](result);
};
XAny.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.any = true;
result = _reduced(this.xf['@@transducer/step'](result, true));
}
return result;
};
return _curry2(function _xany(f, xf) {
return new XAny(f, xf);
});
}();
var _xaperture = function () {
function XAperture(n, xf) {
this.xf = xf;
this.pos = 0;
this.full = false;
this.acc = new Array(n);
}
XAperture.prototype['@@transducer/init'] = _xfBase.init;
XAperture.prototype['@@transducer/result'] = function (result) {
this.acc = null;
return this.xf['@@transducer/result'](result);
};
XAperture.prototype['@@transducer/step'] = function (result, input) {
this.store(input);
return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result;
};
XAperture.prototype.store = function (input) {
this.acc[this.pos] = input;
this.pos += 1;
if (this.pos === this.acc.length) {
this.pos = 0;
this.full = true;
}
};
XAperture.prototype.getCopy = function () {
return _concat(_slice(this.acc, this.pos), _slice(this.acc, 0, this.pos));
};
return _curry2(function _xaperture(n, xf) {
return new XAperture(n, xf);
});
}();
var _xdrop = function () {
function XDrop(n, xf) {
this.xf = xf;
this.n = n;
}
XDrop.prototype['@@transducer/init'] = _xfBase.init;
XDrop.prototype['@@transducer/result'] = _xfBase.result;
XDrop.prototype['@@transducer/step'] = function (result, input) {
if (this.n > 0) {
this.n -= 1;
return result;
}
return this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdrop(n, xf) {
return new XDrop(n, xf);
});
}();
var _xdropLast = function () {
function XDropLast(n, xf) {
this.xf = xf;
this.pos = 0;
this.full = false;
this.acc = new Array(n);
}
XDropLast.prototype['@@transducer/init'] = _xfBase.init;
XDropLast.prototype['@@transducer/result'] = function (result) {
this.acc = null;
return this.xf['@@transducer/result'](result);
};
XDropLast.prototype['@@transducer/step'] = function (result, input) {
if (this.full) {
result = this.xf['@@transducer/step'](result, this.acc[this.pos]);
}
this.store(input);
return result;
};
XDropLast.prototype.store = function (input) {
this.acc[this.pos] = input;
this.pos += 1;
if (this.pos === this.acc.length) {
this.pos = 0;
this.full = true;
}
};
return _curry2(function _xdropLast(n, xf) {
return new XDropLast(n, xf);
});
}();
var _xdropRepeatsWith = function () {
function XDropRepeatsWith(pred, xf) {
this.xf = xf;
this.pred = pred;
this.lastValue = undefined;
this.seenFirstValue = false;
}
XDropRepeatsWith.prototype['@@transducer/init'] = function () {
return this.xf['@@transducer/init']();
};
XDropRepeatsWith.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](result);
};
XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) {
var sameAsLast = false;
if (!this.seenFirstValue) {
this.seenFirstValue = true;
} else if (this.pred(this.lastValue, input)) {
sameAsLast = true;
}
this.lastValue = input;
return sameAsLast ? result : this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdropRepeatsWith(pred, xf) {
return new XDropRepeatsWith(pred, xf);
});
}();
var _xdropWhile = function () {
function XDropWhile(f, xf) {
this.xf = xf;
this.f = f;
}
XDropWhile.prototype['@@transducer/init'] = _xfBase.init;
XDropWhile.prototype['@@transducer/result'] = _xfBase.result;
XDropWhile.prototype['@@transducer/step'] = function (result, input) {
if (this.f) {
if (this.f(input)) {
return result;
}
this.f = null;
}
return this.xf['@@transducer/step'](result, input);
};
return _curry2(function _xdropWhile(f, xf) {
return new XDropWhile(f, xf);
});
}();
var _xfilter = function () {
function XFilter(f, xf) {
this.xf = xf;
this.f = f;
}
XFilter.prototype['@@transducer/init'] = _xfBase.init;
XFilter.prototype['@@transducer/result'] = _xfBase.result;
XFilter.prototype['@@transducer/step'] = function (result, input) {
return this.f(input) ? this.xf['@@transducer/step'](result, input) : result;
};
return _curry2(function _xfilter(f, xf) {
return new XFilter(f, xf);
});
}();
var _xfind = function () {
function XFind(f, xf) {
this.xf = xf;
this.f = f;
this.found = false;
}
XFind.prototype['@@transducer/init'] = _xfBase.init;
XFind.prototype['@@transducer/result'] = function (result) {
if (!this.found) {
result = this.xf['@@transducer/step'](result, void 0);
}
return this.xf['@@transducer/result'](result);
};
XFind.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.found = true;
result = _reduced(this.xf['@@transducer/step'](result, input));
}
return result;
};
return _curry2(function _xfind(f, xf) {
return new XFind(f, xf);
});
}();
var _xfindIndex = function () {
function XFindIndex(f, xf) {
this.xf = xf;
this.f = f;
this.idx = -1;
this.found = false;
}
XFindIndex.prototype['@@transducer/init'] = _xfBase.init;
XFindIndex.prototype['@@transducer/result'] = function (result) {
if (!this.found) {
result = this.xf['@@transducer/step'](result, -1);
}
return this.xf['@@transducer/result'](result);
};
XFindIndex.prototype['@@transducer/step'] = function (result, input) {
this.idx += 1;
if (this.f(input)) {
this.found = true;
result = _reduced(this.xf['@@transducer/step'](result, this.idx));
}
return result;
};
return _curry2(function _xfindIndex(f, xf) {
return new XFindIndex(f, xf);
});
}();
var _xfindLast = function () {
function XFindLast(f, xf) {
this.xf = xf;
this.f = f;
}
XFindLast.prototype['@@transducer/init'] = _xfBase.init;
XFindLast.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last));
};
XFindLast.prototype['@@transducer/step'] = function (result, input) {
if (this.f(input)) {
this.last = input;
}
return result;
};
return _curry2(function _xfindLast(f, xf) {
return new XFindLast(f, xf);
});
}();
var _xfindLastIndex = function () {
function XFindLastIndex(f, xf) {
this.xf = xf;
this.f = f;
this.idx = -1;
this.lastIdx = -1;
}
XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init;
XFindLastIndex.prototype['@@transducer/result'] = function (result) {
return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx));
};
XFindLastIndex.prototype['@@transducer/step'] = function (result, input) {
this.idx += 1;
if (this.f(input)) {
this.lastIdx = this.idx;
}
return result;
};
return _curry2(function _xfindLastIndex(f, xf) {
return new XFindLastIndex(f, xf);
});
}();
var _xmap = function () {
function XMap(f, xf) {
this.xf = xf;
this.f = f;
}
XMap.prototype['@@transducer/init'] = _xfBase.init;
XMap.prototype['@@transducer/result'] = _xfBase.result;
XMap.prototype['@@transducer/step'] = function (result, input) {
return this.xf['@@transducer/step'](result, this.f(input));
};
return _curry2(function _xmap(f, xf) {
return new XMap(f, xf);
});
}();
var _xtake = function () {
function XTake(n, xf) {
this.xf = xf;
this.n = n;
}
XTake.prototype['@@transducer/init'] = _xfBase.init;
XTake.prototype['@@transducer/result'] = _xfBase.result;
XTake.prototype['@@transducer/step'] = function (result, input) {
if (this.n === 0) {
return _reduced(result);
} else {
this.n -= 1;
return this.xf['@@transducer/step'](result, input);
}
};
return _curry2(function _xtake(n, xf) {
return new XTake(n, xf);
});
}();
var _xtakeWhile = function () {
function XTakeWhile(f, xf) {
this.xf = xf;
this.f = f;
}
XTakeWhile.prototype['@@transducer/init'] = _xfBase.init;
XTakeWhile.prototype['@@transducer/result'] = _xfBase.result;
XTakeWhile.prototype['@@transducer/step'] = function (result, input) {
return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result);
};
return _curry2(function _xtakeWhile(f, xf) {
return new XTakeWhile(f, xf);
});
}();
/**
* Adds two values.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a
* @param {Number} b
* @return {Number}
* @see R.subtract
* @example
*
* R.add(2, 3); //=> 5
* R.add(7)(10); //=> 17
*/
var add = _curry2(function add(a, b) {
return Number(a) + Number(b);
});
/**
* Applies a function to the value at the given index of an array, returning a
* new copy of the array with the element at the given index replaced with the
* result of the function application.
*
* @func
* @memberOf R
* @since v0.14.0
* @category List
* @sig (a -> a) -> Number -> [a] -> [a]
* @param {Function} fn The function to apply.
* @param {Number} idx The index.
* @param {Array|Arguments} list An array-like object whose value
* at the supplied index will be replaced.
* @return {Array} A copy of the supplied array-like object with
* the element at index `idx` replaced with the value
* returned by applying `fn` to the existing element.
* @see R.update
* @example
*
* R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2]
* R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2]
*/
var adjust = _curry3(function adjust(fn, idx, list) {
if (idx >= list.length || idx < -list.length) {
return list;
}
var start = idx < 0 ? list.length : 0;
var _idx = start + idx;
var _list = _concat(list);
_list[_idx] = fn(list[_idx]);
return _list;
});
/**
* Returns `true` if all elements of the list match the predicate, `false` if
* there are any that don't.
*
* Dispatches to the `all` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is satisfied by every element, `false`
* otherwise.
* @see R.any, R.none, R.transduce
* @example
*
* var lessThan2 = R.flip(R.lt)(2);
* var lessThan3 = R.flip(R.lt)(3);
* R.all(lessThan2)([1, 2]); //=> false
* R.all(lessThan3)([1, 2]); //=> true
*/
var all = _curry2(_dispatchable('all', _xall, function all(fn, list) {
var idx = 0;
while (idx < list.length) {
if (!fn(list[idx])) {
return false;
}
idx += 1;
}
return true;
}));
/**
* Returns a function that always returns the given value. Note that for
* non-primitives the value returned is a reference to the original value.
*
* This function is known as `const`, `constant`, or `K` (for K combinator) in
* other languages and libraries.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig a -> (* -> a)
* @param {*} val The value to wrap in a function
* @return {Function} A Function :: * -> val.
* @example
*
* var t = R.always('Tee');
* t(); //=> 'Tee'
*/
var always = _curry1(function always(val) {
return function () {
return val;
};
});
/**
* Returns `true` if both arguments are `true`; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Logic
* @sig * -> * -> *
* @param {Boolean} a A boolean value
* @param {Boolean} b A boolean value
* @return {Boolean} `true` if both arguments are `true`, `false` otherwise
* @see R.both
* @example
*
* R.and(true, true); //=> true
* R.and(true, false); //=> false
* R.and(false, true); //=> false
* R.and(false, false); //=> false
*/
var and = _curry2(function and(a, b) {
return a && b;
});
/**
* Returns `true` if at least one of elements of the list match the predicate,
* `false` otherwise.
*
* Dispatches to the `any` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is satisfied by at least one element, `false`
* otherwise.
* @see R.all, R.none, R.transduce
* @example
*
* var lessThan0 = R.flip(R.lt)(0);
* var lessThan2 = R.flip(R.lt)(2);
* R.any(lessThan0)([1, 2]); //=> false
* R.any(lessThan2)([1, 2]); //=> true
*/
var any = _curry2(_dispatchable('any', _xany, function any(fn, list) {
var idx = 0;
while (idx < list.length) {
if (fn(list[idx])) {
return true;
}
idx += 1;
}
return false;
}));
/**
* Returns a new list, composed of n-tuples of consecutive elements If `n` is
* greater than the length of the list, an empty list is returned.
*
* Dispatches to the `aperture` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.12.0
* @category List
* @sig Number -> [a] -> [[a]]
* @param {Number} n The size of the tuples to create
* @param {Array} list The list to split into `n`-tuples
* @return {Array} The new list.
* @see R.transduce
* @example
*
* R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]]
* R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
* R.aperture(7, [1, 2, 3, 4, 5]); //=> []
*/
var aperture = _curry2(_dispatchable('aperture', _xaperture, _aperture));
/**
* Returns a new list containing the contents of the given list, followed by
* the given element.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig a -> [a] -> [a]
* @param {*} el The element to add to the end of the new list.
* @param {Array} list The list whose contents will be added to the beginning of the output
* list.
* @return {Array} A new list containing the contents of the old list followed by `el`.
* @see R.prepend
* @example
*
* R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests']
* R.append('tests', []); //=> ['tests']
* R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']]
*/
var append = _curry2(function append(el, list) {
return _concat(list, [el]);
});
/**
* Applies function `fn` to the argument list `args`. This is useful for
* creating a fixed-arity function from a variadic function. `fn` should be a
* bound function if context is significant.
*
* @func
* @memberOf R
* @since v0.7.0
* @category Function
* @sig (*... -> a) -> [*] -> a
* @param {Function} fn
* @param {Array} args
* @return {*}
* @see R.call, R.unapply
* @example
*
* var nums = [1, 2, 3, -99, 42, 6, 7];
* R.apply(Math.max, nums); //=> 42
*/
var apply = _curry2(function apply(fn, args) {
return fn.apply(this, args);
});
/**
* Makes a shallow clone of an object, setting or overriding the specified
* property with the given value. Note that this copies and flattens prototype
* properties onto the new object as well. All non-primitive properties are
* copied by reference.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Object
* @sig String -> a -> {k: v} -> {k: v}
* @param {String} prop the property name to set
* @param {*} val the new value
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original except for the specified property.
* @see R.dissoc
* @example
*
* R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}
*/
var assoc = _curry3(function assoc(prop, val, obj) {
var result = {};
for (var p in obj) {
result[p] = obj[p];
}
result[prop] = val;
return result;
});
/**
* Makes a shallow clone of an object, setting or overriding the nodes required
* to create the given path, and placing the specific value at the tail end of
* that path. Note that this copies and flattens prototype properties onto the
* new object as well. All non-primitive properties are copied by reference.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Object
* @sig [String] -> a -> {k: v} -> {k: v}
* @param {Array} path the path to set
* @param {*} val the new value
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original except along the specified path.
* @see R.dissocPath
* @example
*
* R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
*/
var assocPath = _curry3(function assocPath(path, val, obj) {
switch (path.length) {
case 0:
return val;
case 1:
return assoc(path[0], val, obj);
default:
return assoc(path[0], assocPath(_slice(path, 1), val, Object(obj[path[0]])), obj);
}
});
/**
* Creates a function that is bound to a context.
* Note: `R.bind` does not provide the additional argument-binding capabilities of
* [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
*
* @func
* @memberOf R
* @since v0.6.0
* @category Function
* @category Object
* @sig (* -> *) -> {*} -> (* -> *)
* @param {Function} fn The function to bind to context
* @param {Object} thisObj The context to bind `fn` to
* @return {Function} A function that will execute in the context of `thisObj`.
* @see R.partial
*/
var bind = _curry2(function bind(fn, thisObj) {
return _arity(fn.length, function () {
return fn.apply(thisObj, arguments);
});
});
/**
* Restricts a number to be within a range.
*
* Also works for other ordered types such as Strings and Dates.
*
* @func
* @memberOf R
* @since v0.20.0
* @category Relation
* @sig Ord a => a -> a -> a -> a
* @param {Number} minimum number
* @param {Number} maximum number
* @param {Number} value to be clamped
* @return {Number} Returns the clamped value
* @example
*
* R.clamp(1, 10, -1) // => 1
* R.clamp(1, 10, 11) // => 10
* R.clamp(1, 10, 4) // => 4
*/
var clamp = _curry3(function clamp(min, max, value) {
if (min > max) {
throw new Error('min must not be greater than max in clamp(min, max, value)');
}
return value < min ? min : value > max ? max : value;
});
/**
* Makes a comparator function out of a function that reports whether the first
* element is less than the second.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a, b -> Boolean) -> (a, b -> Number)
* @param {Function} pred A predicate function of arity two.
* @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`.
* @example
*
* var cmp = R.comparator((a, b) => a.age < b.age);
* var people = [
* // ...
* ];
* R.sort(cmp, people);
*/
var comparator = _curry1(function comparator(pred) {
return function (a, b) {
return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;
};
});
/**
* Returns a curried equivalent of the provided function, with the specified
* arity. The curried function has two unusual capabilities. First, its
* arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the
* following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value `R.__` may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is `R.__`, the
* following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @since v0.5.0
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curry
* @example
*
* var sumArgs = (...args) => R.sum(args);
*
* var curriedAddFourNumbers = R.curryN(4, sumArgs);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4); //=> 10
*/
var curryN = _curry2(function curryN(length, fn) {
if (length === 1) {
return _curry1(fn);
}
return _arity(length, _curryN(length, [], fn));
});
/**
* Decrements its argument.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @see R.inc
* @example
*
* R.dec(42); //=> 41
*/
var dec = add(-1);
/**
* Returns the second argument if it is not `null`, `undefined` or `NaN`
* otherwise the first argument is returned.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Logic
* @sig a -> b -> a | b
* @param {a} val The default value.
* @param {b} val The value to return if it is not null or undefined
* @return {*} The the second value or the default value
* @example
*
* var defaultTo42 = R.defaultTo(42);
*
* defaultTo42(null); //=> 42
* defaultTo42(undefined); //=> 42
* defaultTo42('Ramda'); //=> 'Ramda'
* defaultTo42(parseInt('string')); //=> 42
*/
var defaultTo = _curry2(function defaultTo(d, v) {
return v == null || v !== v ? d : v;
});
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not
* contained in the second list. Duplication is determined according to the
* value returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig (a -> a -> Boolean) -> [*] -> [*] -> [*]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` that are not in `list2`.
* @see R.difference
* @example
*
* var cmp = (x, y) => x.a === y.a;
* var l1 = [{a: 1}, {a: 2}, {a: 3}];
* var l2 = [{a: 3}, {a: 4}];
* R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]
*/
var differenceWith = _curry3(function differenceWith(pred, first, second) {
var out = [];
var idx = 0;
var firstLen = first.length;
while (idx < firstLen) {
if (!_containsWith(pred, first[idx], second) && !_containsWith(pred, first[idx], out)) {
out.push(first[idx]);
}
idx += 1;
}
return out;
});
/**
* Returns a new object that does not contain a `prop` property.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Object
* @sig String -> {k: v} -> {k: v}
* @param {String} prop the name of the property to dissociate
* @param {Object} obj the object to clone
* @return {Object} a new object similar to the original but without the specified property
* @see R.assoc
* @example
*
* R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3}
*/
var dissoc = _curry2(function dissoc(prop, obj) {
var result = {};
for (var p in obj) {
if (p !== prop) {
result[p] = obj[p];
}
}
return result;
});
/**
* Makes a shallow clone of an object, omitting the property at the given path.
* Note that this copies and flattens prototype properties onto the new object
* as well. All non-primitive properties are copied by reference.
*
* @func
* @memberOf R
* @since v0.11.0
* @category Object
* @sig [String] -> {k: v} -> {k: v}
* @param {Array} path the path to set
* @param {Object} obj the object to clone
* @return {Object} a new object without the property at path
* @see R.assocPath
* @example
*
* R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
*/
var dissocPath = _curry2(function dissocPath(path, obj) {
switch (path.length) {
case 0:
return obj;
case 1:
return dissoc(path[0], obj);
default:
var head = path[0];
var tail = _slice(path, 1);
return obj[head] == null ? obj : assoc(head, dissocPath(tail, obj[head]), obj);
}
});
/**
* Divides two numbers. Equivalent to `a / b`.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a / b`.
* @see R.multiply
* @example
*
* R.divide(71, 100); //=> 0.71
*
* var half = R.divide(R.__, 2);
* half(42); //=> 21
*
* var reciprocal = R.divide(1);
* reciprocal(4); //=> 0.25
*/
var divide = _curry2(function divide(a, b) {
return a / b;
});
/**
* Returns a new list containing the last `n` elements of a given list, passing
* each value to the supplied predicate function, skipping elements while the
* predicate function returns `true`. The predicate function is passed one
* argument: *(value)*.
*
* Dispatches to the `dropWhile` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.9.0
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.takeWhile, R.transduce, R.addIndex
* @example
*
* var lteTwo = x => x <= 2;
*
* R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1]
*/
var dropWhile = _curry2(_dispatchable('dropWhile', _xdropWhile, function dropWhile(pred, list) {
var idx = 0;
var len = list.length;
while (idx < len && pred(list[idx])) {
idx += 1;
}
return _slice(list, idx);
}));
/**
* Returns the empty value of its argument's type. Ramda defines the empty
* value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other
* types are supported if they define `<Type>.empty` and/or
* `<Type>.prototype.empty`.
*
* Dispatches to the `empty` method of the first argument, if present.
*
* @func
* @memberOf R
* @since v0.3.0
* @category Function
* @sig a -> a
* @param {*} x
* @return {*}
* @example
*
* R.empty(Just(42)); //=> Nothing()
* R.empty([1, 2, 3]); //=> []
* R.empty('unicorns'); //=> ''
* R.empty({x: 1, y: 2}); //=> {}
*/
// else
var empty = _curry1(function empty(x) {
return x != null && typeof x.empty === 'function' ? x.empty() : x != null && x.constructor != null && typeof x.constructor.empty === 'function' ? x.constructor.empty() : _isArray(x) ? [] : _isString(x) ? '' : _isObject(x) ? {} : _isArguments(x) ? function () {
return arguments;
}() : // else
void 0;
});
/**
* Creates a new object by recursively evolving a shallow copy of `object`,
* according to the `transformation` functions. All non-primitive properties
* are copied by reference.
*
* A `transformation` function will not be invoked if its corresponding key
* does not exist in the evolved object.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Object
* @sig {k: (v -> v)} -> {k: v} -> {k: v}
* @param {Object} transformations The object specifying transformation functions to apply
* to the object.
* @param {Object} object The object to be transformed.
* @return {Object} The transformed object.
* @example
*
* var tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};
* var transformations = {
* firstName: R.trim,
* lastName: R.trim, // Will not get invoked.
* data: {elapsed: R.add(1), remaining: R.add(-1)}
* };
* R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123}
*/
var evolve = _curry2(function evolve(transformations, object) {
var result = {};
var transformation, key, type;
for (key in object) {
transformation = transformations[key];
type = typeof transformation;
result[key] = type === 'function' ? transformation(object[key]) : type === 'object' ? evolve(transformations[key], object[key]) : object[key];
}
return result;
});
/**
* Returns the first element of the list which matches the predicate, or
* `undefined` if no element matches.
*
* Dispatches to the `find` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @see R.transduce
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.find(R.propEq('a', 2))(xs); //=> {a: 2}
* R.find(R.propEq('a', 4))(xs); //=> undefined
*/
var find = _curry2(_dispatchable('find', _xfind, function find(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (fn(list[idx])) {
return list[idx];
}
idx += 1;
}
}));
/**
* Returns the index of the first element of the list which matches the
* predicate, or `-1` if no element matches.
*
* Dispatches to the `findIndex` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @see R.transduce
* @example
*
* var xs = [{a: 1}, {a: 2}, {a: 3}];
* R.findIndex(R.propEq('a', 2))(xs); //=> 1
* R.findIndex(R.propEq('a', 4))(xs); //=> -1
*/
var findIndex = _curry2(_dispatchable('findIndex', _xfindIndex, function findIndex(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
if (fn(list[idx])) {
return idx;
}
idx += 1;
}
return -1;
}));
/**
* Returns the last element of the list which matches the predicate, or
* `undefined` if no element matches.
*
* Dispatches to the `findLast` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig (a -> Boolean) -> [a] -> a | undefined
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Object} The element found, or `undefined`.
* @see R.transduce
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1}
* R.findLast(R.propEq('a', 4))(xs); //=> undefined
*/
var findLast = _curry2(_dispatchable('findLast', _xfindLast, function findLast(fn, list) {
var idx = list.length - 1;
while (idx >= 0) {
if (fn(list[idx])) {
return list[idx];
}
idx -= 1;
}
}));
/**
* Returns the index of the last element of the list which matches the
* predicate, or `-1` if no element matches.
*
* Dispatches to the `findLastIndex` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig (a -> Boolean) -> [a] -> Number
* @param {Function} fn The predicate function used to determine if the element is the
* desired one.
* @param {Array} list The array to consider.
* @return {Number} The index of the element found, or `-1`.
* @see R.transduce
* @example
*
* var xs = [{a: 1, b: 0}, {a:1, b: 1}];
* R.findLastIndex(R.propEq('a', 1))(xs); //=> 1
* R.findLastIndex(R.propEq('a', 4))(xs); //=> -1
*/
var findLastIndex = _curry2(_dispatchable('findLastIndex', _xfindLastIndex, function findLastIndex(fn, list) {
var idx = list.length - 1;
while (idx >= 0) {
if (fn(list[idx])) {
return idx;
}
idx -= 1;
}
return -1;
}));
/**
* Iterate over an input `list`, calling a provided function `fn` for each
* element in the list.
*
* `fn` receives one argument: *(value)*.
*
* Note: `R.forEach` does not skip deleted or unassigned indices (sparse
* arrays), unlike the native `Array.prototype.forEach` method. For more
* details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description
*
* Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns
* the original array. In some libraries this function is named `each`.
*
* Dispatches to the `forEach` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig (a -> *) -> [a] -> [a]
* @param {Function} fn The function to invoke. Receives one argument, `value`.
* @param {Array} list The list to iterate over.
* @return {Array} The original list.
* @see R.addIndex
* @example
*
* var printXPlusFive = x => console.log(x + 5);
* R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]
* //-> 6
* //-> 7
* //-> 8
*/
var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) {
var len = list.length;
var idx = 0;
while (idx < len) {
fn(list[idx]);
idx += 1;
}
return list;
}));
/**
* Creates a new object out of a list key-value pairs.
*
* @func
* @memberOf R
* @since v0.3.0
* @category List
* @sig [[k,v]] -> {k: v}
* @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object.
* @return {Object} The object made by pairing up `keys` and `values`.
* @see R.toPairs, R.pair
* @example
*
* R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
*/
var fromPairs = _curry1(function fromPairs(pairs) {
var idx = 0;
var len = pairs.length;
var out = {};
while (idx < len) {
if (_isArray(pairs[idx]) && pairs[idx].length) {
out[pairs[idx][0]] = pairs[idx][1];
}
idx += 1;
}
return out;
});
/**
* Takes a list and returns a list of lists where each sublist's elements are
* all "equal" according to the provided equality function.
*
* @func
* @memberOf R
* @since v0.21.0
* @category List
* @sig (a, a -> Boolean) -> [a] -> [[a]]
* @param {Function} fn Function for determining whether two given (adjacent)
* elements should be in the same group
* @param {Array} list The array to group. Also accepts a string, which will be
* treated as a list of characters.
* @return {List} A list that contains sublists of equal elements,
* whose concatenations is equal to the original list.
* @example
*
* groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])
* // [[0], [1, 1], [2, 3, 5, 8, 13, 21]]
*
* groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])
* // [[0], [1, 1], [2], [3, 5], [8], [13, 21]]
*
* R.groupWith(R.eqBy(isVowel), 'aestiou')
* // ['ae', 'st', 'iou']
*/
var groupWith = _curry2(function (fn, list) {
var res = [];
var idx = 0;
var len = list.length;
while (idx < len) {
var nextidx = idx + 1;
while (nextidx < len && fn(list[idx], list[nextidx])) {
nextidx += 1;
}
res.push(list.slice(idx, nextidx));
idx = nextidx;
}
return res;
});
/**
* Returns `true` if the first argument is greater than the second; `false`
* otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @see R.lt
* @example
*
* R.gt(2, 1); //=> true
* R.gt(2, 2); //=> false
* R.gt(2, 3); //=> false
* R.gt('a', 'z'); //=> false
* R.gt('z', 'a'); //=> true
*/
var gt = _curry2(function gt(a, b) {
return a > b;
});
/**
* Returns `true` if the first argument is greater than or equal to the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean}
* @see R.lte
* @example
*
* R.gte(2, 1); //=> true
* R.gte(2, 2); //=> true
* R.gte(2, 3); //=> false
* R.gte('a', 'z'); //=> false
* R.gte('z', 'a'); //=> true
*/
var gte = _curry2(function gte(a, b) {
return a >= b;
});
/**
* Returns whether or not an object has an own property with the specified name
*
* @func
* @memberOf R
* @since v0.7.0
* @category Object
* @sig s -> {s: x} -> Boolean
* @param {String} prop The name of the property to check for.
* @param {Object} obj The object to query.
* @return {Boolean} Whether the property exists.
* @example
*
* var hasName = R.has('name');
* hasName({name: 'alice'}); //=> true
* hasName({name: 'bob'}); //=> true
* hasName({}); //=> false
*
* var point = {x: 0, y: 0};
* var pointHas = R.has(R.__, point);
* pointHas('x'); //=> true
* pointHas('y'); //=> true
* pointHas('z'); //=> false
*/
var has = _curry2(_has);
/**
* Returns whether or not an object or its prototype chain has a property with
* the specified name
*
* @func
* @memberOf R
* @since v0.7.0
* @category Object
* @sig s -> {s: x} -> Boolean
* @param {String} prop The name of the property to check for.
* @param {Object} obj The object to query.
* @return {Boolean} Whether the property exists.
* @example
*
* function Rectangle(width, height) {
* this.width = width;
* this.height = height;
* }
* Rectangle.prototype.area = function() {
* return this.width * this.height;
* };
*
* var square = new Rectangle(2, 2);
* R.hasIn('width', square); //=> true
* R.hasIn('area', square); //=> true
*/
var hasIn = _curry2(function hasIn(prop, obj) {
return prop in obj;
});
/**
* Returns true if its arguments are identical, false otherwise. Values are
* identical if they reference the same memory. `NaN` is identical to `NaN`;
* `0` and `-0` are not identical.
*
* @func
* @memberOf R
* @since v0.15.0
* @category Relation
* @sig a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.identical(o, o); //=> true
* R.identical(1, 1); //=> true
* R.identical(1, '1'); //=> false
* R.identical([], []); //=> false
* R.identical(0, -0); //=> false
* R.identical(NaN, NaN); //=> true
*/
// SameValue algorithm
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
// Step 6.a: NaN == NaN
var identical = _curry2(function identical(a, b) {
// SameValue algorithm
if (a === b) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return a !== 0 || 1 / a === 1 / b;
} else {
// Step 6.a: NaN == NaN
return a !== a && b !== b;
}
});
/**
* A function that does nothing but return the parameter supplied to it. Good
* as a default or placeholder function.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig a -> a
* @param {*} x The value to return.
* @return {*} The input value, `x`.
* @example
*
* R.identity(1); //=> 1
*
* var obj = {};
* R.identity(obj) === obj; //=> true
*/
var identity = _curry1(_identity);
/**
* Creates a function that will process either the `onTrue` or the `onFalse`
* function depending upon the result of the `condition` predicate.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Logic
* @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *)
* @param {Function} condition A predicate function
* @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value.
* @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value.
* @return {Function} A new unary function that will process either the `onTrue` or the `onFalse`
* function depending upon the result of the `condition` predicate.
* @see R.unless, R.when
* @example
*
* var incCount = R.ifElse(
* R.has('count'),
* R.over(R.lensProp('count'), R.inc),
* R.assoc('count', 1)
* );
* incCount({}); //=> { count: 1 }
* incCount({ count: 1 }); //=> { count: 2 }
*/
var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) {
return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() {
return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments);
});
});
/**
* Increments its argument.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @see R.dec
* @example
*
* R.inc(42); //=> 43
*/
var inc = add(1);
/**
* Inserts the supplied element into the list, at index `index`. _Note that
* this is not destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @since v0.2.2
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} index The position to insert the element
* @param {*} elt The element to insert into the Array
* @param {Array} list The list to insert into
* @return {Array} A new Array with `elt` inserted at `index`.
* @example
*
* R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4]
*/
var insert = _curry3(function insert(idx, elt, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
var result = _slice(list);
result.splice(idx, 0, elt);
return result;
});
/**
* Inserts the sub-list into the list, at index `index`. _Note that this is not
* destructive_: it returns a copy of the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @since v0.9.0
* @category List
* @sig Number -> [a] -> [a] -> [a]
* @param {Number} index The position to insert the sub-list
* @param {Array} elts The sub-list to insert into the Array
* @param {Array} list The list to insert the sub-list into
* @return {Array} A new Array with `elts` inserted starting at `index`.
* @example
*
* R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4]
*/
var insertAll = _curry3(function insertAll(idx, elts, list) {
idx = idx < list.length && idx >= 0 ? idx : list.length;
return _concat(_concat(_slice(list, 0, idx), elts), _slice(list, idx));
});
/**
* Creates a new list with the separator interposed between elements.
*
* Dispatches to the `intersperse` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.14.0
* @category List
* @sig a -> [a] -> [a]
* @param {*} separator The element to add to the list.
* @param {Array} list The list to be interposed.
* @return {Array} The new list.
* @example
*
* R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a']
*/
var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) {
var out = [];
var idx = 0;
var length = list.length;
while (idx < length) {
if (idx === length - 1) {
out.push(list[idx]);
} else {
out.push(list[idx], separator);
}
idx += 1;
}
return out;
}));
/**
* See if an object (`val`) is an instance of the supplied constructor. This
* function will check up the inheritance chain, if any.
*
* @func
* @memberOf R
* @since v0.3.0
* @category Type
* @sig (* -> {*}) -> a -> Boolean
* @param {Object} ctor A constructor
* @param {*} val The value to test
* @return {Boolean}
* @example
*
* R.is(Object, {}); //=> true
* R.is(Number, 1); //=> true
* R.is(Object, 1); //=> false
* R.is(String, 's'); //=> true
* R.is(String, new String('')); //=> true
* R.is(Object, new String('')); //=> true
* R.is(Object, 's'); //=> false
* R.is(Number, {}); //=> false
*/
var is = _curry2(function is(Ctor, val) {
return val != null && val.constructor === Ctor || val instanceof Ctor;
});
/**
* Tests whether or not an object is similar to an array.
*
* @func
* @memberOf R
* @since v0.5.0
* @category Type
* @category List
* @sig * -> Boolean
* @param {*} x The object to test.
* @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
* @example
*
* R.isArrayLike([]); //=> true
* R.isArrayLike(true); //=> false
* R.isArrayLike({}); //=> false
* R.isArrayLike({length: 10}); //=> false
* R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
*/
var isArrayLike = _curry1(function isArrayLike(x) {
if (_isArray(x)) {
return true;
}
if (!x) {
return false;
}
if (typeof x !== 'object') {
return false;
}
if (x instanceof String) {
return false;
}
if (x.nodeType === 1) {
return !!x.length;
}
if (x.length === 0) {
return true;
}
if (x.length > 0) {
return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
}
return false;
});
/**
* Checks if the input value is `null` or `undefined`.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Type
* @sig * -> Boolean
* @param {*} x The value to test.
* @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`.
* @example
*
* R.isNil(null); //=> true
* R.isNil(undefined); //=> true
* R.isNil(0); //=> false
* R.isNil([]); //=> false
*/
var isNil = _curry1(function isNil(x) {
return x == null;
});
/**
* Returns a list containing the names of all the enumerable own properties of
* the supplied object.
* Note that the order of the output array is not guaranteed to be consistent
* across different JS platforms.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own properties.
* @example
*
* R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']
*/
// cover IE < 9 keys issues
// Safari bug
var keys = function () {
// cover IE < 9 keys issues
var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
var nonEnumerableProps = [
'constructor',
'valueOf',
'isPrototypeOf',
'toString',
'propertyIsEnumerable',
'hasOwnProperty',
'toLocaleString'
];
// Safari bug
var hasArgsEnumBug = function () {
'use strict';
return arguments.propertyIsEnumerable('length');
}();
var contains = function contains(list, item) {
var idx = 0;
while (idx < list.length) {
if (list[idx] === item) {
return true;
}
idx += 1;
}
return false;
};
return typeof Object.keys === 'function' && !hasArgsEnumBug ? _curry1(function keys(obj) {
return Object(obj) !== obj ? [] : Object.keys(obj);
}) : _curry1(function keys(obj) {
if (Object(obj) !== obj) {
return [];
}
var prop, nIdx;
var ks = [];
var checkArgsLength = hasArgsEnumBug && _isArguments(obj);
for (prop in obj) {
if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) {
ks[ks.length] = prop;
}
}
if (hasEnumBug) {
nIdx = nonEnumerableProps.length - 1;
while (nIdx >= 0) {
prop = nonEnumerableProps[nIdx];
if (_has(prop, obj) && !contains(ks, prop)) {
ks[ks.length] = prop;
}
nIdx -= 1;
}
}
return ks;
});
}();
/**
* Returns a list containing the names of all the properties of the supplied
* object, including prototype properties.
* Note that the order of the output array is not guaranteed to be consistent
* across different JS platforms.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Object
* @sig {k: v} -> [k]
* @param {Object} obj The object to extract properties from
* @return {Array} An array of the object's own and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.keysIn(f); //=> ['x', 'y']
*/
var keysIn = _curry1(function keysIn(obj) {
var prop;
var ks = [];
for (prop in obj) {
ks[ks.length] = prop;
}
return ks;
});
/**
* Returns the number of elements in the array by returning `list.length`.
*
* @func
* @memberOf R
* @since v0.3.0
* @category List
* @sig [a] -> Number
* @param {Array} list The array to inspect.
* @return {Number} The length of the array.
* @example
*
* R.length([]); //=> 0
* R.length([1, 2, 3]); //=> 3
*/
var length = _curry1(function length(list) {
return list != null && is(Number, list.length) ? list.length : NaN;
});
/**
* Returns `true` if the first argument is less than the second; `false`
* otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @see R.gt
* @example
*
* R.lt(2, 1); //=> false
* R.lt(2, 2); //=> false
* R.lt(2, 3); //=> true
* R.lt('a', 'z'); //=> true
* R.lt('z', 'a'); //=> false
*/
var lt = _curry2(function lt(a, b) {
return a < b;
});
/**
* Returns `true` if the first argument is less than or equal to the second;
* `false` otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> Boolean
* @param {Number} a
* @param {Number} b
* @return {Boolean}
* @see R.gte
* @example
*
* R.lte(2, 1); //=> false
* R.lte(2, 2); //=> true
* R.lte(2, 3); //=> true
* R.lte('a', 'z'); //=> true
* R.lte('z', 'a'); //=> false
*/
var lte = _curry2(function lte(a, b) {
return a <= b;
});
/**
* The mapAccum function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from left to right, and returning a final value of this
* accumulator together with the new list.
*
* The iterator function receives two arguments, *acc* and *value*, and should
* return a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.addIndex
* @example
*
* var digits = ['1', '2', '3', '4'];
* var appender = (a, b) => [a + b, a + b];
*
* R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
*/
var mapAccum = _curry3(function mapAccum(fn, acc, list) {
var idx = 0;
var len = list.length;
var result = [];
var tuple = [acc];
while (idx < len) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx += 1;
}
return [
tuple[0],
result
];
});
/**
* The mapAccumRight function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from right to left, and returning a final value of this
* accumulator together with the new list.
*
* Similar to `mapAccum`, except moves through the input list from the right to
* the left.
*
* The iterator function receives two arguments, *acc* and *value*, and should
* return a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.addIndex
* @example
*
* var digits = ['1', '2', '3', '4'];
* var append = (a, b) => [a + b, a + b];
*
* R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']]
*/
var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) {
var idx = list.length - 1;
var result = [];
var tuple = [acc];
while (idx >= 0) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx -= 1;
}
return [
tuple[0],
result
];
});
/**
* Tests a regular expression against a String. Note that this function will
* return an empty array when there are no matches. This differs from
* [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)
* which returns `null` when there are no matches.
*
* @func
* @memberOf R
* @since v0.1.0
* @category String
* @sig RegExp -> String -> [String | Undefined]
* @param {RegExp} rx A regular expression.
* @param {String} str The string to match against
* @return {Array} The list of matches or empty array.
* @see R.test
* @example
*
* R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na']
* R.match(/a/, 'b'); //=> []
* R.match(/a/, null); //=> TypeError: null does not have a method named "match"
*/
var match = _curry2(function match(rx, str) {
return str.match(rx) || [];
});
/**
* mathMod behaves like the modulo operator should mathematically, unlike the
* `%` operator (and by extension, R.modulo). So while "-17 % 5" is -2,
* mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN
* when the modulus is zero or negative.
*
* @func
* @memberOf R
* @since v0.3.0
* @category Math
* @sig Number -> Number -> Number
* @param {Number} m The dividend.
* @param {Number} p the modulus.
* @return {Number} The result of `b mod a`.
* @example
*
* R.mathMod(-17, 5); //=> 3
* R.mathMod(17, 5); //=> 2
* R.mathMod(17, -5); //=> NaN
* R.mathMod(17, 0); //=> NaN
* R.mathMod(17.2, 5); //=> NaN
* R.mathMod(17, 5.3); //=> NaN
*
* var clock = R.mathMod(R.__, 12);
* clock(15); //=> 3
* clock(24); //=> 0
*
* var seventeenMod = R.mathMod(17);
* seventeenMod(3); //=> 2
* seventeenMod(4); //=> 1
* seventeenMod(10); //=> 7
*/
var mathMod = _curry2(function mathMod(m, p) {
if (!_isInteger(m)) {
return NaN;
}
if (!_isInteger(p) || p < 1) {
return NaN;
}
return (m % p + p) % p;
});
/**
* Returns the larger of its two arguments.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> a
* @param {*} a
* @param {*} b
* @return {*}
* @see R.maxBy, R.min
* @example
*
* R.max(789, 123); //=> 789
* R.max('a', 'b'); //=> 'b'
*/
var max = _curry2(function max(a, b) {
return b > a ? b : a;
});
/**
* Takes a function and two values, and returns whichever value produces the
* larger result when passed to the provided function.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Relation
* @sig Ord b => (a -> b) -> a -> a -> a
* @param {Function} f
* @param {*} a
* @param {*} b
* @return {*}
* @see R.max, R.minBy
* @example
*
* // square :: Number -> Number
* var square = n => n * n;
*
* R.maxBy(square, -3, 2); //=> -3
*
* R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5
* R.reduce(R.maxBy(square), 0, []); //=> 0
*/
var maxBy = _curry3(function maxBy(f, a, b) {
return f(b) > f(a) ? b : a;
});
/**
* Create a new object with the own properties of the first object merged with
* the own properties of the second object. If a key exists in both objects,
* the value from the second object will be used.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig {k: v} -> {k: v} -> {k: v}
* @param {Object} l
* @param {Object} r
* @return {Object}
* @see R.mergeWith, R.mergeWithKey
* @example
*
* R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 });
* //=> { 'name': 'fred', 'age': 40 }
*
* var resetToDefault = R.merge(R.__, {x: 0});
* resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2}
*/
var merge = _curry2(function merge(l, r) {
return _assign({}, l, r);
});
/**
* Merges a list of objects together into one object.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig [{k: v}] -> {k: v}
* @param {Array} list An array of objects
* @return {Object} A merged object.
* @see R.reduce
* @example
*
* R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3}
* R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2}
*/
var mergeAll = _curry1(function mergeAll(list) {
return _assign.apply(null, [{}].concat(list));
});
/**
* Creates a new object with the own properties of the two provided objects. If
* a key exists in both objects, the provided function is applied to the key
* and the values associated with the key in each object, with the result being
* used as the value associated with the key in the returned object. The key
* will be excluded from the returned object if the resulting value is
* `undefined`.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Object
* @sig (String -> a -> a -> a) -> {a} -> {a} -> {a}
* @param {Function} fn
* @param {Object} l
* @param {Object} r
* @return {Object}
* @see R.merge, R.mergeWith
* @example
*
* let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
* R.mergeWithKey(concatValues,
* { a: true, thing: 'foo', values: [10, 20] },
* { b: true, thing: 'bar', values: [15, 35] });
* //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
*/
var mergeWithKey = _curry3(function mergeWithKey(fn, l, r) {
var result = {};
var k;
for (k in l) {
if (_has(k, l)) {
result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k];
}
}
for (k in r) {
if (_has(k, r) && !_has(k, result)) {
result[k] = r[k];
}
}
return result;
});
/**
* Returns the smaller of its two arguments.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord a => a -> a -> a
* @param {*} a
* @param {*} b
* @return {*}
* @see R.minBy, R.max
* @example
*
* R.min(789, 123); //=> 123
* R.min('a', 'b'); //=> 'a'
*/
var min = _curry2(function min(a, b) {
return b < a ? b : a;
});
/**
* Takes a function and two values, and returns whichever value produces the
* smaller result when passed to the provided function.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Relation
* @sig Ord b => (a -> b) -> a -> a -> a
* @param {Function} f
* @param {*} a
* @param {*} b
* @return {*}
* @see R.min, R.maxBy
* @example
*
* // square :: Number -> Number
* var square = n => n * n;
*
* R.minBy(square, -3, 2); //=> 2
*
* R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1
* R.reduce(R.minBy(square), Infinity, []); //=> Infinity
*/
var minBy = _curry3(function minBy(f, a, b) {
return f(b) < f(a) ? b : a;
});
/**
* Divides the second parameter by the first and returns the remainder. Note
* that this function preserves the JavaScript-style behavior for modulo. For
* mathematical modulo see `mathMod`.
*
* @func
* @memberOf R
* @since v0.1.1
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The value to the divide.
* @param {Number} b The pseudo-modulus
* @return {Number} The result of `b % a`.
* @see R.mathMod
* @example
*
* R.modulo(17, 3); //=> 2
* // JS behavior:
* R.modulo(-17, 3); //=> -2
* R.modulo(17, -3); //=> 2
*
* var isOdd = R.modulo(R.__, 2);
* isOdd(42); //=> 0
* isOdd(21); //=> 1
*/
var modulo = _curry2(function modulo(a, b) {
return a % b;
});
/**
* Multiplies two numbers. Equivalent to `a * b` but curried.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a * b`.
* @see R.divide
* @example
*
* var double = R.multiply(2);
* var triple = R.multiply(3);
* double(3); //=> 6
* triple(4); //=> 12
* R.multiply(2, 5); //=> 10
*/
var multiply = _curry2(function multiply(a, b) {
return a * b;
});
/**
* Wraps a function of any arity (including nullary) in a function that accepts
* exactly `n` parameters. Any extraneous parameters will not be passed to the
* supplied function.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {Number} n The desired arity of the new function.
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity `n`.
* @example
*
* var takesTwoArgs = (a, b) => [a, b];
*
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.nAry(1, takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only `n` arguments are passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var nAry = _curry2(function nAry(n, fn) {
switch (n) {
case 0:
return function () {
return fn.call(this);
};
case 1:
return function (a0) {
return fn.call(this, a0);
};
case 2:
return function (a0, a1) {
return fn.call(this, a0, a1);
};
case 3:
return function (a0, a1, a2) {
return fn.call(this, a0, a1, a2);
};
case 4:
return function (a0, a1, a2, a3) {
return fn.call(this, a0, a1, a2, a3);
};
case 5:
return function (a0, a1, a2, a3, a4) {
return fn.call(this, a0, a1, a2, a3, a4);
};
case 6:
return function (a0, a1, a2, a3, a4, a5) {
return fn.call(this, a0, a1, a2, a3, a4, a5);
};
case 7:
return function (a0, a1, a2, a3, a4, a5, a6) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6);
};
case 8:
return function (a0, a1, a2, a3, a4, a5, a6, a7) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7);
};
case 9:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8);
};
case 10:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9);
};
default:
throw new Error('First argument to nAry must be a non-negative integer no greater than ten');
}
});
/**
* Negates its argument.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Math
* @sig Number -> Number
* @param {Number} n
* @return {Number}
* @example
*
* R.negate(42); //=> -42
*/
var negate = _curry1(function negate(n) {
return -n;
});
/**
* Returns `true` if no elements of the list match the predicate, `false`
* otherwise.
*
* Dispatches to the `any` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.12.0
* @category List
* @sig (a -> Boolean) -> [a] -> Boolean
* @param {Function} fn The predicate function.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise.
* @see R.all, R.any
* @example
*
* var isEven = n => n % 2 === 0;
*
* R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true
* R.none(isEven, [1, 3, 5, 7, 8, 11]); //=> false
*/
var none = _curry2(_complement(_dispatchable('any', _xany, any)));
/**
* A function that returns the `!` of its argument. It will return `true` when
* passed false-y value, and `false` when passed a truth-y one.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Logic
* @sig * -> Boolean
* @param {*} a any value
* @return {Boolean} the logical inverse of passed argument.
* @see R.complement
* @example
*
* R.not(true); //=> false
* R.not(false); //=> true
* R.not(0); => true
* R.not(1); => false
*/
var not = _curry1(function not(a) {
return !a;
});
/**
* Returns the nth element of the given list or string. If n is negative the
* element at index length + n is returned.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Number -> [a] -> a | Undefined
* @sig Number -> String -> String
* @param {Number} offset
* @param {*} list
* @return {*}
* @example
*
* var list = ['foo', 'bar', 'baz', 'quux'];
* R.nth(1, list); //=> 'bar'
* R.nth(-1, list); //=> 'quux'
* R.nth(-99, list); //=> undefined
*
* R.nth(2, 'abc'); //=> 'c'
* R.nth(3, 'abc'); //=> ''
*/
var nth = _curry2(function nth(offset, list) {
var idx = offset < 0 ? list.length + offset : offset;
return _isString(list) ? list.charAt(idx) : list[idx];
});
/**
* Returns a function which returns its nth argument.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Function
* @sig Number -> *... -> *
* @param {Number} n
* @return {Function}
* @example
*
* R.nthArg(1)('a', 'b', 'c'); //=> 'b'
* R.nthArg(-1)('a', 'b', 'c'); //=> 'c'
*/
var nthArg = _curry1(function nthArg(n) {
return function () {
return nth(n, arguments);
};
});
/**
* Creates an object containing a single key:value pair.
*
* @func
* @memberOf R
* @since v0.18.0
* @category Object
* @sig String -> a -> {String:a}
* @param {String} key
* @param {*} val
* @return {Object}
* @see R.pair
* @example
*
* var matchPhrases = R.compose(
* R.objOf('must'),
* R.map(R.objOf('match_phrase'))
* );
* matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]}
*/
var objOf = _curry2(function objOf(key, val) {
var obj = {};
obj[key] = val;
return obj;
});
/**
* Returns a singleton array containing the value provided.
*
* Note this `of` is different from the ES6 `of`; See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
*
* @func
* @memberOf R
* @since v0.3.0
* @category Function
* @sig a -> [a]
* @param {*} x any value
* @return {Array} An array wrapping `x`.
* @example
*
* R.of(null); //=> [null]
* R.of([42]); //=> [[42]]
*/
var of = _curry1(_of);
/**
* Accepts a function `fn` and returns a function that guards invocation of
* `fn` such that `fn` can only ever be called once, no matter how many times
* the returned function is invoked. The first value calculated is returned in
* subsequent invocations.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a... -> b) -> (a... -> b)
* @param {Function} fn The function to wrap in a call-only-once wrapper.
* @return {Function} The wrapped function.
* @example
*
* var addOneOnce = R.once(x => x + 1);
* addOneOnce(10); //=> 11
* addOneOnce(addOneOnce(50)); //=> 11
*/
var once = _curry1(function once(fn) {
var called = false;
var result;
return _arity(fn.length, function () {
if (called) {
return result;
}
called = true;
result = fn.apply(this, arguments);
return result;
});
});
/**
* Returns `true` if one or both of its arguments are `true`. Returns `false`
* if both arguments are `false`.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Logic
* @sig * -> * -> *
* @param {Boolean} a A boolean value
* @param {Boolean} b A boolean value
* @return {Boolean} `true` if one or both arguments are `true`, `false` otherwise
* @see R.either
* @example
*
* R.or(true, true); //=> true
* R.or(true, false); //=> true
* R.or(false, true); //=> true
* R.or(false, false); //=> false
*/
var or = _curry2(function or(a, b) {
return a || b;
});
/**
* Returns the result of "setting" the portion of the given data structure
* focused by the given lens to the result of applying the given function to
* the focused value.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> (a -> a) -> s -> s
* @param {Lens} lens
* @param {*} v
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var headLens = R.lensIndex(0);
*
* R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz']
*/
// `Identity` is a functor that holds a single value, where `map` simply
// transforms the held value with the provided function.
// The value returned by the getter function is first transformed with `f`,
// then set as the value of an `Identity`. This is then mapped over with the
// setter function of the lens.
var over = function () {
// `Identity` is a functor that holds a single value, where `map` simply
// transforms the held value with the provided function.
var Identity = function (x) {
return {
value: x,
map: function (f) {
return Identity(f(x));
}
};
};
return _curry3(function over(lens, f, x) {
// The value returned by the getter function is first transformed with `f`,
// then set as the value of an `Identity`. This is then mapped over with the
// setter function of the lens.
return lens(function (y) {
return Identity(f(y));
})(x).value;
});
}();
/**
* Takes two arguments, `fst` and `snd`, and returns `[fst, snd]`.
*
* @func
* @memberOf R
* @since v0.18.0
* @category List
* @sig a -> b -> (a,b)
* @param {*} fst
* @param {*} snd
* @return {Array}
* @see R.objOf, R.of
* @example
*
* R.pair('foo', 'bar'); //=> ['foo', 'bar']
*/
var pair = _curry2(function pair(fst, snd) {
return [
fst,
snd
];
});
/**
* Retrieve the value at a given path.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Object
* @sig [String] -> {k: v} -> v | Undefined
* @param {Array} path The path to use.
* @param {Object} obj The object to retrieve the nested property from.
* @return {*} The data at `path`.
* @example
*
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
*/
var path = _curry2(function path(paths, obj) {
var val = obj;
var idx = 0;
while (idx < paths.length) {
if (val == null) {
return;
}
val = val[paths[idx]];
idx += 1;
}
return val;
});
/**
* If the given, non-null object has a value at the given path, returns the
* value at that path. Otherwise returns the provided default value.
*
* @func
* @memberOf R
* @since v0.18.0
* @category Object
* @sig a -> [String] -> Object -> a
* @param {*} d The default value.
* @param {Array} p The path to use.
* @param {Object} obj The object to retrieve the nested property from.
* @return {*} The data at `path` of the supplied object or the default value.
* @example
*
* R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
* R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"
*/
var pathOr = _curry3(function pathOr(d, p, obj) {
return defaultTo(d, path(p, obj));
});
/**
* Returns `true` if the specified object property at given path satisfies the
* given predicate; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Logic
* @sig (a -> Boolean) -> [String] -> Object -> Boolean
* @param {Function} pred
* @param {Array} propPath
* @param {*} obj
* @return {Boolean}
* @see R.propSatisfies, R.path
* @example
*
* R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true
*/
var pathSatisfies = _curry3(function pathSatisfies(pred, propPath, obj) {
return propPath.length > 0 && pred(path(propPath, obj));
});
/**
* Returns a partial copy of an object containing only the keys specified. If
* the key does not exist, the property is ignored.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String property names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.omit, R.props
* @example
*
* R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}
*/
var pick = _curry2(function pick(names, obj) {
var result = {};
var idx = 0;
while (idx < names.length) {
if (names[idx] in obj) {
result[names[idx]] = obj[names[idx]];
}
idx += 1;
}
return result;
});
/**
* Similar to `pick` except that this one includes a `key: undefined` pair for
* properties that don't exist.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig [k] -> {k: v} -> {k: v}
* @param {Array} names an array of String property names to copy onto a new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties from `names` on it.
* @see R.pick
* @example
*
* R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
* R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined}
*/
var pickAll = _curry2(function pickAll(names, obj) {
var result = {};
var idx = 0;
var len = names.length;
while (idx < len) {
var name = names[idx];
result[name] = obj[name];
idx += 1;
}
return result;
});
/**
* Returns a partial copy of an object containing only the keys that satisfy
* the supplied predicate.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Object
* @sig (v, k -> Boolean) -> {k: v} -> {k: v}
* @param {Function} pred A predicate to determine whether or not a key
* should be included on the output object.
* @param {Object} obj The object to copy from
* @return {Object} A new object with only properties that satisfy `pred`
* on it.
* @see R.pick, R.filter
* @example
*
* var isUpperCase = (val, key) => key.toUpperCase() === key;
* R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
*/
var pickBy = _curry2(function pickBy(test, obj) {
var result = {};
for (var prop in obj) {
if (test(obj[prop], prop, obj)) {
result[prop] = obj[prop];
}
}
return result;
});
/**
* Returns a new list with the given element at the front, followed by the
* contents of the list.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig a -> [a] -> [a]
* @param {*} el The item to add to the head of the output list.
* @param {Array} list The array to add to the tail of the output list.
* @return {Array} A new array.
* @see R.append
* @example
*
* R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum']
*/
var prepend = _curry2(function prepend(el, list) {
return _concat([el], list);
});
/**
* Returns a function that when supplied an object returns the indicated
* property of that object, if it exists.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig s -> {s: a} -> a | Undefined
* @param {String} p The property name
* @param {Object} obj The object to query
* @return {*} The value at `obj.p`.
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
*/
var prop = _curry2(function prop(p, obj) {
return obj[p];
});
/**
* If the given, non-null object has an own property with the specified name,
* returns the value of that property. Otherwise returns the provided default
* value.
*
* @func
* @memberOf R
* @since v0.6.0
* @category Object
* @sig a -> String -> Object -> a
* @param {*} val The default value.
* @param {String} p The name of the property to return.
* @param {Object} obj The object to query.
* @return {*} The value of given property of the supplied object or the default value.
* @example
*
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var favorite = R.prop('favoriteLibrary');
* var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');
*
* favorite(alice); //=> undefined
* favoriteWithDefault(alice); //=> 'Ramda'
*/
var propOr = _curry3(function propOr(val, p, obj) {
return obj != null && _has(p, obj) ? obj[p] : val;
});
/**
* Returns `true` if the specified object property satisfies the given
* predicate; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Logic
* @sig (a -> Boolean) -> String -> {String: a} -> Boolean
* @param {Function} pred
* @param {String} name
* @param {*} obj
* @return {Boolean}
* @see R.propEq, R.propIs
* @example
*
* R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true
*/
var propSatisfies = _curry3(function propSatisfies(pred, name, obj) {
return pred(obj[name]);
});
/**
* Acts as multiple `prop`: array of keys in, array of values out. Preserves
* order.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig [k] -> {k: v} -> [v]
* @param {Array} ps The property names to fetch
* @param {Object} obj The object to query
* @return {Array} The corresponding values or partially applied function.
* @example
*
* R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]
* R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]
*
* var fullName = R.compose(R.join(' '), R.props(['first', 'last']));
* fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'
*/
var props = _curry2(function props(ps, obj) {
var len = ps.length;
var out = [];
var idx = 0;
while (idx < len) {
out[idx] = obj[ps[idx]];
idx += 1;
}
return out;
});
/**
* Returns a list of numbers from `from` (inclusive) to `to` (exclusive).
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Number -> Number -> [Number]
* @param {Number} from The first number in the list.
* @param {Number} to One more than the last number in the list.
* @return {Array} The list of numbers in tthe set `[a, b)`.
* @example
*
* R.range(1, 5); //=> [1, 2, 3, 4]
* R.range(50, 53); //=> [50, 51, 52]
*/
var range = _curry2(function range(from, to) {
if (!(_isNumber(from) && _isNumber(to))) {
throw new TypeError('Both arguments to range must be numbers');
}
var result = [];
var n = from;
while (n < to) {
result.push(n);
n += 1;
}
return result;
});
/**
* Returns a single item by iterating through the list, successively calling
* the iterator function and passing it an accumulator value and the current
* value from the array, and then passing the result to the next call.
*
* Similar to `reduce`, except moves through the input list from the right to
* the left.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse
* arrays), unlike the native `Array.prototype.reduce` method. For more details
* on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.addIndex
* @example
*
* var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
* var flattenPairs = (acc, pair) => acc.concat(pair);
*
* R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
*/
var reduceRight = _curry3(function reduceRight(fn, acc, list) {
var idx = list.length - 1;
while (idx >= 0) {
acc = fn(acc, list[idx]);
idx -= 1;
}
return acc;
});
/**
* Returns a value wrapped to indicate that it is the final value of the reduce
* and transduce functions. The returned value should be considered a black
* box: the internal structure is not guaranteed to be stable.
*
* Note: this optimization is unavailable to functions not explicitly listed
* above. For instance, it is not currently supported by reduceRight.
*
* @func
* @memberOf R
* @since v0.15.0
* @category List
* @sig a -> *
* @param {*} x The final value of the reduce.
* @return {*} The wrapped value.
* @see R.reduce, R.transduce
* @example
*
* R.reduce(
* R.pipe(R.add, R.when(R.gte(R.__, 10), R.reduced)),
* 0,
* [1, 2, 3, 4, 5]) // 10
*/
var reduced = _curry1(_reduced);
/**
* Removes the sub-list of `list` starting at index `start` and containing
* `count` elements. _Note that this is not destructive_: it returns a copy of
* the list with the changes.
* <small>No lists have been harmed in the application of this function.</small>
*
* @func
* @memberOf R
* @since v0.2.2
* @category List
* @sig Number -> Number -> [a] -> [a]
* @param {Number} start The position to start removing elements
* @param {Number} count The number of elements to remove
* @param {Array} list The list to remove from
* @return {Array} A new Array with `count` elements from `start` removed.
* @example
*
* R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
*/
var remove = _curry3(function remove(start, count, list) {
return _concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count)));
});
/**
* Replace a substring or regex match in a string with a replacement.
*
* @func
* @memberOf R
* @since v0.7.0
* @category String
* @sig RegExp|String -> String -> String -> String
* @param {RegExp|String} pattern A regular expression or a substring to match.
* @param {String} replacement The string to replace the matches with.
* @param {String} str The String to do the search and replacement in.
* @return {String} The result.
* @example
*
* R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo'
* R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo'
*
* // Use the "g" (global) flag to replace all occurrences:
* R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar'
*/
var replace = _curry3(function replace(regex, replacement, str) {
return str.replace(regex, replacement);
});
/**
* Returns a new list or string with the elements or characters in reverse
* order.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [a]
* @sig String -> String
* @param {Array|String} list
* @return {Array|String}
* @example
*
* R.reverse([1, 2, 3]); //=> [3, 2, 1]
* R.reverse([1, 2]); //=> [2, 1]
* R.reverse([1]); //=> [1]
* R.reverse([]); //=> []
*
* R.reverse('abc'); //=> 'cba'
* R.reverse('ab'); //=> 'ba'
* R.reverse('a'); //=> 'a'
* R.reverse(''); //=> ''
*/
var reverse = _curry1(function reverse(list) {
return _isString(list) ? list.split('').reverse().join('') : _slice(list).reverse();
});
/**
* Scan is similar to reduce, but returns a list of successively reduced values
* from the left
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig (a,b -> a) -> a -> [b] -> [a]
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {Array} A list of all intermediately reduced values.
* @example
*
* var numbers = [1, 2, 3, 4];
* var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24]
*/
var scan = _curry3(function scan(fn, acc, list) {
var idx = 0;
var len = list.length;
var result = [acc];
while (idx < len) {
acc = fn(acc, list[idx]);
result[idx + 1] = acc;
idx += 1;
}
return result;
});
/**
* Returns the result of "setting" the portion of the given data structure
* focused by the given lens to the given value.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> a -> s -> s
* @param {Lens} lens
* @param {*} v
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lensProp('x');
*
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2}
*/
var set = _curry3(function set(lens, v, x) {
return over(lens, always(v), x);
});
/**
* Returns the elements of the given list or string (or object with a `slice`
* method) from `fromIndex` (inclusive) to `toIndex` (exclusive).
*
* Dispatches to the `slice` method of the third argument, if present.
*
* @func
* @memberOf R
* @since v0.1.4
* @category List
* @sig Number -> Number -> [a] -> [a]
* @sig Number -> Number -> String -> String
* @param {Number} fromIndex The start index (inclusive).
* @param {Number} toIndex The end index (exclusive).
* @param {*} list
* @return {*}
* @example
*
* R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']
* R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']
* R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(0, 3, 'ramda'); //=> 'ram'
*/
var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) {
return Array.prototype.slice.call(list, fromIndex, toIndex);
}));
/**
* Returns a copy of the list, sorted according to the comparator function,
* which should accept two values at a time and return a negative number if the
* first value is smaller, a positive number if it's larger, and zero if they
* are equal. Please note that this is a **copy** of the list. It does not
* modify the original.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a,a -> Number) -> [a] -> [a]
* @param {Function} comparator A sorting function :: a -> b -> Int
* @param {Array} list The list to sort
* @return {Array} a new array with its elements sorted by the comparator function.
* @example
*
* var diff = function(a, b) { return a - b; };
* R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]
*/
var sort = _curry2(function sort(comparator, list) {
return _slice(list).sort(comparator);
});
/**
* Sorts the list according to the supplied function.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig Ord b => (a -> b) -> [a] -> [a]
* @param {Function} fn
* @param {Array} list The list to sort.
* @return {Array} A new list sorted by the keys generated by `fn`.
* @example
*
* var sortByFirstItem = R.sortBy(R.prop(0));
* var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name')));
* var pairs = [[-1, 1], [-2, 2], [-3, 3]];
* sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]]
* var alice = {
* name: 'ALICE',
* age: 101
* };
* var bob = {
* name: 'Bob',
* age: -10
* };
* var clara = {
* name: 'clara',
* age: 314.159
* };
* var people = [clara, bob, alice];
* sortByNameCaseInsensitive(people); //=> [alice, bob, clara]
*/
var sortBy = _curry2(function sortBy(fn, list) {
return _slice(list).sort(function (a, b) {
var aa = fn(a);
var bb = fn(b);
return aa < bb ? -1 : aa > bb ? 1 : 0;
});
});
/**
* Splits a given list or string at a given index.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig Number -> [a] -> [[a], [a]]
* @sig Number -> String -> [String, String]
* @param {Number} index The index where the array/string is split.
* @param {Array|String} array The array/string to be split.
* @return {Array}
* @example
*
* R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]]
* R.splitAt(5, 'hello world'); //=> ['hello', ' world']
* R.splitAt(-1, 'foobar'); //=> ['fooba', 'r']
*/
var splitAt = _curry2(function splitAt(index, array) {
return [
slice(0, index, array),
slice(index, length(array), array)
];
});
/**
* Splits a collection into slices of the specified length.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig Number -> [a] -> [[a]]
* @sig Number -> String -> [String]
* @param {Number} n
* @param {Array} list
* @return {Array}
* @example
*
* R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]]
* R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz']
*/
var splitEvery = _curry2(function splitEvery(n, list) {
if (n <= 0) {
throw new Error('First argument to splitEvery must be a positive integer');
}
var result = [];
var idx = 0;
while (idx < list.length) {
result.push(slice(idx, idx += n, list));
}
return result;
});
/**
* Takes a list and a predicate and returns a pair of lists with the following properties:
*
* - the result of concatenating the two output lists is equivalent to the input list;
* - none of the elements of the first output list satisfies the predicate; and
* - if the second output list is non-empty, its first element satisfies the predicate.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig (a -> Boolean) -> [a] -> [[a], [a]]
* @param {Function} pred The predicate that determines where the array is split.
* @param {Array} list The array to be split.
* @return {Array}
* @example
*
* R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]]
*/
var splitWhen = _curry2(function splitWhen(pred, list) {
var idx = 0;
var len = list.length;
var prefix = [];
while (idx < len && !pred(list[idx])) {
prefix.push(list[idx]);
idx += 1;
}
return [
prefix,
_slice(list, idx)
];
});
/**
* Subtracts its second argument from its first argument.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig Number -> Number -> Number
* @param {Number} a The first value.
* @param {Number} b The second value.
* @return {Number} The result of `a - b`.
* @see R.add
* @example
*
* R.subtract(10, 8); //=> 2
*
* var minus5 = R.subtract(R.__, 5);
* minus5(17); //=> 12
*
* var complementaryAngle = R.subtract(90);
* complementaryAngle(30); //=> 60
* complementaryAngle(72); //=> 18
*/
var subtract = _curry2(function subtract(a, b) {
return Number(a) - Number(b);
});
/**
* Returns all but the first element of the given list or string (or object
* with a `tail` method).
*
* Dispatches to the `slice` method of the first argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [a]
* @sig String -> String
* @param {*} list
* @return {*}
* @see R.head, R.init, R.last
* @example
*
* R.tail([1, 2, 3]); //=> [2, 3]
* R.tail([1, 2]); //=> [2]
* R.tail([1]); //=> []
* R.tail([]); //=> []
*
* R.tail('abc'); //=> 'bc'
* R.tail('ab'); //=> 'b'
* R.tail('a'); //=> ''
* R.tail(''); //=> ''
*/
var tail = _checkForMethod('tail', slice(1, Infinity));
/**
* Returns the first `n` elements of the given list, string, or
* transducer/transformer (or object with a `take` method).
*
* Dispatches to the `take` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n
* @param {*} list
* @return {*}
* @see R.drop
* @example
*
* R.take(1, ['foo', 'bar', 'baz']); //=> ['foo']
* R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
* R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.take(3, 'ramda'); //=> 'ram'
*
* var personnel = [
* 'Dave Brubeck',
* 'Paul Desmond',
* 'Eugene Wright',
* 'Joe Morello',
* 'Gerry Mulligan',
* 'Bob Bates',
* 'Joe Dodge',
* 'Ron Crotty'
* ];
*
* var takeFive = R.take(5);
* takeFive(personnel);
* //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']
*/
var take = _curry2(_dispatchable('take', _xtake, function take(n, xs) {
return slice(0, n < 0 ? Infinity : n, xs);
}));
/**
* Returns a new list containing the last `n` elements of a given list, passing
* each value to the supplied predicate function, and terminating when the
* predicate function returns `false`. Excludes the element that caused the
* predicate function to fail. The predicate function is passed one argument:
* *(value)*.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.dropLastWhile, R.addIndex
* @example
*
* var isNotOne = x => x !== 1;
*
* R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4]
*/
var takeLastWhile = _curry2(function takeLastWhile(fn, list) {
var idx = list.length - 1;
while (idx >= 0 && fn(list[idx])) {
idx -= 1;
}
return _slice(list, idx + 1, Infinity);
});
/**
* Returns a new list containing the first `n` elements of a given list,
* passing each value to the supplied predicate function, and terminating when
* the predicate function returns `false`. Excludes the element that caused the
* predicate function to fail. The predicate function is passed one argument:
* *(value)*.
*
* Dispatches to the `takeWhile` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.dropWhile, R.transduce, R.addIndex
* @example
*
* var isNotFour = x => x !== 4;
*
* R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3]
*/
var takeWhile = _curry2(_dispatchable('takeWhile', _xtakeWhile, function takeWhile(fn, list) {
var idx = 0;
var len = list.length;
while (idx < len && fn(list[idx])) {
idx += 1;
}
return _slice(list, 0, idx);
}));
/**
* Runs the given function with the supplied object, then returns the object.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a -> *) -> a -> a
* @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away.
* @param {*} x
* @return {*} `x`.
* @example
*
* var sayX = x => console.log('x is ' + x);
* R.tap(sayX, 100); //=> 100
* //-> 'x is 100'
*/
var tap = _curry2(function tap(fn, x) {
fn(x);
return x;
});
/**
* Calls an input function `n` times, returning an array containing the results
* of those function calls.
*
* `fn` is passed one argument: The current value of `n`, which begins at `0`
* and is gradually incremented to `n - 1`.
*
* @func
* @memberOf R
* @since v0.2.3
* @category List
* @sig (Number -> a) -> Number -> [a]
* @param {Function} fn The function to invoke. Passed one argument, the current value of `n`.
* @param {Number} n A value between `0` and `n - 1`. Increments after each function call.
* @return {Array} An array containing the return values of all calls to `fn`.
* @example
*
* R.times(R.identity, 5); //=> [0, 1, 2, 3, 4]
*/
var times = _curry2(function times(fn, n) {
var len = Number(n);
var idx = 0;
var list;
if (len < 0 || isNaN(len)) {
throw new RangeError('n must be a non-negative number');
}
list = new Array(len);
while (idx < len) {
list[idx] = fn(idx);
idx += 1;
}
return list;
});
/**
* Converts an object into an array of key, value arrays. Only the object's
* own properties are used.
* Note that the order of the output array is not guaranteed to be consistent
* across different JS platforms.
*
* @func
* @memberOf R
* @since v0.4.0
* @category Object
* @sig {String: *} -> [[String,*]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own properties.
* @see R.fromPairs
* @example
*
* R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]]
*/
var toPairs = _curry1(function toPairs(obj) {
var pairs = [];
for (var prop in obj) {
if (_has(prop, obj)) {
pairs[pairs.length] = [
prop,
obj[prop]
];
}
}
return pairs;
});
/**
* Converts an object into an array of key, value arrays. The object's own
* properties and prototype properties are used. Note that the order of the
* output array is not guaranteed to be consistent across different JS
* platforms.
*
* @func
* @memberOf R
* @since v0.4.0
* @category Object
* @sig {String: *} -> [[String,*]]
* @param {Object} obj The object to extract from
* @return {Array} An array of key, value arrays from the object's own
* and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.toPairsIn(f); //=> [['x','X'], ['y','Y']]
*/
var toPairsIn = _curry1(function toPairsIn(obj) {
var pairs = [];
for (var prop in obj) {
pairs[pairs.length] = [
prop,
obj[prop]
];
}
return pairs;
});
/**
* Transposes the rows and columns of a 2D list.
* When passed a list of `n` lists of length `x`,
* returns a list of `x` lists of length `n`.
*
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig [[a]] -> [[a]]
* @param {Array} list A 2D list
* @return {Array} A 2D list
* @example
*
* R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']]
* R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']]
*
* If some of the rows are shorter than the following rows, their elements are skipped:
*
* R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]]
*/
var transpose = _curry1(function transpose(outerlist) {
var i = 0;
var result = [];
while (i < outerlist.length) {
var innerlist = outerlist[i];
var j = 0;
while (j < innerlist.length) {
if (typeof result[j] === 'undefined') {
result[j] = [];
}
result[j].push(innerlist[j]);
j += 1;
}
i += 1;
}
return result;
});
/**
* Removes (strips) whitespace from both ends of the string.
*
* @func
* @memberOf R
* @since v0.6.0
* @category String
* @sig String -> String
* @param {String} str The string to trim.
* @return {String} Trimmed version of `str`.
* @example
*
* R.trim(' xyz '); //=> 'xyz'
* R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z']
*/
var trim = function () {
var ws = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + '\u2029\uFEFF';
var zeroWidth = '\u200B';
var hasProtoTrim = typeof String.prototype.trim === 'function';
if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) {
return _curry1(function trim(str) {
var beginRx = new RegExp('^[' + ws + '][' + ws + ']*');
var endRx = new RegExp('[' + ws + '][' + ws + ']*$');
return str.replace(beginRx, '').replace(endRx, '');
});
} else {
return _curry1(function trim(str) {
return str.trim();
});
}
}();
/**
* `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned
* function evaluates the `tryer`; if it does not throw, it simply returns the
* result. If the `tryer` *does* throw, the returned function evaluates the
* `catcher` function and returns its result. Note that for effective
* composition with this function, both the `tryer` and `catcher` functions
* must return the same type of results.
*
* @func
* @memberOf R
* @since v0.20.0
* @category Function
* @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a)
* @param {Function} tryer The function that may throw.
* @param {Function} catcher The function that will be evaluated if `tryer` throws.
* @return {Function} A new function that will catch exceptions and send then to the catcher.
* @example
*
* R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true
* R.tryCatch(R.prop('x'), R.F, null); //=> false
*/
var tryCatch = _curry2(function _tryCatch(tryer, catcher) {
return _arity(tryer.length, function () {
try {
return tryer.apply(this, arguments);
} catch (e) {
return catcher.apply(this, _concat([e], arguments));
}
});
});
/**
* Gives a single-word string description of the (native) type of a value,
* returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
* attempt to distinguish user Object types any further, reporting them all as
* 'Object'.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Type
* @sig (* -> {*}) -> String
* @param {*} val The value to test
* @return {String}
* @example
*
* R.type({}); //=> "Object"
* R.type(1); //=> "Number"
* R.type(false); //=> "Boolean"
* R.type('s'); //=> "String"
* R.type(null); //=> "Null"
* R.type([]); //=> "Array"
* R.type(/[A-z]/); //=> "RegExp"
*/
var type = _curry1(function type(val) {
return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1);
});
/**
* Takes a function `fn`, which takes a single array argument, and returns a
* function which:
*
* - takes any number of positional arguments;
* - passes these arguments to `fn` as an array; and
* - returns the result.
*
* In other words, R.unapply derives a variadic function from a function which
* takes an array. R.unapply is the inverse of R.apply.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Function
* @sig ([*...] -> a) -> (*... -> a)
* @param {Function} fn
* @return {Function}
* @see R.apply
* @example
*
* R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]'
*/
var unapply = _curry1(function unapply(fn) {
return function () {
return fn(_slice(arguments));
};
});
/**
* Wraps a function of any arity (including nullary) in a function that accepts
* exactly 1 parameter. Any extraneous parameters will not be passed to the
* supplied function.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Function
* @sig (* -> b) -> (a -> b)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 1.
* @example
*
* var takesTwoArgs = function(a, b) {
* return [a, b];
* };
* takesTwoArgs.length; //=> 2
* takesTwoArgs(1, 2); //=> [1, 2]
*
* var takesOneArg = R.unary(takesTwoArgs);
* takesOneArg.length; //=> 1
* // Only 1 argument is passed to the wrapped function
* takesOneArg(1, 2); //=> [1, undefined]
*/
var unary = _curry1(function unary(fn) {
return nAry(1, fn);
});
/**
* Returns a function of arity `n` from a (manually) curried function.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Function
* @sig Number -> (a -> b) -> (a -> c)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to uncurry.
* @return {Function} A new function.
* @see R.curry
* @example
*
* var addFour = a => b => c => d => a + b + c + d;
*
* var uncurriedAddFour = R.uncurryN(4, addFour);
* uncurriedAddFour(1, 2, 3, 4); //=> 10
*/
var uncurryN = _curry2(function uncurryN(depth, fn) {
return curryN(depth, function () {
var currentDepth = 1;
var value = fn;
var idx = 0;
var endIdx;
while (currentDepth <= depth && typeof value === 'function') {
endIdx = currentDepth === depth ? arguments.length : idx + value.length;
value = value.apply(this, _slice(arguments, idx, endIdx));
currentDepth += 1;
idx = endIdx;
}
return value;
});
});
/**
* Builds a list from a seed value. Accepts an iterator function, which returns
* either false to stop iteration or an array of length 2 containing the value
* to add to the resulting list and the seed to be used in the next call to the
* iterator function.
*
* The iterator function receives one argument: *(seed)*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig (a -> [b]) -> * -> [b]
* @param {Function} fn The iterator function. receives one argument, `seed`, and returns
* either false to quit iteration or an array of length two to proceed. The element
* at index 0 of this array will be added to the resulting array, and the element
* at index 1 will be passed to the next call to `fn`.
* @param {*} seed The seed value.
* @return {Array} The final list.
* @example
*
* var f = n => n > 50 ? false : [-n, n + 10];
* R.unfold(f, 10); //=> [-10, -20, -30, -40, -50]
*/
var unfold = _curry2(function unfold(fn, seed) {
var pair = fn(seed);
var result = [];
while (pair && pair.length) {
result[result.length] = pair[0];
pair = fn(pair[1]);
}
return result;
});
/**
* Returns a new list containing only one copy of each element in the original
* list, based upon the value returned by applying the supplied predicate to
* two list elements. Prefers the first item if two items compare equal based
* on the predicate.
*
* @func
* @memberOf R
* @since v0.2.0
* @category List
* @sig (a, a -> Boolean) -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* var strEq = R.eqBy(String);
* R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2]
* R.uniqWith(strEq)([{}, {}]); //=> [{}]
* R.uniqWith(strEq)([1, '1', 1]); //=> [1]
* R.uniqWith(strEq)(['1', 1, 1]); //=> ['1']
*/
var uniqWith = _curry2(function uniqWith(pred, list) {
var idx = 0;
var len = list.length;
var result = [];
var item;
while (idx < len) {
item = list[idx];
if (!_containsWith(pred, item, result)) {
result[result.length] = item;
}
idx += 1;
}
return result;
});
/**
* Tests the final argument by passing it to the given predicate function. If
* the predicate is not satisfied, the function will return the result of
* calling the `whenFalseFn` function with the same argument. If the predicate
* is satisfied, the argument is returned as is.
*
* @func
* @memberOf R
* @since v0.18.0
* @category Logic
* @sig (a -> Boolean) -> (a -> a) -> a -> a
* @param {Function} pred A predicate function
* @param {Function} whenFalseFn A function to invoke when the `pred` evaluates
* to a falsy value.
* @param {*} x An object to test with the `pred` function and
* pass to `whenFalseFn` if necessary.
* @return {*} Either `x` or the result of applying `x` to `whenFalseFn`.
* @see R.ifElse, R.when
* @example
*
* // coerceArray :: (a|[a]) -> [a]
* var coerceArray = R.unless(R.isArrayLike, R.of);
* coerceArray([1, 2, 3]); //=> [1, 2, 3]
* coerceArray(1); //=> [1]
*/
var unless = _curry3(function unless(pred, whenFalseFn, x) {
return pred(x) ? x : whenFalseFn(x);
});
/**
* Takes a predicate, a transformation function, and an initial value,
* and returns a value of the same type as the initial value.
* It does so by applying the transformation until the predicate is satisfied,
* at which point it returns the satisfactory value.
*
* @func
* @memberOf R
* @since v0.20.0
* @category Logic
* @sig (a -> Boolean) -> (a -> a) -> a -> a
* @param {Function} pred A predicate function
* @param {Function} fn The iterator function
* @param {*} init Initial value
* @return {*} Final value that satisfies predicate
* @example
*
* R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128
*/
var until = _curry3(function until(pred, fn, init) {
var val = init;
while (!pred(val)) {
val = fn(val);
}
return val;
});
/**
* Returns a new copy of the array with the element at the provided index
* replaced with the given value.
*
* @func
* @memberOf R
* @since v0.14.0
* @category List
* @sig Number -> a -> [a] -> [a]
* @param {Number} idx The index to update.
* @param {*} x The value to exist at the given index of the returned array.
* @param {Array|Arguments} list The source array-like object to be updated.
* @return {Array} A copy of `list` with the value at index `idx` replaced with `x`.
* @see R.adjust
* @example
*
* R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2]
* R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2]
*/
var update = _curry3(function update(idx, x, list) {
return adjust(always(x), idx, list);
});
/**
* Accepts a function `fn` and a list of transformer functions and returns a
* new curried function. When the new function is invoked, it calls the
* function `fn` with parameters consisting of the result of calling each
* supplied handler on successive arguments to the new function.
*
* If more arguments are passed to the returned function than transformer
* functions, those arguments are passed directly to `fn` as additional
* parameters. If you expect additional arguments that don't need to be
* transformed, although you can ignore them, it's best to pass an identity
* function so that the new function reports the correct arity.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (x1 -> x2 -> ... -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z)
* @param {Function} fn The function to wrap.
* @param {Array} transformers A list of transformer functions
* @return {Function} The wrapped function.
* @example
*
* R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81
* R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81
* R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32
* R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32
*/
var useWith = _curry2(function useWith(fn, transformers) {
return curryN(transformers.length, function () {
var args = [];
var idx = 0;
while (idx < transformers.length) {
args.push(transformers[idx].call(this, arguments[idx]));
idx += 1;
}
return fn.apply(this, args.concat(_slice(arguments, transformers.length)));
});
});
/**
* Returns a list of all the enumerable own properties of the supplied object.
* Note that the order of the output array is not guaranteed across different
* JS platforms.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own properties.
* @example
*
* R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]
*/
var values = _curry1(function values(obj) {
var props = keys(obj);
var len = props.length;
var vals = [];
var idx = 0;
while (idx < len) {
vals[idx] = obj[props[idx]];
idx += 1;
}
return vals;
});
/**
* Returns a list of all the properties, including prototype properties, of the
* supplied object.
* Note that the order of the output array is not guaranteed to be consistent
* across different JS platforms.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Object
* @sig {k: v} -> [v]
* @param {Object} obj The object to extract values from
* @return {Array} An array of the values of the object's own and prototype properties.
* @example
*
* var F = function() { this.x = 'X'; };
* F.prototype.y = 'Y';
* var f = new F();
* R.valuesIn(f); //=> ['X', 'Y']
*/
var valuesIn = _curry1(function valuesIn(obj) {
var prop;
var vs = [];
for (prop in obj) {
vs[vs.length] = obj[prop];
}
return vs;
});
/**
* Returns a "view" of the given data structure, determined by the given lens.
* The lens's focus determines which portion of the data structure is visible.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Lens s a -> s -> a
* @param {Lens} lens
* @param {*} x
* @return {*}
* @see R.prop, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lensProp('x');
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.view(xLens, {x: 4, y: 2}); //=> 4
*/
// `Const` is a functor that effectively ignores the function given to `map`.
// Using `Const` effectively ignores the setter function of the `lens`,
// leaving the value returned by the getter function unmodified.
var view = function () {
// `Const` is a functor that effectively ignores the function given to `map`.
var Const = function (x) {
return {
value: x,
map: function () {
return this;
}
};
};
return _curry2(function view(lens, x) {
// Using `Const` effectively ignores the setter function of the `lens`,
// leaving the value returned by the getter function unmodified.
return lens(Const)(x).value;
});
}();
/**
* Tests the final argument by passing it to the given predicate function. If
* the predicate is satisfied, the function will return the result of calling
* the `whenTrueFn` function with the same argument. If the predicate is not
* satisfied, the argument is returned as is.
*
* @func
* @memberOf R
* @since v0.18.0
* @category Logic
* @sig (a -> Boolean) -> (a -> a) -> a -> a
* @param {Function} pred A predicate function
* @param {Function} whenTrueFn A function to invoke when the `condition`
* evaluates to a truthy value.
* @param {*} x An object to test with the `pred` function and
* pass to `whenTrueFn` if necessary.
* @return {*} Either `x` or the result of applying `x` to `whenTrueFn`.
* @see R.ifElse, R.unless
* @example
*
* // truncate :: String -> String
* var truncate = R.when(
* R.propSatisfies(R.gt(R.__, 10), 'length'),
* R.pipe(R.take(10), R.append('…'), R.join(''))
* );
* truncate('12345'); //=> '12345'
* truncate('0123456789ABC'); //=> '0123456789…'
*/
var when = _curry3(function when(pred, whenTrueFn, x) {
return pred(x) ? whenTrueFn(x) : x;
});
/**
* Takes a spec object and a test object; returns true if the test satisfies
* the spec. Each of the spec's own properties must be a predicate function.
* Each predicate is applied to the value of the corresponding property of the
* test object. `where` returns true if all the predicates return true, false
* otherwise.
*
* `where` is well suited to declaratively expressing constraints for other
* functions such as `filter` and `find`.
*
* @func
* @memberOf R
* @since v0.1.1
* @category Object
* @sig {String: (* -> Boolean)} -> {String: *} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @example
*
* // pred :: Object -> Boolean
* var pred = R.where({
* a: R.equals('foo'),
* b: R.complement(R.equals('bar')),
* x: R.gt(_, 10),
* y: R.lt(_, 20)
* });
*
* pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
* pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
* pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
* pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
* pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
*/
var where = _curry2(function where(spec, testObj) {
for (var prop in spec) {
if (_has(prop, spec) && !spec[prop](testObj[prop])) {
return false;
}
}
return true;
});
/**
* Wrap a function inside another to allow you to make adjustments to the
* parameters, or do other processing either before the internal function is
* called or with its results.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c)
* @param {Function} fn The function to wrap.
* @param {Function} wrapper The wrapper function.
* @return {Function} The wrapped function.
* @example
*
* var greet = name => 'Hello ' + name;
*
* var shoutedGreet = R.wrap(greet, (gr, name) => gr(name).toUpperCase());
*
* shoutedGreet("Kathy"); //=> "HELLO KATHY"
*
* var shortenedGreet = R.wrap(greet, function(gr, name) {
* return gr(name.substring(0, 3));
* });
* shortenedGreet("Robert"); //=> "Hello Rob"
*/
var wrap = _curry2(function wrap(fn, wrapper) {
return curryN(fn.length, function () {
return wrapper.apply(this, _concat([fn], arguments));
});
});
/**
* Creates a new list out of the two supplied by creating each possible pair
* from the lists.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [b] -> [[a,b]]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The list made by combining each possible pair from
* `as` and `bs` into pairs (`[a, b]`).
* @example
*
* R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
*/
// = xprodWith(prepend); (takes about 3 times as long...)
var xprod = _curry2(function xprod(a, b) {
// = xprodWith(prepend); (takes about 3 times as long...)
var idx = 0;
var ilen = a.length;
var j;
var jlen = b.length;
var result = [];
while (idx < ilen) {
j = 0;
while (j < jlen) {
result[result.length] = [
a[idx],
b[j]
];
j += 1;
}
idx += 1;
}
return result;
});
/**
* Creates a new list out of the two supplied by pairing up equally-positioned
* items from both lists. The returned list is truncated to the length of the
* shorter of the two input lists.
* Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [b] -> [[a,b]]
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
* @example
*
* R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
*/
var zip = _curry2(function zip(a, b) {
var rv = [];
var idx = 0;
var len = Math.min(a.length, b.length);
while (idx < len) {
rv[idx] = [
a[idx],
b[idx]
];
idx += 1;
}
return rv;
});
/**
* Creates a new object out of a list of keys and a list of values.
* Key/value pairing is truncated to the length of the shorter of the two lists.
* Note: `zipObj` is equivalent to `pipe(zipWith(pair), fromPairs)`.
*
* @func
* @memberOf R
* @since v0.3.0
* @category List
* @sig [String] -> [*] -> {String: *}
* @param {Array} keys The array that will be properties on the output object.
* @param {Array} values The list of values on the output object.
* @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`.
* @example
*
* R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3}
*/
var zipObj = _curry2(function zipObj(keys, values) {
var idx = 0;
var len = Math.min(keys.length, values.length);
var out = {};
while (idx < len) {
out[keys[idx]] = values[idx];
idx += 1;
}
return out;
});
/**
* Creates a new list out of the two supplied by applying the function to each
* equally-positioned pair in the lists. The returned list is truncated to the
* length of the shorter of the two input lists.
*
* @function
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a,b -> c) -> [a] -> [b] -> [c]
* @param {Function} fn The function used to combine the two elements into one value.
* @param {Array} list1 The first array to consider.
* @param {Array} list2 The second array to consider.
* @return {Array} The list made by combining same-indexed elements of `list1` and `list2`
* using `fn`.
* @example
*
* var f = (x, y) => {
* // ...
* };
* R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']);
* //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')]
*/
var zipWith = _curry3(function zipWith(fn, a, b) {
var rv = [];
var idx = 0;
var len = Math.min(a.length, b.length);
while (idx < len) {
rv[idx] = fn(a[idx], b[idx]);
idx += 1;
}
return rv;
});
/**
* A function that always returns `false`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Function
* @sig * -> Boolean
* @param {*}
* @return {Boolean}
* @see R.always, R.T
* @example
*
* R.F(); //=> false
*/
var F = always(false);
/**
* A function that always returns `true`. Any passed in parameters are ignored.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Function
* @sig * -> Boolean
* @param {*}
* @return {Boolean}
* @see R.always, R.F
* @example
*
* R.T(); //=> true
*/
var T = always(true);
/**
* Copies an object.
*
* @private
* @param {*} value The value to be copied
* @param {Array} refFrom Array containing the source references
* @param {Array} refTo Array containing the copied source references
* @param {Boolean} deep Whether or not to perform deep cloning.
* @return {*} The copied value.
*/
var _clone = function _clone(value, refFrom, refTo, deep) {
var copy = function copy(copiedValue) {
var len = refFrom.length;
var idx = 0;
while (idx < len) {
if (value === refFrom[idx]) {
return refTo[idx];
}
idx += 1;
}
refFrom[idx + 1] = value;
refTo[idx + 1] = copiedValue;
for (var key in value) {
copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key];
}
return copiedValue;
};
switch (type(value)) {
case 'Object':
return copy({});
case 'Array':
return copy([]);
case 'Date':
return new Date(value.valueOf());
case 'RegExp':
return _cloneRegExp(value);
default:
return value;
}
};
var _createPartialApplicator = function _createPartialApplicator(concat) {
return _curry2(function (fn, args) {
return _arity(Math.max(0, fn.length - args.length), function () {
return fn.apply(this, concat(args, arguments));
});
});
};
var _dropLast = function dropLast(n, xs) {
return take(n < xs.length ? xs.length - n : 0, xs);
};
// Values of other types are only equal if identical.
var _equals = function _equals(a, b, stackA, stackB) {
if (identical(a, b)) {
return true;
}
if (type(a) !== type(b)) {
return false;
}
if (a == null || b == null) {
return false;
}
if (typeof a.equals === 'function' || typeof b.equals === 'function') {
return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a);
}
switch (type(a)) {
case 'Arguments':
case 'Array':
case 'Object':
if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') {
return a === b;
}
break;
case 'Boolean':
case 'Number':
case 'String':
if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) {
return false;
}
break;
case 'Date':
if (!identical(a.valueOf(), b.valueOf())) {
return false;
}
break;
case 'Error':
return a.name === b.name && a.message === b.message;
case 'RegExp':
if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) {
return false;
}
break;
case 'Map':
case 'Set':
if (!_equals(_arrayFromIterator(a.entries()), _arrayFromIterator(b.entries()), stackA, stackB)) {
return false;
}
break;
case 'Int8Array':
case 'Uint8Array':
case 'Uint8ClampedArray':
case 'Int16Array':
case 'Uint16Array':
case 'Int32Array':
case 'Uint32Array':
case 'Float32Array':
case 'Float64Array':
break;
case 'ArrayBuffer':
break;
default:
// Values of other types are only equal if identical.
return false;
}
var keysA = keys(a);
if (keysA.length !== keys(b).length) {
return false;
}
var idx = stackA.length - 1;
while (idx >= 0) {
if (stackA[idx] === a) {
return stackB[idx] === b;
}
idx -= 1;
}
stackA.push(a);
stackB.push(b);
idx = keysA.length - 1;
while (idx >= 0) {
var key = keysA[idx];
if (!(_has(key, b) && _equals(b[key], a[key], stackA, stackB))) {
return false;
}
idx -= 1;
}
stackA.pop();
stackB.pop();
return true;
};
/**
* `_makeFlat` is a helper function that returns a one-level or fully recursive
* function based on the flag passed in.
*
* @private
*/
var _makeFlat = function _makeFlat(recursive) {
return function flatt(list) {
var value, jlen, j;
var result = [];
var idx = 0;
var ilen = list.length;
while (idx < ilen) {
if (isArrayLike(list[idx])) {
value = recursive ? flatt(list[idx]) : list[idx];
j = 0;
jlen = value.length;
while (j < jlen) {
result[result.length] = value[j];
j += 1;
}
} else {
result[result.length] = list[idx];
}
idx += 1;
}
return result;
};
};
var _reduce = function () {
function _arrayReduce(xf, acc, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
acc = xf['@@transducer/step'](acc, list[idx]);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
idx += 1;
}
return xf['@@transducer/result'](acc);
}
function _iterableReduce(xf, acc, iter) {
var step = iter.next();
while (!step.done) {
acc = xf['@@transducer/step'](acc, step.value);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
step = iter.next();
}
return xf['@@transducer/result'](acc);
}
function _methodReduce(xf, acc, obj) {
return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc));
}
var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';
return function _reduce(fn, acc, list) {
if (typeof fn === 'function') {
fn = _xwrap(fn);
}
if (isArrayLike(list)) {
return _arrayReduce(fn, acc, list);
}
if (typeof list.reduce === 'function') {
return _methodReduce(fn, acc, list);
}
if (list[symIterator] != null) {
return _iterableReduce(fn, acc, list[symIterator]());
}
if (typeof list.next === 'function') {
return _iterableReduce(fn, acc, list);
}
throw new TypeError('reduce: list must be array or iterable');
};
}();
var _stepCat = function () {
var _stepCatArray = {
'@@transducer/init': Array,
'@@transducer/step': function (xs, x) {
xs.push(x);
return xs;
},
'@@transducer/result': _identity
};
var _stepCatString = {
'@@transducer/init': String,
'@@transducer/step': function (a, b) {
return a + b;
},
'@@transducer/result': _identity
};
var _stepCatObject = {
'@@transducer/init': Object,
'@@transducer/step': function (result, input) {
return _assign(result, isArrayLike(input) ? objOf(input[0], input[1]) : input);
},
'@@transducer/result': _identity
};
return function _stepCat(obj) {
if (_isTransformer(obj)) {
return obj;
}
if (isArrayLike(obj)) {
return _stepCatArray;
}
if (typeof obj === 'string') {
return _stepCatString;
}
if (typeof obj === 'object') {
return _stepCatObject;
}
throw new Error('Cannot create transformer for ' + obj);
};
}();
var _xdropLastWhile = function () {
function XDropLastWhile(fn, xf) {
this.f = fn;
this.retained = [];
this.xf = xf;
}
XDropLastWhile.prototype['@@transducer/init'] = _xfBase.init;
XDropLastWhile.prototype['@@transducer/result'] = function (result) {
this.retained = null;
return this.xf['@@transducer/result'](result);
};
XDropLastWhile.prototype['@@transducer/step'] = function (result, input) {
return this.f(input) ? this.retain(result, input) : this.flush(result, input);
};
XDropLastWhile.prototype.flush = function (result, input) {
result = _reduce(this.xf['@@transducer/step'], result, this.retained);
this.retained = [];
return this.xf['@@transducer/step'](result, input);
};
XDropLastWhile.prototype.retain = function (result, input) {
this.retained.push(input);
return result;
};
return _curry2(function _xdropLastWhile(fn, xf) {
return new XDropLastWhile(fn, xf);
});
}();
var _xgroupBy = function () {
function XGroupBy(f, xf) {
this.xf = xf;
this.f = f;
this.inputs = {};
}
XGroupBy.prototype['@@transducer/init'] = _xfBase.init;
XGroupBy.prototype['@@transducer/result'] = function (result) {
var key;
for (key in this.inputs) {
if (_has(key, this.inputs)) {
result = this.xf['@@transducer/step'](result, this.inputs[key]);
if (result['@@transducer/reduced']) {
result = result['@@transducer/value'];
break;
}
}
}
this.inputs = null;
return this.xf['@@transducer/result'](result);
};
XGroupBy.prototype['@@transducer/step'] = function (result, input) {
var key = this.f(input);
this.inputs[key] = this.inputs[key] || [
key,
[]
];
this.inputs[key][1] = append(input, this.inputs[key][1]);
return result;
};
return _curry2(function _xgroupBy(f, xf) {
return new XGroupBy(f, xf);
});
}();
/**
* Creates a new list iteration function from an existing one by adding two new
* parameters to its callback function: the current index, and the entire list.
*
* This would turn, for instance, Ramda's simple `map` function into one that
* more closely resembles `Array.prototype.map`. Note that this will only work
* for functions in which the iteration callback function is the first
* parameter, and where the list is the last parameter. (This latter might be
* unimportant if the list parameter is not used.)
*
* @func
* @memberOf R
* @since v0.15.0
* @category Function
* @category List
* @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *)
* @param {Function} fn A list iteration function that does not pass index or list to its callback
* @return {Function} An altered list iteration function that passes (item, index, list) to its callback
* @example
*
* var mapIndexed = R.addIndex(R.map);
* mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']);
* //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r']
*/
var addIndex = _curry1(function addIndex(fn) {
return curryN(fn.length, function () {
var idx = 0;
var origFn = arguments[0];
var list = arguments[arguments.length - 1];
var args = _slice(arguments);
args[0] = function () {
var result = origFn.apply(this, _concat(arguments, [
idx,
list
]));
idx += 1;
return result;
};
return fn.apply(this, args);
});
});
/**
* Wraps a function of any arity (including nullary) in a function that accepts
* exactly 2 parameters. Any extraneous parameters will not be passed to the
* supplied function.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Function
* @sig (* -> c) -> (a, b -> c)
* @param {Function} fn The function to wrap.
* @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of
* arity 2.
* @example
*
* var takesThreeArgs = function(a, b, c) {
* return [a, b, c];
* };
* takesThreeArgs.length; //=> 3
* takesThreeArgs(1, 2, 3); //=> [1, 2, 3]
*
* var takesTwoArgs = R.binary(takesThreeArgs);
* takesTwoArgs.length; //=> 2
* // Only 2 arguments are passed to the wrapped function
* takesTwoArgs(1, 2, 3); //=> [1, 2, undefined]
*/
var binary = _curry1(function binary(fn) {
return nAry(2, fn);
});
/**
* Creates a deep copy of the value which may contain (nested) `Array`s and
* `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are not
* copied, but assigned by their reference.
*
* Dispatches to a `clone` method if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig {*} -> {*}
* @param {*} value The object or array to clone
* @return {*} A new object or array.
* @example
*
* var objects = [{}, {}, {}];
* var objectsClone = R.clone(objects);
* objects[0] === objectsClone[0]; //=> false
*/
var clone = _curry1(function clone(value) {
return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, [], [], true);
});
/**
* Returns a curried equivalent of the provided function. The curried function
* has two unusual capabilities. First, its arguments needn't be provided one
* at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
* following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value `R.__` may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is `R.__`, the
* following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (* -> a) -> (* -> a)
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curryN
* @example
*
* var addFourNumbers = (a, b, c, d) => a + b + c + d;
*
* var curriedAddFourNumbers = R.curry(addFourNumbers);
* var f = curriedAddFourNumbers(1, 2);
* var g = f(3);
* g(4); //=> 10
*/
var curry = _curry1(function curry(fn) {
return curryN(fn.length, fn);
});
/**
* Returns all but the first `n` elements of the given list, string, or
* transducer/transformer (or object with a `drop` method).
*
* Dispatches to the `drop` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n
* @param {*} list
* @return {*}
* @see R.take, R.transduce
* @example
*
* R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
* R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz']
* R.drop(3, ['foo', 'bar', 'baz']); //=> []
* R.drop(4, ['foo', 'bar', 'baz']); //=> []
* R.drop(3, 'ramda'); //=> 'da'
*/
var drop = _curry2(_dispatchable('drop', _xdrop, function drop(n, xs) {
return slice(Math.max(0, n), Infinity, xs);
}));
/**
* Returns a list containing all but the last `n` elements of the given `list`.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n The number of elements of `xs` to skip.
* @param {Array} xs The collection to consider.
* @return {Array}
* @see R.takeLast
* @example
*
* R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']
* R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo']
* R.dropLast(3, ['foo', 'bar', 'baz']); //=> []
* R.dropLast(4, ['foo', 'bar', 'baz']); //=> []
* R.dropLast(3, 'ramda'); //=> 'ra'
*/
var dropLast = _curry2(_dispatchable('dropLast', _xdropLast, _dropLast));
/**
* Returns a new list containing all but last the`n` elements of a given list,
* passing each value from the right to the supplied predicate function,
* skipping elements while the predicate function returns `true`. The predicate
* function is passed one argument: (value)*.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig (a -> Boolean) -> [a] -> [a]
* @param {Function} fn The function called per iteration.
* @param {Array} list The collection to iterate over.
* @return {Array} A new array.
* @see R.takeLastWhile, R.addIndex
* @example
*
* var lteThree = x => x <= 3;
*
* R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4]
*/
var dropLastWhile = _curry2(_dispatchable('dropLastWhile', _xdropLastWhile, _dropLastWhile));
/**
* Returns `true` if its arguments are equivalent, `false` otherwise. Handles
* cyclical data structures.
*
* Dispatches symmetrically to the `equals` methods of both arguments, if
* present.
*
* @func
* @memberOf R
* @since v0.15.0
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* R.equals(1, 1); //=> true
* R.equals(1, '1'); //=> false
* R.equals([1, 2, 3], [1, 2, 3]); //=> true
*
* var a = {}; a.v = a;
* var b = {}; b.v = b;
* R.equals(a, b); //=> true
*/
var equals = _curry2(function equals(a, b) {
return _equals(a, b, [], []);
});
/**
* Takes a predicate and a "filterable", and returns a new filterable of the
* same type containing the members of the given filterable which satisfy the
* given predicate.
*
* Dispatches to the `filter` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Filterable f => (a -> Boolean) -> f a -> f a
* @param {Function} pred
* @param {Array} filterable
* @return {Array}
* @see R.reject, R.transduce, R.addIndex
* @example
*
* var isEven = n => n % 2 === 0;
*
* R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]
*
* R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}
*/
// else
var filter = _curry2(_dispatchable('filter', _xfilter, function (pred, filterable) {
return _isObject(filterable) ? _reduce(function (acc, key) {
if (pred(filterable[key])) {
acc[key] = filterable[key];
}
return acc;
}, {}, keys(filterable)) : // else
_filter(pred, filterable);
}));
/**
* Returns a new list by pulling every item out of it (and all its sub-arrays)
* and putting them in a new array, depth-first.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [b]
* @param {Array} list The array to consider.
* @return {Array} The flattened list.
* @see R.unnest
* @example
*
* R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]);
* //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
var flatten = _curry1(_makeFlat(true));
/**
* Returns a new function much like the supplied one, except that the first two
* arguments' order is reversed.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z)
* @param {Function} fn The function to invoke with its first two parameters reversed.
* @return {*} The result of invoking `fn` with its first two parameters' order reversed.
* @example
*
* var mergeThree = (a, b, c) => [].concat(a, b, c);
*
* mergeThree(1, 2, 3); //=> [1, 2, 3]
*
* R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3]
*/
var flip = _curry1(function flip(fn) {
return curry(function (a, b) {
var args = _slice(arguments);
args[0] = b;
args[1] = a;
return fn.apply(this, args);
});
});
/**
* Returns the first element of the given list or string. In some libraries
* this function is named `first`.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> a | Undefined
* @sig String -> String
* @param {Array|String} list
* @return {*}
* @see R.tail, R.init, R.last
* @example
*
* R.head(['fi', 'fo', 'fum']); //=> 'fi'
* R.head([]); //=> undefined
*
* R.head('abc'); //=> 'a'
* R.head(''); //=> ''
*/
var head = nth(0);
/**
* Returns all but the last element of the given list or string.
*
* @func
* @memberOf R
* @since v0.9.0
* @category List
* @sig [a] -> [a]
* @sig String -> String
* @param {*} list
* @return {*}
* @see R.last, R.head, R.tail
* @example
*
* R.init([1, 2, 3]); //=> [1, 2]
* R.init([1, 2]); //=> [1]
* R.init([1]); //=> []
* R.init([]); //=> []
*
* R.init('abc'); //=> 'ab'
* R.init('ab'); //=> 'a'
* R.init('a'); //=> ''
* R.init(''); //=> ''
*/
var init = slice(0, -1);
/**
* Combines two lists into a set (i.e. no duplicates) composed of those
* elements common to both lists. Duplication is determined according to the
* value returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig (a -> a -> Boolean) -> [*] -> [*] -> [*]
* @param {Function} pred A predicate function that determines whether
* the two supplied elements are equal.
* @param {Array} list1 One list of items to compare
* @param {Array} list2 A second list of items to compare
* @return {Array} A new list containing those elements common to both lists.
* @see R.intersection
* @example
*
* var buffaloSpringfield = [
* {id: 824, name: 'Richie Furay'},
* {id: 956, name: 'Dewey Martin'},
* {id: 313, name: 'Bruce Palmer'},
* {id: 456, name: 'Stephen Stills'},
* {id: 177, name: 'Neil Young'}
* ];
* var csny = [
* {id: 204, name: 'David Crosby'},
* {id: 456, name: 'Stephen Stills'},
* {id: 539, name: 'Graham Nash'},
* {id: 177, name: 'Neil Young'}
* ];
*
* R.intersectionWith(R.eqBy(R.prop('id')), buffaloSpringfield, csny);
* //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}]
*/
var intersectionWith = _curry3(function intersectionWith(pred, list1, list2) {
var lookupList, filteredList;
if (list1.length > list2.length) {
lookupList = list1;
filteredList = list2;
} else {
lookupList = list2;
filteredList = list1;
}
var results = [];
var idx = 0;
while (idx < filteredList.length) {
if (_containsWith(pred, filteredList[idx], lookupList)) {
results[results.length] = filteredList[idx];
}
idx += 1;
}
return uniqWith(pred, results);
});
/**
* Transforms the items of the list with the transducer and appends the
* transformed items to the accumulator using an appropriate iterator function
* based on the accumulator type.
*
* The accumulator can be an array, string, object or a transformer. Iterated
* items will be appended to arrays and concatenated to strings. Objects will
* be merged directly or 2-item arrays will be merged as key, value pairs.
*
* The accumulator can also be a transformer object that provides a 2-arity
* reducing iterator function, step, 0-arity initial value function, init, and
* 1-arity result extraction function result. The step function is used as the
* iterator function in reduce. The result function is used to convert the
* final accumulator into the return type and in most cases is R.identity. The
* init function is used to provide the initial accumulator.
*
* The iteration is performed with R.reduce after initializing the transducer.
*
* @func
* @memberOf R
* @since v0.12.0
* @category List
* @sig a -> (b -> b) -> [c] -> a
* @param {*} acc The initial accumulator value.
* @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var numbers = [1, 2, 3, 4];
* var transducer = R.compose(R.map(R.add(1)), R.take(2));
*
* R.into([], transducer, numbers); //=> [2, 3]
*
* var intoArray = R.into([]);
* intoArray(transducer, numbers); //=> [2, 3]
*/
var into = _curry3(function into(acc, xf, list) {
return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list);
});
/**
* Same as R.invertObj, however this accounts for objects with duplicate values
* by putting the values into an array.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Object
* @sig {s: x} -> {x: [ s, ... ]}
* @param {Object} obj The object or array to invert
* @return {Object} out A new object with keys
* in an array.
* @example
*
* var raceResultsByFirstName = {
* first: 'alice',
* second: 'jake',
* third: 'alice',
* };
* R.invert(raceResultsByFirstName);
* //=> { 'alice': ['first', 'third'], 'jake':['second'] }
*/
var invert = _curry1(function invert(obj) {
var props = keys(obj);
var len = props.length;
var idx = 0;
var out = {};
while (idx < len) {
var key = props[idx];
var val = obj[key];
var list = _has(val, out) ? out[val] : out[val] = [];
list[list.length] = key;
idx += 1;
}
return out;
});
/**
* Returns a new object with the keys of the given object as values, and the
* values of the given object, which are coerced to strings, as keys. Note
* that the last key found is preferred when handling the same value.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Object
* @sig {s: x} -> {x: s}
* @param {Object} obj The object or array to invert
* @return {Object} out A new object
* @example
*
* var raceResults = {
* first: 'alice',
* second: 'jake'
* };
* R.invertObj(raceResults);
* //=> { 'alice': 'first', 'jake':'second' }
*
* // Alternatively:
* var raceResults = ['alice', 'jake'];
* R.invertObj(raceResults);
* //=> { 'alice': '0', 'jake':'1' }
*/
var invertObj = _curry1(function invertObj(obj) {
var props = keys(obj);
var len = props.length;
var idx = 0;
var out = {};
while (idx < len) {
var key = props[idx];
out[obj[key]] = key;
idx += 1;
}
return out;
});
/**
* Returns `true` if the given value is its type's empty value; `false`
* otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Logic
* @sig a -> Boolean
* @param {*} x
* @return {Boolean}
* @see R.empty
* @example
*
* R.isEmpty([1, 2, 3]); //=> false
* R.isEmpty([]); //=> true
* R.isEmpty(''); //=> true
* R.isEmpty(null); //=> false
* R.isEmpty({}); //=> true
* R.isEmpty({length: 0}); //=> false
*/
var isEmpty = _curry1(function isEmpty(x) {
return x != null && equals(x, empty(x));
});
/**
* Returns the last element of the given list or string.
*
* @func
* @memberOf R
* @since v0.1.4
* @category List
* @sig [a] -> a | Undefined
* @sig String -> String
* @param {*} list
* @return {*}
* @see R.init, R.head, R.tail
* @example
*
* R.last(['fi', 'fo', 'fum']); //=> 'fum'
* R.last([]); //=> undefined
*
* R.last('abc'); //=> 'c'
* R.last(''); //=> ''
*/
var last = nth(-1);
/**
* Returns the position of the last occurrence of an item in an array, or -1 if
* the item is not included in the array. `R.equals` is used to determine
* equality.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} xs The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
* @see R.indexOf
* @example
*
* R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6
* R.lastIndexOf(10, [1,2,3,4]); //=> -1
*/
var lastIndexOf = _curry2(function lastIndexOf(target, xs) {
if (typeof xs.lastIndexOf === 'function' && !_isArray(xs)) {
return xs.lastIndexOf(target);
} else {
var idx = xs.length - 1;
while (idx >= 0) {
if (equals(xs[idx], target)) {
return idx;
}
idx -= 1;
}
return -1;
}
});
/**
* Takes a function and
* a [functor](https://github.com/fantasyland/fantasy-land#functor),
* applies the function to each of the functor's values, and returns
* a functor of the same shape.
*
* Ramda provides suitable `map` implementations for `Array` and `Object`,
* so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`.
*
* Dispatches to the `map` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* Also treats functions as functors and will compose them together.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Functor f => (a -> b) -> f a -> f b
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {Array} list The list to be iterated over.
* @return {Array} The new list.
* @see R.transduce, R.addIndex
* @example
*
* var double = x => x * 2;
*
* R.map(double, [1, 2, 3]); //=> [2, 4, 6]
*
* R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}
*/
var map = _curry2(_dispatchable('map', _xmap, function map(fn, functor) {
switch (Object.prototype.toString.call(functor)) {
case '[object Function]':
return curryN(functor.length, function () {
return fn.call(this, functor.apply(this, arguments));
});
case '[object Object]':
return _reduce(function (acc, key) {
acc[key] = fn(functor[key]);
return acc;
}, {}, keys(functor));
default:
return _map(fn, functor);
}
}));
/**
* An Object-specific version of `map`. The function is applied to three
* arguments: *(value, key, obj)*. If only the value is significant, use
* `map` instead.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Object
* @sig ((*, String, Object) -> *) -> Object -> Object
* @param {Function} fn
* @param {Object} obj
* @return {Object}
* @see R.map
* @example
*
* var values = { x: 1, y: 2, z: 3 };
* var prependKeyAndDouble = (num, key, obj) => key + (num * 2);
*
* R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' }
*/
var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) {
return _reduce(function (acc, key) {
acc[key] = fn(obj[key], key, obj);
return acc;
}, {}, keys(obj));
});
/**
* Creates a new object with the own properties of the two provided objects. If
* a key exists in both objects, the provided function is applied to the values
* associated with the key in each object, with the result being used as the
* value associated with the key in the returned object. The key will be
* excluded from the returned object if the resulting value is `undefined`.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Object
* @sig (a -> a -> a) -> {a} -> {a} -> {a}
* @param {Function} fn
* @param {Object} l
* @param {Object} r
* @return {Object}
* @see R.merge, R.mergeWithKey
* @example
*
* R.mergeWith(R.concat,
* { a: true, values: [10, 20] },
* { b: true, values: [15, 35] });
* //=> { a: true, b: true, values: [10, 20, 15, 35] }
*/
var mergeWith = _curry3(function mergeWith(fn, l, r) {
return mergeWithKey(function (_, _l, _r) {
return fn(_l, _r);
}, l, r);
});
/**
* Takes a function `f` and a list of arguments, and returns a function `g`.
* When applied, `g` returns the result of applying `f` to the arguments
* provided initially followed by the arguments provided to `g`.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Function
* @sig ((a, b, c, ..., n) -> x) -> [a, b, c, ...] -> ((d, e, f, ..., n) -> x)
* @param {Function} f
* @param {Array} args
* @return {Function}
* @see R.partialRight
* @example
*
* var multiply = (a, b) => a * b;
* var double = R.partial(multiply, [2]);
* double(2); //=> 4
*
* var greet = (salutation, title, firstName, lastName) =>
* salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
*
* var sayHello = R.partial(greet, ['Hello']);
* var sayHelloToMs = R.partial(sayHello, ['Ms.']);
* sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!'
*/
var partial = _createPartialApplicator(_concat);
/**
* Takes a function `f` and a list of arguments, and returns a function `g`.
* When applied, `g` returns the result of applying `f` to the arguments
* provided to `g` followed by the arguments provided initially.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Function
* @sig ((a, b, c, ..., n) -> x) -> [d, e, f, ..., n] -> ((a, b, c, ...) -> x)
* @param {Function} f
* @param {Array} args
* @return {Function}
* @see R.partial
* @example
*
* var greet = (salutation, title, firstName, lastName) =>
* salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!';
*
* var greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']);
*
* greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!'
*/
var partialRight = _createPartialApplicator(flip(_concat));
/**
* Determines whether a nested path on an object has a specific value, in
* `R.equals` terms. Most likely used to filter a list.
*
* @func
* @memberOf R
* @since v0.7.0
* @category Relation
* @sig [String] -> * -> {String: *} -> Boolean
* @param {Array} path The path of the nested property to use
* @param {*} val The value to compare the nested property with
* @param {Object} obj The object to check the nested property in
* @return {Boolean} `true` if the value equals the nested object property,
* `false` otherwise.
* @example
*
* var user1 = { address: { zipCode: 90210 } };
* var user2 = { address: { zipCode: 55555 } };
* var user3 = { name: 'Bob' };
* var users = [ user1, user2, user3 ];
* var isFamous = R.pathEq(['address', 'zipCode'], 90210);
* R.filter(isFamous, users); //=> [ user1 ]
*/
var pathEq = _curry3(function pathEq(_path, val, obj) {
return equals(path(_path, obj), val);
});
/**
* Returns a new list by plucking the same named property off all objects in
* the list supplied.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig k -> [{k: v}] -> [v]
* @param {Number|String} key The key name to pluck off of each object.
* @param {Array} list The array to consider.
* @return {Array} The list of values for the given key.
* @see R.props
* @example
*
* R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2]
* R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3]
*/
var pluck = _curry2(function pluck(p, list) {
return map(prop(p), list);
});
/**
* Reasonable analog to SQL `select` statement.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @category Relation
* @sig [k] -> [{k: v}] -> [{k: v}]
* @param {Array} props The property names to project
* @param {Array} objs The objects to query
* @return {Array} An array of objects with just the `props` properties.
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2};
* var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7};
* var kids = [abby, fred];
* R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}]
*/
// passing `identity` gives correct arity
var project = useWith(_map, [
pickAll,
identity
]);
/**
* Returns `true` if the specified object property is equal, in `R.equals`
* terms, to the given value; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig String -> a -> Object -> Boolean
* @param {String} name
* @param {*} val
* @param {*} obj
* @return {Boolean}
* @see R.equals, R.propSatisfies
* @example
*
* var abby = {name: 'Abby', age: 7, hair: 'blond'};
* var fred = {name: 'Fred', age: 12, hair: 'brown'};
* var rusty = {name: 'Rusty', age: 10, hair: 'brown'};
* var alois = {name: 'Alois', age: 15, disposition: 'surly'};
* var kids = [abby, fred, rusty, alois];
* var hasBrownHair = R.propEq('hair', 'brown');
* R.filter(hasBrownHair, kids); //=> [fred, rusty]
*/
var propEq = _curry3(function propEq(name, val, obj) {
return propSatisfies(equals(val), name, obj);
});
/**
* Returns `true` if the specified object property is of the given type;
* `false` otherwise.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Type
* @sig Type -> String -> Object -> Boolean
* @param {Function} type
* @param {String} name
* @param {*} obj
* @return {Boolean}
* @see R.is, R.propSatisfies
* @example
*
* R.propIs(Number, 'x', {x: 1, y: 2}); //=> true
* R.propIs(Number, 'x', {x: 'foo'}); //=> false
* R.propIs(Number, 'x', {}); //=> false
*/
var propIs = _curry3(function propIs(type, name, obj) {
return propSatisfies(is(type), name, obj);
});
/**
* Returns a single item by iterating through the list, successively calling
* the iterator function and passing it an accumulator value and the current
* value from the array, and then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*. It may use
* `R.reduced` to shortcut the iteration.
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse
* arrays), unlike the native `Array.prototype.reduce` method. For more details
* on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* Dispatches to the `reduce` method of the third argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig ((a, b) -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.reduced, R.addIndex
* @example
*
* var numbers = [1, 2, 3];
* var add = (a, b) => a + b;
*
* R.reduce(add, 10, numbers); //=> 16
*/
var reduce = _curry3(_reduce);
/**
* Groups the elements of the list according to the result of calling
* the String-returning function `keyFn` on each element and reduces the elements
* of each group to a single value via the reducer function `valueFn`.
*
* This function is basically a more general `groupBy` function.
*
* @func
* @memberOf R
* @since v0.20.0
* @category List
* @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a}
* @param {Function} valueFn The function that reduces the elements of each group to a single
* value. Receives two values, accumulator for a particular group and the current element.
* @param {*} acc The (initial) accumulator value for each group.
* @param {Function} keyFn The function that maps the list's element into a key.
* @param {Array} list The array to group.
* @return {Object} An object with the output of `keyFn` for keys, mapped to the output of
* `valueFn` for elements which produced that key when passed to `keyFn`.
* @see R.groupBy, R.reduce
* @example
*
* var reduceToNamesBy = R.reduceBy((acc, student) => acc.concat(student.name), []);
* var namesByGrade = reduceToNamesBy(function(student) {
* var score = student.score;
* return score < 65 ? 'F' :
* score < 70 ? 'D' :
* score < 80 ? 'C' :
* score < 90 ? 'B' : 'A';
* });
* var students = [{name: 'Lucy', score: 92},
* {name: 'Drew', score: 85},
* // ...
* {name: 'Bart', score: 62}];
* namesByGrade(students);
* // {
* // 'A': ['Lucy'],
* // 'B': ['Drew']
* // // ...,
* // 'F': ['Bart']
* // }
*/
var reduceBy = _curryN(4, [], function reduceBy(valueFn, valueAcc, keyFn, list) {
return _reduce(function (acc, elt) {
var key = keyFn(elt);
acc[key] = valueFn(_has(key, acc) ? acc[key] : valueAcc, elt);
return acc;
}, {}, list);
});
/**
* The complement of `filter`.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig Filterable f => (a -> Boolean) -> f a -> f a
* @param {Function} pred
* @param {Array} filterable
* @return {Array}
* @see R.filter, R.transduce, R.addIndex
* @example
*
* var isOdd = (n) => n % 2 === 1;
*
* R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]
*
* R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}
*/
var reject = _curry2(function reject(pred, filterable) {
return filter(_complement(pred), filterable);
});
/**
* Returns a fixed list of size `n` containing a specified identical value.
*
* @func
* @memberOf R
* @since v0.1.1
* @category List
* @sig a -> n -> [a]
* @param {*} value The value to repeat.
* @param {Number} n The desired size of the output list.
* @return {Array} A new array containing `n` `value`s.
* @example
*
* R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi']
*
* var obj = {};
* var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}]
* repeatedObjs[0] === repeatedObjs[1]; //=> true
*/
var repeat = _curry2(function repeat(value, n) {
return times(always(value), n);
});
/**
* Adds together all the elements of a list.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {Number} The sum of all the numbers in the list.
* @see R.reduce
* @example
*
* R.sum([2,4,6,8,100,1]); //=> 121
*/
var sum = reduce(add, 0);
/**
* Returns a new list containing the last `n` elements of the given list.
* If `n > list.length`, returns a list of `list.length` elements.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig Number -> [a] -> [a]
* @sig Number -> String -> String
* @param {Number} n The number of elements to return.
* @param {Array} xs The collection to consider.
* @return {Array}
* @see R.dropLast
* @example
*
* R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz']
* R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz']
* R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']
* R.takeLast(3, 'ramda'); //=> 'mda'
*/
var takeLast = _curry2(function takeLast(n, xs) {
return drop(n >= 0 ? xs.length - n : 0, xs);
});
/**
* Initializes a transducer using supplied iterator function. Returns a single
* item by iterating through the list, successively calling the transformed
* iterator function and passing it an accumulator value and the current value
* from the array, and then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*. It will be
* wrapped as a transformer to initialize the transducer. A transformer can be
* passed directly in place of an iterator function. In both cases, iteration
* may be stopped early with the `R.reduced` function.
*
* A transducer is a function that accepts a transformer and returns a
* transformer and can be composed directly.
*
* A transformer is an an object that provides a 2-arity reducing iterator
* function, step, 0-arity initial value function, init, and 1-arity result
* extraction function, result. The step function is used as the iterator
* function in reduce. The result function is used to convert the final
* accumulator into the return type and in most cases is R.identity. The init
* function can be used to provide an initial accumulator, but is ignored by
* transduce.
*
* The iteration is performed with R.reduce after initializing the transducer.
*
* @func
* @memberOf R
* @since v0.12.0
* @category List
* @sig (c -> c) -> (a,b -> a) -> a -> [b] -> a
* @param {Function} xf The transducer function. Receives a transformer and returns a transformer.
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array. Wrapped as transformer, if necessary, and used to
* initialize the transducer
* @param {*} acc The initial accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.reduce, R.reduced, R.into
* @example
*
* var numbers = [1, 2, 3, 4];
* var transducer = R.compose(R.map(R.add(1)), R.take(2));
*
* R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3]
*/
var transduce = curryN(4, function transduce(xf, fn, acc, list) {
return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list);
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements
* of each list. Duplication is determined according to the value returned by
* applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig (a -> a -> Boolean) -> [*] -> [*] -> [*]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @see R.union
* @example
*
* var l1 = [{a: 1}, {a: 2}];
* var l2 = [{a: 1}, {a: 4}];
* R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}]
*/
var unionWith = _curry3(function unionWith(pred, list1, list2) {
return uniqWith(pred, _concat(list1, list2));
});
/**
* Takes a spec object and a test object; returns true if the test satisfies
* the spec, false otherwise. An object satisfies the spec if, for each of the
* spec's own properties, accessing that property of the object gives the same
* value (in `R.equals` terms) as accessing that property of the spec.
*
* `whereEq` is a specialization of [`where`](#where).
*
* @func
* @memberOf R
* @since v0.14.0
* @category Object
* @sig {String: *} -> {String: *} -> Boolean
* @param {Object} spec
* @param {Object} testObj
* @return {Boolean}
* @see R.where
* @example
*
* // pred :: Object -> Boolean
* var pred = R.whereEq({a: 1, b: 2});
*
* pred({a: 1}); //=> false
* pred({a: 1, b: 2}); //=> true
* pred({a: 1, b: 2, c: 3}); //=> true
* pred({a: 1, b: 1}); //=> false
*/
var whereEq = _curry2(function whereEq(spec, testObj) {
return where(map(equals, spec), testObj);
});
var _flatCat = function () {
var preservingReduced = function (xf) {
return {
'@@transducer/init': _xfBase.init,
'@@transducer/result': function (result) {
return xf['@@transducer/result'](result);
},
'@@transducer/step': function (result, input) {
var ret = xf['@@transducer/step'](result, input);
return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret;
}
};
};
return function _xcat(xf) {
var rxf = preservingReduced(xf);
return {
'@@transducer/init': _xfBase.init,
'@@transducer/result': function (result) {
return rxf['@@transducer/result'](result);
},
'@@transducer/step': function (result, input) {
return !isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input);
}
};
};
}();
// Array.prototype.indexOf doesn't exist below IE9
// manually crawl the list to distinguish between +0 and -0
// NaN
// non-zero numbers can utilise Set
// all these types can utilise Set
// null can utilise Set
// anything else not covered above, defer to R.equals
var _indexOf = function _indexOf(list, a, idx) {
var inf, item;
// Array.prototype.indexOf doesn't exist below IE9
if (typeof list.indexOf === 'function') {
switch (typeof a) {
case 'number':
if (a === 0) {
// manually crawl the list to distinguish between +0 and -0
inf = 1 / a;
while (idx < list.length) {
item = list[idx];
if (item === 0 && 1 / item === inf) {
return idx;
}
idx += 1;
}
return -1;
} else if (a !== a) {
// NaN
while (idx < list.length) {
item = list[idx];
if (typeof item === 'number' && item !== item) {
return idx;
}
idx += 1;
}
return -1;
}
// non-zero numbers can utilise Set
return list.indexOf(a, idx);
// all these types can utilise Set
case 'string':
case 'boolean':
case 'function':
case 'undefined':
return list.indexOf(a, idx);
case 'object':
if (a === null) {
// null can utilise Set
return list.indexOf(a, idx);
}
}
}
// anything else not covered above, defer to R.equals
while (idx < list.length) {
if (equals(list[idx], a)) {
return idx;
}
idx += 1;
}
return -1;
};
var _xchain = _curry2(function _xchain(f, xf) {
return map(f, _flatCat(xf));
});
/**
* Takes a list of predicates and returns a predicate that returns true for a
* given list of arguments if every one of the provided predicates is satisfied
* by those arguments.
*
* The function returned is a curried function whose arity matches that of the
* highest-arity predicate.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} preds
* @return {Function}
* @see R.anyPass
* @example
*
* var isQueen = R.propEq('rank', 'Q');
* var isSpade = R.propEq('suit', '♠︎');
* var isQueenOfSpades = R.allPass([isQueen, isSpade]);
*
* isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false
* isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true
*/
var allPass = _curry1(function allPass(preds) {
return curryN(reduce(max, 0, pluck('length', preds)), function () {
var idx = 0;
var len = preds.length;
while (idx < len) {
if (!preds[idx].apply(this, arguments)) {
return false;
}
idx += 1;
}
return true;
});
});
/**
* Returns `true` if all elements are unique, in `R.equals` terms, otherwise
* `false`.
*
* @func
* @memberOf R
* @since v0.18.0
* @category List
* @sig [a] -> Boolean
* @param {Array} list The array to consider.
* @return {Boolean} `true` if all elements are unique, else `false`.
* @deprecated since v0.20.0
* @example
*
* R.allUniq(['1', 1]); //=> true
* R.allUniq([1, 1]); //=> false
* R.allUniq([[42], [42]]); //=> false
*/
var allUniq = _curry1(function allUniq(list) {
var len = list.length;
var idx = 0;
while (idx < len) {
if (_indexOf(list, list[idx], idx + 1) >= 0) {
return false;
}
idx += 1;
}
return true;
});
/**
* Takes a list of predicates and returns a predicate that returns true for a
* given list of arguments if at least one of the provided predicates is
* satisfied by those arguments.
*
* The function returned is a curried function whose arity matches that of the
* highest-arity predicate.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Logic
* @sig [(*... -> Boolean)] -> (*... -> Boolean)
* @param {Array} preds
* @return {Function}
* @see R.allPass
* @example
*
* var gte = R.anyPass([R.gt, R.equals]);
*
* gte(3, 2); //=> true
* gte(2, 2); //=> true
* gte(2, 3); //=> false
*/
var anyPass = _curry1(function anyPass(preds) {
return curryN(reduce(max, 0, pluck('length', preds)), function () {
var idx = 0;
var len = preds.length;
while (idx < len) {
if (preds[idx].apply(this, arguments)) {
return true;
}
idx += 1;
}
return false;
});
});
/**
* ap applies a list of functions to a list of values.
*
* Dispatches to the `ap` method of the second argument, if present. Also
* treats functions as applicatives.
*
* @func
* @memberOf R
* @since v0.3.0
* @category Function
* @sig [f] -> [a] -> [f a]
* @param {Array} fns An array of functions
* @param {Array} vs An array of values
* @return {Array} An array of results of applying each of `fns` to all of `vs` in turn.
* @example
*
* R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6]
*/
// else
var ap = _curry2(function ap(applicative, fn) {
return typeof applicative.ap === 'function' ? applicative.ap(fn) : typeof applicative === 'function' ? curryN(Math.max(applicative.length, fn.length), function () {
return applicative.apply(this, arguments)(fn.apply(this, arguments));
}) : // else
_reduce(function (acc, f) {
return _concat(acc, map(f, fn));
}, [], applicative);
});
/**
* Given a spec object recursively mapping properties to functions, creates a
* function producing an object of the same structure, by mapping each property
* to the result of calling its associated function with the supplied arguments.
*
* @func
* @memberOf R
* @since v0.20.0
* @category Function
* @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v})
* @param {Object} spec an object recursively mapping properties to functions for
* producing the values for these properties.
* @return {Function} A function that returns an object of the same structure
* as `spec', with each property set to the value returned by calling its
* associated function with the supplied arguments.
* @see R.juxt
* @example
*
* var getMetrics = R.applySpec({
* sum: R.add,
* nested: { mul: R.multiply }
* });
* getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }
*/
var applySpec = _curry1(function applySpec(spec) {
spec = map(function (v) {
return typeof v == 'function' ? v : applySpec(v);
}, spec);
return curryN(reduce(max, 0, pluck('length', values(spec))), function () {
var args = arguments;
return map(function (f) {
return apply(f, args);
}, spec);
});
});
/**
* Returns the result of calling its first argument with the remaining
* arguments. This is occasionally useful as a converging function for
* `R.converge`: the left branch can produce a function while the right branch
* produces a value to be passed to that function as an argument.
*
* @func
* @memberOf R
* @since v0.9.0
* @category Function
* @sig (*... -> a),*... -> a
* @param {Function} fn The function to apply to the remaining arguments.
* @param {...*} args Any number of positional arguments.
* @return {*}
* @see R.apply
* @example
*
* var indentN = R.pipe(R.times(R.always(' ')),
* R.join(''),
* R.replace(/^(?!$)/gm));
*
* var format = R.converge(R.call, [
* R.pipe(R.prop('indent'), indentN),
* R.prop('value')
* ]);
*
* format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n'
*/
var call = curry(function call(fn) {
return fn.apply(this, _slice(arguments, 1));
});
/**
* `chain` maps a function over a list and concatenates the results. `chain`
* is also known as `flatMap` in some libraries
*
* Dispatches to the `chain` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.3.0
* @category List
* @sig (a -> [b]) -> [a] -> [b]
* @param {Function} fn
* @param {Array} list
* @return {Array}
* @example
*
* var duplicate = n => [n, n];
* R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]
*/
var chain = _curry2(_dispatchable('chain', _xchain, function chain(fn, monad) {
if (typeof monad === 'function') {
return function () {
return monad.call(this, fn.apply(this, arguments)).apply(this, arguments);
};
}
return _makeFlat(false)(map(fn, monad));
}));
/**
* Returns a function, `fn`, which encapsulates if/else-if/else logic.
* `R.cond` takes a list of [predicate, transform] pairs. All of the arguments
* to `fn` are applied to each of the predicates in turn until one returns a
* "truthy" value, at which point `fn` returns the result of applying its
* arguments to the corresponding transformer. If none of the predicates
* matches, `fn` returns undefined.
*
* @func
* @memberOf R
* @since v0.6.0
* @category Logic
* @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *)
* @param {Array} pairs
* @return {Function}
* @example
*
* var fn = R.cond([
* [R.equals(0), R.always('water freezes at 0°C')],
* [R.equals(100), R.always('water boils at 100°C')],
* [R.T, temp => 'nothing special happens at ' + temp + '°C']
* ]);
* fn(0); //=> 'water freezes at 0°C'
* fn(50); //=> 'nothing special happens at 50°C'
* fn(100); //=> 'water boils at 100°C'
*/
var cond = _curry1(function cond(pairs) {
var arity = reduce(max, 0, map(function (pair) {
return pair[0].length;
}, pairs));
return _arity(arity, function () {
var idx = 0;
while (idx < pairs.length) {
if (pairs[idx][0].apply(this, arguments)) {
return pairs[idx][1].apply(this, arguments);
}
idx += 1;
}
});
});
/**
* Wraps a constructor function inside a curried function that can be called
* with the same arguments and returns the same type. The arity of the function
* returned is specified to allow using variadic constructor functions.
*
* @func
* @memberOf R
* @since v0.4.0
* @category Function
* @sig Number -> (* -> {*}) -> (* -> {*})
* @param {Number} n The arity of the constructor function.
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Variadic constructor function
* var Widget = () => {
* this.children = Array.prototype.slice.call(arguments);
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = [
* // ...
* ];
* R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets
*/
var constructN = _curry2(function constructN(n, Fn) {
if (n > 10) {
throw new Error('Constructor with greater than ten arguments');
}
if (n === 0) {
return function () {
return new Fn();
};
}
return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {
switch (arguments.length) {
case 1:
return new Fn($0);
case 2:
return new Fn($0, $1);
case 3:
return new Fn($0, $1, $2);
case 4:
return new Fn($0, $1, $2, $3);
case 5:
return new Fn($0, $1, $2, $3, $4);
case 6:
return new Fn($0, $1, $2, $3, $4, $5);
case 7:
return new Fn($0, $1, $2, $3, $4, $5, $6);
case 8:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7);
case 9:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8);
case 10:
return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9);
}
}));
});
/**
* Accepts a converging function and a list of branching functions and returns
* a new function. When invoked, this new function is applied to some
* arguments, each branching function is applied to those same arguments. The
* results of each branching function are passed as arguments to the converging
* function to produce the return value.
*
* @func
* @memberOf R
* @since v0.4.2
* @category Function
* @sig (x1 -> x2 -> ... -> z) -> [(a -> b -> ... -> x1), (a -> b -> ... -> x2), ...] -> (a -> b -> ... -> z)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {Array} functions A list of functions.
* @return {Function} A new function.
* @example
*
* var add = (a, b) => a + b;
* var multiply = (a, b) => a * b;
* var subtract = (a, b) => a - b;
*
* //≅ multiply( add(1, 2), subtract(1, 2) );
* R.converge(multiply, [add, subtract])(1, 2); //=> -3
*
* var add3 = (a, b, c) => a + b + c;
* R.converge(add3, [multiply, add, subtract])(1, 2); //=> 4
*/
var converge = _curry2(function converge(after, fns) {
return curryN(reduce(max, 0, pluck('length', fns)), function () {
var args = arguments;
var context = this;
return after.apply(context, _map(function (fn) {
return fn.apply(context, args);
}, fns));
});
});
/**
* Counts the elements of a list according to how many match each value of a
* key generated by the supplied function. Returns an object mapping the keys
* produced by `fn` to the number of occurrences in the list. Note that all
* keys are coerced to strings because of how JavaScript objects work.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig (a -> String) -> [a] -> {*}
* @param {Function} fn The function used to map values to keys.
* @param {Array} list The list to count elements from.
* @return {Object} An object mapping keys to number of occurrences in the list.
* @example
*
* var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2];
* var letters = R.split('', 'abcABCaaaBBc');
* R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1}
* R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3}
*/
var countBy = reduceBy(function (acc, elem) {
return acc + 1;
}, 0);
/**
* Returns a new list without any consecutively repeating elements. Equality is
* determined by applying the supplied predicate two consecutive elements. The
* first element in a series of equal element is the one being preserved.
*
* Dispatches to the `dropRepeatsWith` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.14.0
* @category List
* @sig (a, a -> Boolean) -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list The array to consider.
* @return {Array} `list` without repeating elements.
* @see R.transduce
* @example
*
* var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3];
* R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3]
*/
var dropRepeatsWith = _curry2(_dispatchable('dropRepeatsWith', _xdropRepeatsWith, function dropRepeatsWith(pred, list) {
var result = [];
var idx = 1;
var len = list.length;
if (len !== 0) {
result[0] = list[0];
while (idx < len) {
if (!pred(last(result), list[idx])) {
result[result.length] = list[idx];
}
idx += 1;
}
}
return result;
}));
/**
* Takes a function and two values in its domain and returns `true` if the
* values map to the same value in the codomain; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.18.0
* @category Relation
* @sig (a -> b) -> a -> a -> Boolean
* @param {Function} f
* @param {*} x
* @param {*} y
* @return {Boolean}
* @example
*
* R.eqBy(Math.abs, 5, -5); //=> true
*/
var eqBy = _curry3(function eqBy(f, x, y) {
return equals(f(x), f(y));
});
/**
* Reports whether two objects have the same value, in `R.equals` terms, for
* the specified property. Useful as a curried predicate.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig k -> {k: v} -> {k: v} -> Boolean
* @param {String} prop The name of the property to compare
* @param {Object} obj1
* @param {Object} obj2
* @return {Boolean}
*
* @example
*
* var o1 = { a: 1, b: 2, c: 3, d: 4 };
* var o2 = { a: 10, b: 20, c: 3, d: 40 };
* R.eqProps('a', o1, o2); //=> false
* R.eqProps('c', o1, o2); //=> true
*/
var eqProps = _curry3(function eqProps(prop, obj1, obj2) {
return equals(obj1[prop], obj2[prop]);
});
/**
* Splits a list into sub-lists stored in an object, based on the result of
* calling a String-returning function on each element, and grouping the
* results according to values returned.
*
* Dispatches to the `groupBy` method of the second argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a -> String) -> [a] -> {String: [a]}
* @param {Function} fn Function :: a -> String
* @param {Array} list The array to group
* @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements
* that produced that key when passed to `fn`.
* @see R.transduce
* @example
*
* var byGrade = R.groupBy(function(student) {
* var score = student.score;
* return score < 65 ? 'F' :
* score < 70 ? 'D' :
* score < 80 ? 'C' :
* score < 90 ? 'B' : 'A';
* });
* var students = [{name: 'Abby', score: 84},
* {name: 'Eddy', score: 58},
* // ...
* {name: 'Jack', score: 69}];
* byGrade(students);
* // {
* // 'A': [{name: 'Dianne', score: 99}],
* // 'B': [{name: 'Abby', score: 84}]
* // // ...,
* // 'F': [{name: 'Eddy', score: 58}]
* // }
*/
var groupBy = _curry2(_dispatchable('groupBy', _xgroupBy, reduceBy(function (acc, item) {
if (acc == null) {
acc = [];
}
acc.push(item);
return acc;
}, null)));
/**
* Given a function that generates a key, turns a list of objects into an
* object indexing the objects by the given key. Note that if multiple
* objects generate the same value for the indexing key only the last value
* will be included in the generated object.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig (a -> String) -> [{k: v}] -> {k: {k: v}}
* @param {Function} fn Function :: a -> String
* @param {Array} array The array of objects to index
* @return {Object} An object indexing each array element by the given property.
* @example
*
* var list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}];
* R.indexBy(R.prop('id'), list);
* //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}}
*/
var indexBy = reduceBy(function (acc, elem) {
return elem;
}, null);
/**
* Returns the position of the first occurrence of an item in an array, or -1
* if the item is not included in the array. `R.equals` is used to determine
* equality.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig a -> [a] -> Number
* @param {*} target The item to find.
* @param {Array} xs The array to search in.
* @return {Number} the index of the target, or -1 if the target is not found.
* @see R.lastIndexOf
* @example
*
* R.indexOf(3, [1,2,3,4]); //=> 2
* R.indexOf(10, [1,2,3,4]); //=> -1
*/
var indexOf = _curry2(function indexOf(target, xs) {
return typeof xs.indexOf === 'function' && !_isArray(xs) ? xs.indexOf(target) : _indexOf(xs, target, 0);
});
/**
* juxt applies a list of functions to a list of values.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Function
* @sig [(a, b, ..., m) -> n] -> ((a, b, ..., m) -> [n])
* @param {Array} fns An array of functions
* @return {Function} A function that returns a list of values after applying each of the original `fns` to its parameters.
* @see R.applySpec
* @example
*
* var range = R.juxt([Math.min, Math.max]);
* range(3, 4, 9, -3); //=> [-3, 9]
*/
var juxt = _curry1(function juxt(fns) {
return converge(_arrayOf, fns);
});
/**
* Returns a lens for the given getter and setter functions. The getter "gets"
* the value of the focus; the setter "sets" the value of the focus. The setter
* should not mutate the data structure.
*
* @func
* @memberOf R
* @since v0.8.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig (s -> a) -> ((a, s) -> s) -> Lens s a
* @param {Function} getter
* @param {Function} setter
* @return {Lens}
* @see R.view, R.set, R.over, R.lensIndex, R.lensProp
* @example
*
* var xLens = R.lens(R.prop('x'), R.assoc('x'));
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
*/
var lens = _curry2(function lens(getter, setter) {
return function (toFunctorFn) {
return function (target) {
return map(function (focus) {
return setter(focus, target);
}, toFunctorFn(getter(target)));
};
};
});
/**
* Returns a lens whose focus is the specified index.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig Number -> Lens s a
* @param {Number} n
* @return {Lens}
* @see R.view, R.set, R.over
* @example
*
* var headLens = R.lensIndex(0);
*
* R.view(headLens, ['a', 'b', 'c']); //=> 'a'
* R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c']
* R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c']
*/
var lensIndex = _curry1(function lensIndex(n) {
return lens(nth(n), update(n));
});
/**
* Returns a lens whose focus is the specified path.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig [String] -> Lens s a
* @param {Array} path The path to use.
* @return {Lens}
* @see R.view, R.set, R.over
* @example
*
* var xyLens = R.lensPath(['x', 'y']);
*
* R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2
* R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}}
* R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}}
*/
var lensPath = _curry1(function lensPath(p) {
return lens(path(p), assocPath(p));
});
/**
* Returns a lens whose focus is the specified property.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Object
* @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s
* @sig String -> Lens s a
* @param {String} k
* @return {Lens}
* @see R.view, R.set, R.over
* @example
*
* var xLens = R.lensProp('x');
*
* R.view(xLens, {x: 1, y: 2}); //=> 1
* R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}
* R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}
*/
var lensProp = _curry1(function lensProp(k) {
return lens(prop(k), assoc(k));
});
/**
* "lifts" a function to be the specified arity, so that it may "map over" that
* many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
*
* @func
* @memberOf R
* @since v0.7.0
* @category Function
* @sig Number -> (*... -> *) -> ([*]... -> [*])
* @param {Function} fn The function to lift into higher context
* @return {Function} The lifted function.
* @see R.lift, R.ap
* @example
*
* var madd3 = R.liftN(3, R.curryN(3, (...args) => R.sum(args)));
* madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
*/
var liftN = _curry2(function liftN(arity, fn) {
var lifted = curryN(arity, fn);
return curryN(arity, function () {
return _reduce(ap, map(lifted, arguments[0]), _slice(arguments, 1));
});
});
/**
* Returns the mean of the given list of numbers.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Math
* @sig [Number] -> Number
* @param {Array} list
* @return {Number}
* @example
*
* R.mean([2, 7, 9]); //=> 6
* R.mean([]); //=> NaN
*/
var mean = _curry1(function mean(list) {
return sum(list) / list.length;
});
/**
* Returns the median of the given list of numbers.
*
* @func
* @memberOf R
* @since v0.14.0
* @category Math
* @sig [Number] -> Number
* @param {Array} list
* @return {Number}
* @example
*
* R.median([2, 9, 7]); //=> 7
* R.median([7, 2, 10, 9]); //=> 8
* R.median([]); //=> NaN
*/
var median = _curry1(function median(list) {
var len = list.length;
if (len === 0) {
return NaN;
}
var width = 2 - len % 2;
var idx = (len - width) / 2;
return mean(_slice(list).sort(function (a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}).slice(idx, idx + width));
});
/**
* Takes a predicate and a list or other "filterable" object and returns the
* pair of filterable objects of the same type of elements which do and do not
* satisfy, the predicate, respectively.
*
* @func
* @memberOf R
* @since v0.1.4
* @category List
* @sig Filterable f => (a -> Boolean) -> f a -> [f a, f a]
* @param {Function} pred A predicate to determine which side the element belongs to.
* @param {Array} filterable the list (or other filterable) to partition.
* @return {Array} An array, containing first the subset of elements that satisfy the
* predicate, and second the subset of elements that do not satisfy.
* @see R.filter, R.reject
* @example
*
* R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']);
* // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]
*
* R.partition(R.contains('s'), { a: 'sss', b: 'ttt', foo: 'bars' });
* // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ]
*/
var partition = juxt([
filter,
reject
]);
/**
* Performs left-to-right function composition. The leftmost function may have
* any arity; the remaining functions must be unary.
*
* In some libraries this function is named `sequence`.
*
* **Note:** The result of pipe is not automatically curried.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
* @param {...Function} functions
* @return {Function}
* @see R.compose
* @example
*
* var f = R.pipe(Math.pow, R.negate, R.inc);
*
* f(3, 4); // -(3^4) + 1
*/
var pipe = function pipe() {
if (arguments.length === 0) {
throw new Error('pipe requires at least one argument');
}
return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments)));
};
/**
* Performs left-to-right composition of one or more Promise-returning
* functions. The leftmost function may have any arity; the remaining functions
* must be unary.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Function
* @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z)
* @param {...Function} functions
* @return {Function}
* @see R.composeP
* @example
*
* // followersForUser :: String -> Promise [User]
* var followersForUser = R.pipeP(db.getUserById, db.getFollowers);
*/
var pipeP = function pipeP() {
if (arguments.length === 0) {
throw new Error('pipeP requires at least one argument');
}
return _arity(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments)));
};
/**
* Multiplies together all the elements of a list.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Math
* @sig [Number] -> Number
* @param {Array} list An array of numbers
* @return {Number} The product of all the numbers in the list.
* @see R.reduce
* @example
*
* R.product([2,4,6,8,100,1]); //=> 38400
*/
var product = reduce(multiply, 1);
/**
* Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable)
* of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an
* Applicative of Traversable.
*
* Dispatches to the `sequence` method of the second argument, if present.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a)
* @param {Function} of
* @param {*} traversable
* @return {*}
* @see R.traverse
* @example
*
* R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3])
* R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing()
*
* R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)]
* R.sequence(R.of, Nothing()); //=> [Nothing()]
*/
var sequence = _curry2(function sequence(of, traversable) {
return typeof traversable.sequence === 'function' ? traversable.sequence(of) : reduceRight(function (acc, x) {
return ap(map(prepend, x), acc);
}, of([]), traversable);
});
/**
* Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning
* function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable),
* then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative
* into an Applicative of Traversable.
*
* Dispatches to the `sequence` method of the third argument, if present.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b)
* @param {Function} of
* @param {Function} f
* @param {*} traversable
* @return {*}
* @see R.sequence
* @example
*
* // Returns `Nothing` if the given divisor is `0`
* safeDiv = n => d => d === 0 ? Nothing() : Just(n / d)
*
* R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Just([5, 2.5, 2])
* R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Nothing
*/
var traverse = _curry3(function traverse(of, f, traversable) {
return sequence(of, map(f, traversable));
});
/**
* Shorthand for `R.chain(R.identity)`, which removes one level of nesting from
* any [Chain](https://github.com/fantasyland/fantasy-land#chain).
*
* @func
* @memberOf R
* @since v0.3.0
* @category List
* @sig Chain c => c (c a) -> c a
* @param {*} list
* @return {*}
* @see R.flatten, R.chain
* @example
*
* R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]]
* R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6]
*/
var unnest = chain(_identity);
var _contains = function _contains(a, list) {
return _indexOf(list, a, 0) >= 0;
};
// mapPairs :: (Object, [String]) -> [String]
var _toString = function _toString(x, seen) {
var recur = function recur(y) {
var xs = seen.concat([x]);
return _contains(y, xs) ? '<Circular>' : _toString(y, xs);
};
// mapPairs :: (Object, [String]) -> [String]
var mapPairs = function (obj, keys) {
return _map(function (k) {
return _quote(k) + ': ' + recur(obj[k]);
}, keys.slice().sort());
};
switch (Object.prototype.toString.call(x)) {
case '[object Arguments]':
return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))';
case '[object Array]':
return '[' + _map(recur, x).concat(mapPairs(x, reject(function (k) {
return /^\d+$/.test(k);
}, keys(x)))).join(', ') + ']';
case '[object Boolean]':
return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString();
case '[object Date]':
return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')';
case '[object Null]':
return 'null';
case '[object Number]':
return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10);
case '[object String]':
return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x);
case '[object Undefined]':
return 'undefined';
default:
if (typeof x.toString === 'function') {
var repr = x.toString();
if (repr !== '[object Object]') {
return repr;
}
}
return '{' + mapPairs(x, keys(x)).join(', ') + '}';
}
};
/**
* Performs right-to-left function composition. The rightmost function may have
* any arity; the remaining functions must be unary.
*
* **Note:** The result of compose is not automatically curried.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z)
* @param {...Function} functions
* @return {Function}
* @see R.pipe
* @example
*
* var f = R.compose(R.inc, R.negate, Math.pow);
*
* f(3, 4); // -(3^4) + 1
*/
var compose = function compose() {
if (arguments.length === 0) {
throw new Error('compose requires at least one argument');
}
return pipe.apply(this, reverse(arguments));
};
/**
* Returns the right-to-left Kleisli composition of the provided functions,
* each of which must return a value of a type supported by [`chain`](#chain).
*
* `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), R.chain(f))`.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Function
* @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (m a -> m z)
* @param {...Function}
* @return {Function}
* @see R.pipeK
* @example
*
* // parseJson :: String -> Maybe *
* // get :: String -> Object -> Maybe *
*
* // getStateCode :: Maybe String -> Maybe String
* var getStateCode = R.composeK(
* R.compose(Maybe.of, R.toUpper),
* get('state'),
* get('address'),
* get('user'),
* parseJson
* );
*
* getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}'));
* //=> Just('NY')
* getStateCode(Maybe.of('[Invalid JSON]'));
* //=> Nothing()
*/
var composeK = function composeK() {
return compose.apply(this, prepend(identity, map(chain, arguments)));
};
/**
* Performs right-to-left composition of one or more Promise-returning
* functions. The rightmost function may have any arity; the remaining
* functions must be unary.
*
* @func
* @memberOf R
* @since v0.10.0
* @category Function
* @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z)
* @param {...Function} functions
* @return {Function}
* @see R.pipeP
* @example
*
* // followersForUser :: String -> Promise [User]
* var followersForUser = R.composeP(db.getFollowers, db.getUserById);
*/
var composeP = function composeP() {
if (arguments.length === 0) {
throw new Error('composeP requires at least one argument');
}
return pipeP.apply(this, reverse(arguments));
};
/**
* Wraps a constructor function inside a curried function that can be called
* with the same arguments and returns the same type.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (* -> {*}) -> (* -> {*})
* @param {Function} Fn The constructor function to wrap.
* @return {Function} A wrapped, curried constructor function.
* @example
*
* // Constructor function
* var Widget = config => {
* // ...
* };
* Widget.prototype = {
* // ...
* };
* var allConfigs = [
* // ...
* ];
* R.map(R.construct(Widget), allConfigs); // a list of Widgets
*/
var construct = _curry1(function construct(Fn) {
return constructN(Fn.length, Fn);
});
/**
* Returns `true` if the specified value is equal, in `R.equals` terms, to at
* least one element of the given list; `false` otherwise.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig a -> [a] -> Boolean
* @param {Object} a The item to compare against.
* @param {Array} list The array to consider.
* @return {Boolean} `true` if the item is in the list, `false` otherwise.
* @see R.any
* @example
*
* R.contains(3, [1, 2, 3]); //=> true
* R.contains(4, [1, 2, 3]); //=> false
* R.contains([42], [[42]]); //=> true
*/
var contains = _curry2(_contains);
/**
* Finds the set (i.e. no duplicates) of all elements in the first list not
* contained in the second list.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig [*] -> [*] -> [*]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` that are not in `list2`.
* @see R.differenceWith
* @example
*
* R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]
* R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]
*/
var difference = _curry2(function difference(first, second) {
var out = [];
var idx = 0;
var firstLen = first.length;
while (idx < firstLen) {
if (!_contains(first[idx], second) && !_contains(first[idx], out)) {
out[out.length] = first[idx];
}
idx += 1;
}
return out;
});
/**
* Returns a new list without any consecutively repeating elements. `R.equals`
* is used to determine equality.
*
* Dispatches to the `dropRepeats` method of the first argument, if present.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.14.0
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} `list` without repeating elements.
* @see R.transduce
* @example
*
* R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2]
*/
var dropRepeats = _curry1(_dispatchable('dropRepeats', _xdropRepeatsWith(equals), dropRepeatsWith(equals)));
/**
* "lifts" a function of arity > 1 so that it may "map over" a list, Function or other
* object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply).
*
* @func
* @memberOf R
* @since v0.7.0
* @category Function
* @sig (*... -> *) -> ([*]... -> [*])
* @param {Function} fn The function to lift into higher context
* @return {Function} The lifted function.
* @see R.liftN
* @example
*
* var madd3 = R.lift(R.curry((a, b, c) => a + b + c));
*
* madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7]
*
* var madd5 = R.lift(R.curry((a, b, c, d, e) => a + b + c + d + e));
*
* madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24]
*/
var lift = _curry1(function lift(fn) {
return liftN(fn.length, fn);
});
/**
* Returns a partial copy of an object omitting the keys specified.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig [String] -> {String: *} -> {String: *}
* @param {Array} names an array of String property names to omit from the new object
* @param {Object} obj The object to copy from
* @return {Object} A new object with properties from `names` not on it.
* @see R.pick
* @example
*
* R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}
*/
var omit = _curry2(function omit(names, obj) {
var result = {};
for (var prop in obj) {
if (!_contains(prop, names)) {
result[prop] = obj[prop];
}
}
return result;
});
/**
* Returns the left-to-right Kleisli composition of the provided functions,
* each of which must return a value of a type supported by [`chain`](#chain).
*
* `R.pipeK(f, g, h)` is equivalent to `R.pipe(R.chain(f), R.chain(g), R.chain(h))`.
*
* @func
* @memberOf R
* @since v0.16.0
* @category Function
* @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (m a -> m z)
* @param {...Function}
* @return {Function}
* @see R.composeK
* @example
*
* // parseJson :: String -> Maybe *
* // get :: String -> Object -> Maybe *
*
* // getStateCode :: Maybe String -> Maybe String
* var getStateCode = R.pipeK(
* parseJson,
* get('user'),
* get('address'),
* get('state'),
* R.compose(Maybe.of, R.toUpper)
* );
*
* getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}'));
* //=> Just('NY')
* getStateCode(Maybe.of('[Invalid JSON]'));
* //=> Nothing()
*/
var pipeK = function pipeK() {
return composeK.apply(this, reverse(arguments));
};
/**
* Returns the string representation of the given value. `eval`'ing the output
* should result in a value equivalent to the input value. Many of the built-in
* `toString` methods do not satisfy this requirement.
*
* If the given value is an `[object Object]` with a `toString` method other
* than `Object.prototype.toString`, this method is invoked with no arguments
* to produce the return value. This means user-defined constructor functions
* can provide a suitable `toString` method. For example:
*
* function Point(x, y) {
* this.x = x;
* this.y = y;
* }
*
* Point.prototype.toString = function() {
* return 'new Point(' + this.x + ', ' + this.y + ')';
* };
*
* R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'
*
* @func
* @memberOf R
* @since v0.14.0
* @category String
* @sig * -> String
* @param {*} val
* @return {String}
* @example
*
* R.toString(42); //=> '42'
* R.toString('abc'); //=> '"abc"'
* R.toString([1, 2, 3]); //=> '[1, 2, 3]'
* R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}'
* R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")'
*/
var toString = _curry1(function toString(val) {
return _toString(val, []);
});
/**
* Returns a new list without values in the first argument.
* `R.equals` is used to determine equality.
*
* Acts as a transducer if a transformer is given in list position.
*
* @func
* @memberOf R
* @since v0.19.0
* @category List
* @sig [a] -> [a] -> [a]
* @param {Array} list1 The values to be removed from `list2`.
* @param {Array} list2 The array to remove values from.
* @return {Array} The new array without values in `list1`.
* @see R.transduce
* @example
*
* R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4]
*/
var without = _curry2(function (xs, list) {
return reject(flip(_contains)(xs), list);
});
// A simple Set type that honours R.equals semantics
/* globals Set */
/**
* Combines the logic for checking whether an item is a member of the set and
* for adding a new item to the set.
*
* @param item The item to check or add to the Set instance.
* @param shouldAdd If true, the item will be added to the set if it doesn't
* already exist.
* @param set The set instance to check or add to.
* @return {boolean} When shouldAdd is true, this will return true when a new
* item was added otherwise false. When shouldAdd is false,
* this will return true if the item already exists, otherwise
* false.
*/
// distinguish between +0 and -0
// these types can all utilise Set
// set._items['boolean'] holds a two element array
// representing [ falseExists, trueExists ]
// compare functions for reference equality
/* falls through */
// reduce the search size of heterogeneous sets by creating buckets
// for each type.
// scan through all previously applied items
var _Set = function () {
function _Set() {
/* globals Set */
this._nativeSet = typeof Set === 'function' ? new Set() : null;
this._items = {};
}
_Set.prototype.add = function (item) {
return hasOrAdd(item, true, this);
};
_Set.prototype.has = function (item) {
return hasOrAdd(item, false, this);
};
/**
* Combines the logic for checking whether an item is a member of the set and
* for adding a new item to the set.
*
* @param item The item to check or add to the Set instance.
* @param shouldAdd If true, the item will be added to the set if it doesn't
* already exist.
* @param set The set instance to check or add to.
* @return {boolean} When shouldAdd is true, this will return true when a new
* item was added otherwise false. When shouldAdd is false,
* this will return true if the item already exists, otherwise
* false.
*/
function hasOrAdd(item, shouldAdd, set) {
var type = typeof item;
var prevSize, newSize;
switch (type) {
case 'string':
case 'number':
// distinguish between +0 and -0
if (item === 0 && !set._items['-0'] && 1 / item === -Infinity) {
if (shouldAdd) {
set._items['-0'] = true;
}
return shouldAdd;
}
// these types can all utilise Set
if (set._nativeSet !== null) {
if (shouldAdd) {
prevSize = set._nativeSet.size;
set._nativeSet.add(item);
newSize = set._nativeSet.size;
return newSize > prevSize;
} else {
return set._nativeSet.has(item);
}
} else {
if (!(type in set._items)) {
if (shouldAdd) {
set._items[type] = {};
set._items[type][item] = true;
}
return shouldAdd;
} else if (item in set._items[type]) {
return !shouldAdd;
} else {
if (shouldAdd) {
set._items[type][item] = true;
}
return shouldAdd;
}
}
case 'boolean':
// set._items['boolean'] holds a two element array
// representing [ falseExists, trueExists ]
if (type in set._items) {
var bIdx = item ? 1 : 0;
if (set._items[type][bIdx]) {
return !shouldAdd;
} else {
if (shouldAdd) {
set._items[type][bIdx] = true;
}
return shouldAdd;
}
} else {
if (shouldAdd) {
set._items[type] = item ? [
false,
true
] : [
true,
false
];
}
return shouldAdd;
}
case 'function':
// compare functions for reference equality
if (set._nativeSet !== null) {
if (shouldAdd) {
prevSize = set._nativeSet.size;
set._nativeSet.add(item);
newSize = set._nativeSet.size;
return newSize > prevSize;
} else {
return set._nativeSet.has(item);
}
} else {
if (!(type in set._items)) {
if (shouldAdd) {
set._items[type] = [item];
}
return shouldAdd;
}
if (!_contains(item, set._items[type])) {
if (shouldAdd) {
set._items[type].push(item);
}
return shouldAdd;
}
}
return !shouldAdd;
case 'undefined':
if (set._items[type]) {
return !shouldAdd;
} else {
if (shouldAdd) {
set._items[type] = true;
}
return shouldAdd;
}
case 'object':
if (item === null) {
if (!set._items['null']) {
if (shouldAdd) {
set._items['null'] = true;
}
return shouldAdd;
}
return !shouldAdd;
}
/* falls through */
default:
// reduce the search size of heterogeneous sets by creating buckets
// for each type.
type = Object.prototype.toString.call(item);
if (!(type in set._items)) {
if (shouldAdd) {
set._items[type] = [item];
}
return shouldAdd;
}
// scan through all previously applied items
if (!_contains(item, set._items[type])) {
if (shouldAdd) {
set._items[type].push(item);
}
return shouldAdd;
}
return !shouldAdd;
}
}
return _Set;
}();
/**
* A function wrapping calls to the two functions in an `&&` operation,
* returning the result of the first function if it is false-y and the result
* of the second function otherwise. Note that this is short-circuited,
* meaning that the second function will not be invoked if the first returns a
* false-y value.
*
* In addition to functions, `R.both` also accepts any fantasy-land compatible
* applicative functor.
*
* @func
* @memberOf R
* @since v0.12.0
* @category Logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together.
* @see R.and
* @example
*
* var gt10 = x => x > 10;
* var even = x => x % 2 === 0;
* var f = R.both(gt10, even);
* f(100); //=> true
* f(101); //=> false
*/
var both = _curry2(function both(f, g) {
return _isFunction(f) ? function _both() {
return f.apply(this, arguments) && g.apply(this, arguments);
} : lift(and)(f, g);
});
/**
* Takes a function `f` and returns a function `g` such that:
*
* - applying `g` to zero or more arguments will give __true__ if applying
* the same arguments to `f` gives a logical __false__ value; and
*
* - applying `g` to zero or more arguments will give __false__ if applying
* the same arguments to `f` gives a logical __true__ value.
*
* `R.complement` will work on all other functors as well.
*
* @func
* @memberOf R
* @since v0.12.0
* @category Logic
* @sig (*... -> *) -> (*... -> Boolean)
* @param {Function} f
* @return {Function}
* @see R.not
* @example
*
* var isEven = n => n % 2 === 0;
* var isOdd = R.complement(isEven);
* isOdd(21); //=> true
* isOdd(42); //=> false
*/
var complement = lift(not);
/**
* A function wrapping calls to the two functions in an `||` operation,
* returning the result of the first function if it is truth-y and the result
* of the second function otherwise. Note that this is short-circuited,
* meaning that the second function will not be invoked if the first returns a
* truth-y value.
*
* In addition to functions, `R.either` also accepts any fantasy-land compatible
* applicative functor.
*
* @func
* @memberOf R
* @since v0.12.0
* @category Logic
* @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean)
* @param {Function} f a predicate
* @param {Function} g another predicate
* @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together.
* @see R.or
* @example
*
* var gt10 = x => x > 10;
* var even = x => x % 2 === 0;
* var f = R.either(gt10, even);
* f(101); //=> true
* f(8); //=> true
*/
var either = _curry2(function either(f, g) {
return _isFunction(f) ? function _either() {
return f.apply(this, arguments) || g.apply(this, arguments);
} : lift(or)(f, g);
});
/**
* Turns a named method with a specified arity into a function that can be
* called directly supplied with arguments and a target object.
*
* The returned function is curried and accepts `arity + 1` parameters where
* the final parameter is the target object.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
* @param {Number} arity Number of arguments the returned function should take
* before the target object.
* @param {String} method Name of the method to call.
* @return {Function} A new curried function.
* @example
*
* var sliceFrom = R.invoker(1, 'slice');
* sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
* var sliceFrom6 = R.invoker(2, 'slice')(6);
* sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
*/
var invoker = _curry2(function invoker(arity, method) {
return curryN(arity + 1, function () {
var target = arguments[arity];
if (target != null && is(Function, target[method])) {
return target[method].apply(target, _slice(arguments, 0, arity));
}
throw new TypeError(toString(target) + ' does not have a method named "' + method + '"');
});
});
/**
* Returns a string made by inserting the `separator` between each element and
* concatenating all the elements into a single string.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig String -> [a] -> String
* @param {Number|String} separator The string used to separate the elements.
* @param {Array} xs The elements to join into a string.
* @return {String} str The string made by concatenating `xs` with `separator`.
* @see R.split
* @example
*
* var spacer = R.join(' ');
* spacer(['a', 2, 3.4]); //=> 'a 2 3.4'
* R.join('|', [1, 2, 3]); //=> '1|2|3'
*/
var join = invoker(1, 'join');
/**
* Creates a new function that, when invoked, caches the result of calling `fn`
* for a given argument set and returns the result. Subsequent calls to the
* memoized `fn` with the same argument set will not result in an additional
* call to `fn`; instead, the cached result for that set of arguments will be
* returned.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (*... -> a) -> (*... -> a)
* @param {Function} fn The function to memoize.
* @return {Function} Memoized version of `fn`.
* @example
*
* var count = 0;
* var factorial = R.memoize(n => {
* count += 1;
* return R.product(R.range(1, n + 1));
* });
* factorial(5); //=> 120
* factorial(5); //=> 120
* factorial(5); //=> 120
* count; //=> 1
*/
var memoize = _curry1(function memoize(fn) {
var cache = {};
return _arity(fn.length, function () {
var key = toString(arguments);
if (!_has(key, cache)) {
cache[key] = fn.apply(this, arguments);
}
return cache[key];
});
});
/**
* Splits a string into an array of strings based on the given
* separator.
*
* @func
* @memberOf R
* @since v0.1.0
* @category String
* @sig (String | RegExp) -> String -> [String]
* @param {String|RegExp} sep The pattern.
* @param {String} str The string to separate into an array.
* @return {Array} The array of strings from `str` separated by `str`.
* @see R.join
* @example
*
* var pathComponents = R.split('/');
* R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node']
*
* R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd']
*/
var split = invoker(1, 'split');
/**
* Determines whether a given string matches a given regular expression.
*
* @func
* @memberOf R
* @since v0.12.0
* @category String
* @sig RegExp -> String -> Boolean
* @param {RegExp} pattern
* @param {String} str
* @return {Boolean}
* @see R.match
* @example
*
* R.test(/^x/, 'xyz'); //=> true
* R.test(/^y/, 'xyz'); //=> false
*/
var test = _curry2(function test(pattern, str) {
if (!_isRegExp(pattern)) {
throw new TypeError('\u2018test\u2019 requires a value of type RegExp as its first argument; received ' + toString(pattern));
}
return _cloneRegExp(pattern).test(str);
});
/**
* The lower case version of a string.
*
* @func
* @memberOf R
* @since v0.9.0
* @category String
* @sig String -> String
* @param {String} str The string to lower case.
* @return {String} The lower case version of `str`.
* @see R.toUpper
* @example
*
* R.toLower('XYZ'); //=> 'xyz'
*/
var toLower = invoker(0, 'toLowerCase');
/**
* The upper case version of a string.
*
* @func
* @memberOf R
* @since v0.9.0
* @category String
* @sig String -> String
* @param {String} str The string to upper case.
* @return {String} The upper case version of `str`.
* @see R.toLower
* @example
*
* R.toUpper('abc'); //=> 'ABC'
*/
var toUpper = invoker(0, 'toUpperCase');
/**
* Returns a new list containing only one copy of each element in the original
* list, based upon the value returned by applying the supplied function to
* each list element. Prefers the first item if the supplied function produces
* the same value on two items. `R.equals` is used for comparison.
*
* @func
* @memberOf R
* @since v0.16.0
* @category List
* @sig (a -> b) -> [a] -> [a]
* @param {Function} fn A function used to produce a value to use during comparisons.
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]
*/
var uniqBy = _curry2(function uniqBy(fn, list) {
var set = new _Set();
var result = [];
var idx = 0;
var appliedItem, item;
while (idx < list.length) {
item = list[idx];
appliedItem = fn(item);
if (set.add(appliedItem)) {
result.push(item);
}
idx += 1;
}
return result;
});
/**
* Returns the result of concatenating the given lists or strings.
*
* Dispatches to the `concat` method of the first argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [a] -> [a]
* @sig String -> String -> String
* @param {Array|String} a
* @param {Array|String} b
* @return {Array|String}
*
* @example
*
* R.concat([], []); //=> []
* R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3]
* R.concat('ABC', 'DEF'); // 'ABCDEF'
*/
var concat = flip(invoker(1, 'concat'));
/**
* Finds the set (i.e. no duplicates) of all elements contained in the first or
* second list, but not both.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Relation
* @sig [*] -> [*] -> [*]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` or `list2`, but not both.
* @see R.symmetricDifferenceWith
* @example
*
* R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5]
* R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2]
*/
var symmetricDifference = _curry2(function symmetricDifference(list1, list2) {
return concat(difference(list1, list2), difference(list2, list1));
});
/**
* Finds the set (i.e. no duplicates) of all elements contained in the first or
* second list, but not both. Duplication is determined according to the value
* returned by applying the supplied predicate to two list elements.
*
* @func
* @memberOf R
* @since v0.19.0
* @category Relation
* @sig (a -> a -> Boolean) -> [a] -> [a] -> [a]
* @param {Function} pred A predicate used to test whether two items are equal.
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The elements in `list1` or `list2`, but not both.
* @see R.symmetricDifference
* @example
*
* var eqA = R.eqBy(R.prop('a'));
* var l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
* var l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}];
* R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}]
*/
var symmetricDifferenceWith = _curry3(function symmetricDifferenceWith(pred, list1, list2) {
return concat(differenceWith(pred, list1, list2), differenceWith(pred, list2, list1));
});
/**
* Returns a new list containing only one copy of each element in the original
* list. `R.equals` is used to determine equality.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [a]
* @param {Array} list The array to consider.
* @return {Array} The list of unique items.
* @example
*
* R.uniq([1, 1, 2, 1]); //=> [1, 2]
* R.uniq([1, '1']); //=> [1, '1']
* R.uniq([[42], [42]]); //=> [[42]]
*/
var uniq = uniqBy(identity);
/**
* Combines two lists into a set (i.e. no duplicates) composed of those
* elements common to both lists.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig [*] -> [*] -> [*]
* @param {Array} list1 The first list.
* @param {Array} list2 The second list.
* @return {Array} The list of elements found in both `list1` and `list2`.
* @see R.intersectionWith
* @example
*
* R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]
*/
var intersection = _curry2(function intersection(list1, list2) {
var lookupList, filteredList;
if (list1.length > list2.length) {
lookupList = list1;
filteredList = list2;
} else {
lookupList = list2;
filteredList = list1;
}
return uniq(_filter(flip(_contains)(lookupList), filteredList));
});
/**
* Combines two lists into a set (i.e. no duplicates) composed of the elements
* of each list.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Relation
* @sig [*] -> [*] -> [*]
* @param {Array} as The first list.
* @param {Array} bs The second list.
* @return {Array} The first and second lists concatenated, with
* duplicates removed.
* @example
*
* R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4]
*/
var union = _curry2(compose(uniq, _concat));
var R = {
F: F,
T: T,
__: __,
add: add,
addIndex: addIndex,
adjust: adjust,
all: all,
allPass: allPass,
allUniq: allUniq,
always: always,
and: and,
any: any,
anyPass: anyPass,
ap: ap,
aperture: aperture,
append: append,
apply: apply,
applySpec: applySpec,
assoc: assoc,
assocPath: assocPath,
binary: binary,
bind: bind,
both: both,
call: call,
chain: chain,
clamp: clamp,
clone: clone,
comparator: comparator,
complement: complement,
compose: compose,
composeK: composeK,
composeP: composeP,
concat: concat,
cond: cond,
construct: construct,
constructN: constructN,
contains: contains,
converge: converge,
countBy: countBy,
curry: curry,
curryN: curryN,
dec: dec,
defaultTo: defaultTo,
difference: difference,
differenceWith: differenceWith,
dissoc: dissoc,
dissocPath: dissocPath,
divide: divide,
drop: drop,
dropLast: dropLast,
dropLastWhile: dropLastWhile,
dropRepeats: dropRepeats,
dropRepeatsWith: dropRepeatsWith,
dropWhile: dropWhile,
either: either,
empty: empty,
eqBy: eqBy,
eqProps: eqProps,
equals: equals,
evolve: evolve,
filter: filter,
find: find,
findIndex: findIndex,
findLast: findLast,
findLastIndex: findLastIndex,
flatten: flatten,
flip: flip,
forEach: forEach,
fromPairs: fromPairs,
groupBy: groupBy,
groupWith: groupWith,
gt: gt,
gte: gte,
has: has,
hasIn: hasIn,
head: head,
identical: identical,
identity: identity,
ifElse: ifElse,
inc: inc,
indexBy: indexBy,
indexOf: indexOf,
init: init,
insert: insert,
insertAll: insertAll,
intersection: intersection,
intersectionWith: intersectionWith,
intersperse: intersperse,
into: into,
invert: invert,
invertObj: invertObj,
invoker: invoker,
is: is,
isArrayLike: isArrayLike,
isEmpty: isEmpty,
isNil: isNil,
join: join,
juxt: juxt,
keys: keys,
keysIn: keysIn,
last: last,
lastIndexOf: lastIndexOf,
length: length,
lens: lens,
lensIndex: lensIndex,
lensPath: lensPath,
lensProp: lensProp,
lift: lift,
liftN: liftN,
lt: lt,
lte: lte,
map: map,
mapAccum: mapAccum,
mapAccumRight: mapAccumRight,
mapObjIndexed: mapObjIndexed,
match: match,
mathMod: mathMod,
max: max,
maxBy: maxBy,
mean: mean,
median: median,
memoize: memoize,
merge: merge,
mergeAll: mergeAll,
mergeWith: mergeWith,
mergeWithKey: mergeWithKey,
min: min,
minBy: minBy,
modulo: modulo,
multiply: multiply,
nAry: nAry,
negate: negate,
none: none,
not: not,
nth: nth,
nthArg: nthArg,
objOf: objOf,
of: of,
omit: omit,
once: once,
or: or,
over: over,
pair: pair,
partial: partial,
partialRight: partialRight,
partition: partition,
path: path,
pathEq: pathEq,
pathOr: pathOr,
pathSatisfies: pathSatisfies,
pick: pick,
pickAll: pickAll,
pickBy: pickBy,
pipe: pipe,
pipeK: pipeK,
pipeP: pipeP,
pluck: pluck,
prepend: prepend,
product: product,
project: project,
prop: prop,
propEq: propEq,
propIs: propIs,
propOr: propOr,
propSatisfies: propSatisfies,
props: props,
range: range,
reduce: reduce,
reduceBy: reduceBy,
reduceRight: reduceRight,
reduced: reduced,
reject: reject,
remove: remove,
repeat: repeat,
replace: replace,
reverse: reverse,
scan: scan,
sequence: sequence,
set: set,
slice: slice,
sort: sort,
sortBy: sortBy,
split: split,
splitAt: splitAt,
splitEvery: splitEvery,
splitWhen: splitWhen,
subtract: subtract,
sum: sum,
symmetricDifference: symmetricDifference,
symmetricDifferenceWith: symmetricDifferenceWith,
tail: tail,
take: take,
takeLast: takeLast,
takeLastWhile: takeLastWhile,
takeWhile: takeWhile,
tap: tap,
test: test,
times: times,
toLower: toLower,
toPairs: toPairs,
toPairsIn: toPairsIn,
toString: toString,
toUpper: toUpper,
transduce: transduce,
transpose: transpose,
traverse: traverse,
trim: trim,
tryCatch: tryCatch,
type: type,
unapply: unapply,
unary: unary,
uncurryN: uncurryN,
unfold: unfold,
union: union,
unionWith: unionWith,
uniq: uniq,
uniqBy: uniqBy,
uniqWith: uniqWith,
unless: unless,
unnest: unnest,
until: until,
update: update,
useWith: useWith,
values: values,
valuesIn: valuesIn,
view: view,
when: when,
where: where,
whereEq: whereEq,
without: without,
wrap: wrap,
xprod: xprod,
zip: zip,
zipObj: zipObj,
zipWith: zipWith
};
/* eslint-env amd */
/* TEST_ENTRY_POINT */
if (typeof exports === 'object') {
module.exports = R;
} else if (typeof define === 'function' && define.amd) {
define(function() { return R; });
} else {
this.R = R;
}
}.call(this));
},{}],384:[function(require,module,exports){
(function (global){
/* global window */
'use strict';
module.exports = require('./ponyfill')(global || window || this);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./ponyfill":385}],385:[function(require,module,exports){
'use strict';
module.exports = function symbolObservablePonyfill(root) {
var result;
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
result = Symbol.observable;
} else {
result = Symbol('observable');
Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
},{}],386:[function(require,module,exports){
(function(self) {
'use strict';
if (self.fetch) {
return
}
var support = {
searchParams: 'URLSearchParams' in self,
iterable: 'Symbol' in self && 'iterator' in Symbol,
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob()
return true
} catch(e) {
return false
}
})(),
formData: 'FormData' in self,
arrayBuffer: 'ArrayBuffer' in self
}
function normalizeName(name) {
if (typeof name !== 'string') {
name = String(name)
}
if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
throw new TypeError('Invalid character in header field name')
}
return name.toLowerCase()
}
function normalizeValue(value) {
if (typeof value !== 'string') {
value = String(value)
}
return value
}
// Build a destructive iterator for the value list
function iteratorFor(items) {
var iterator = {
next: function() {
var value = items.shift()
return {done: value === undefined, value: value}
}
}
if (support.iterable) {
iterator[Symbol.iterator] = function() {
return iterator
}
}
return iterator
}
function Headers(headers) {
this.map = {}
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value)
}, this)
} else if (headers) {
Object.getOwnPropertyNames(headers).forEach(function(name) {
this.append(name, headers[name])
}, this)
}
}
Headers.prototype.append = function(name, value) {
name = normalizeName(name)
value = normalizeValue(value)
var list = this.map[name]
if (!list) {
list = []
this.map[name] = list
}
list.push(value)
}
Headers.prototype['delete'] = function(name) {
delete this.map[normalizeName(name)]
}
Headers.prototype.get = function(name) {
var values = this.map[normalizeName(name)]
return values ? values[0] : null
}
Headers.prototype.getAll = function(name) {
return this.map[normalizeName(name)] || []
}
Headers.prototype.has = function(name) {
return this.map.hasOwnProperty(normalizeName(name))
}
Headers.prototype.set = function(name, value) {
this.map[normalizeName(name)] = [normalizeValue(value)]
}
Headers.prototype.forEach = function(callback, thisArg) {
Object.getOwnPropertyNames(this.map).forEach(function(name) {
this.map[name].forEach(function(value) {
callback.call(thisArg, value, name, this)
}, this)
}, this)
}
Headers.prototype.keys = function() {
var items = []
this.forEach(function(value, name) { items.push(name) })
return iteratorFor(items)
}
Headers.prototype.values = function() {
var items = []
this.forEach(function(value) { items.push(value) })
return iteratorFor(items)
}
Headers.prototype.entries = function() {
var items = []
this.forEach(function(value, name) { items.push([name, value]) })
return iteratorFor(items)
}
if (support.iterable) {
Headers.prototype[Symbol.iterator] = Headers.prototype.entries
}
function consumed(body) {
if (body.bodyUsed) {
return Promise.reject(new TypeError('Already read'))
}
body.bodyUsed = true
}
function fileReaderReady(reader) {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result)
}
reader.onerror = function() {
reject(reader.error)
}
})
}
function readBlobAsArrayBuffer(blob) {
var reader = new FileReader()
reader.readAsArrayBuffer(blob)
return fileReaderReady(reader)
}
function readBlobAsText(blob) {
var reader = new FileReader()
reader.readAsText(blob)
return fileReaderReady(reader)
}
function Body() {
this.bodyUsed = false
this._initBody = function(body) {
this._bodyInit = body
if (typeof body === 'string') {
this._bodyText = body
} else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
this._bodyBlob = body
} else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
this._bodyFormData = body
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this._bodyText = body.toString()
} else if (!body) {
this._bodyText = ''
} else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) {
// Only support ArrayBuffers for POST method.
// Receiving ArrayBuffers happens via Blobs, instead.
} else {
throw new Error('unsupported BodyInit type')
}
if (!this.headers.get('content-type')) {
if (typeof body === 'string') {
this.headers.set('content-type', 'text/plain;charset=UTF-8')
} else if (this._bodyBlob && this._bodyBlob.type) {
this.headers.set('content-type', this._bodyBlob.type)
} else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
}
}
}
if (support.blob) {
this.blob = function() {
var rejected = consumed(this)
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return Promise.resolve(this._bodyBlob)
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as blob')
} else {
return Promise.resolve(new Blob([this._bodyText]))
}
}
this.arrayBuffer = function() {
return this.blob().then(readBlobAsArrayBuffer)
}
this.text = function() {
var rejected = consumed(this)
if (rejected) {
return rejected
}
if (this._bodyBlob) {
return readBlobAsText(this._bodyBlob)
} else if (this._bodyFormData) {
throw new Error('could not read FormData body as text')
} else {
return Promise.resolve(this._bodyText)
}
}
} else {
this.text = function() {
var rejected = consumed(this)
return rejected ? rejected : Promise.resolve(this._bodyText)
}
}
if (support.formData) {
this.formData = function() {
return this.text().then(decode)
}
}
this.json = function() {
return this.text().then(JSON.parse)
}
return this
}
// HTTP methods whose capitalization should be normalized
var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
function normalizeMethod(method) {
var upcased = method.toUpperCase()
return (methods.indexOf(upcased) > -1) ? upcased : method
}
function Request(input, options) {
options = options || {}
var body = options.body
if (Request.prototype.isPrototypeOf(input)) {
if (input.bodyUsed) {
throw new TypeError('Already read')
}
this.url = input.url
this.credentials = input.credentials
if (!options.headers) {
this.headers = new Headers(input.headers)
}
this.method = input.method
this.mode = input.mode
if (!body) {
body = input._bodyInit
input.bodyUsed = true
}
} else {
this.url = input
}
this.credentials = options.credentials || this.credentials || 'omit'
if (options.headers || !this.headers) {
this.headers = new Headers(options.headers)
}
this.method = normalizeMethod(options.method || this.method || 'GET')
this.mode = options.mode || this.mode || null
this.referrer = null
if ((this.method === 'GET' || this.method === 'HEAD') && body) {
throw new TypeError('Body not allowed for GET or HEAD requests')
}
this._initBody(body)
}
Request.prototype.clone = function() {
return new Request(this)
}
function decode(body) {
var form = new FormData()
body.trim().split('&').forEach(function(bytes) {
if (bytes) {
var split = bytes.split('=')
var name = split.shift().replace(/\+/g, ' ')
var value = split.join('=').replace(/\+/g, ' ')
form.append(decodeURIComponent(name), decodeURIComponent(value))
}
})
return form
}
function headers(xhr) {
var head = new Headers()
var pairs = (xhr.getAllResponseHeaders() || '').trim().split('\n')
pairs.forEach(function(header) {
var split = header.trim().split(':')
var key = split.shift().trim()
var value = split.join(':').trim()
head.append(key, value)
})
return head
}
Body.call(Request.prototype)
function Response(bodyInit, options) {
if (!options) {
options = {}
}
this.type = 'default'
this.status = options.status
this.ok = this.status >= 200 && this.status < 300
this.statusText = options.statusText
this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
this.url = options.url || ''
this._initBody(bodyInit)
}
Body.call(Response.prototype)
Response.prototype.clone = function() {
return new Response(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new Headers(this.headers),
url: this.url
})
}
Response.error = function() {
var response = new Response(null, {status: 0, statusText: ''})
response.type = 'error'
return response
}
var redirectStatuses = [301, 302, 303, 307, 308]
Response.redirect = function(url, status) {
if (redirectStatuses.indexOf(status) === -1) {
throw new RangeError('Invalid status code')
}
return new Response(null, {status: status, headers: {location: url}})
}
self.Headers = Headers
self.Request = Request
self.Response = Response
self.fetch = function(input, init) {
return new Promise(function(resolve, reject) {
var request
if (Request.prototype.isPrototypeOf(input) && !init) {
request = input
} else {
request = new Request(input, init)
}
var xhr = new XMLHttpRequest()
function responseURL() {
if ('responseURL' in xhr) {
return xhr.responseURL
}
// Avoid security warnings on getResponseHeader when not allowed by CORS
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL')
}
return
}
xhr.onload = function() {
var options = {
status: xhr.status,
statusText: xhr.statusText,
headers: headers(xhr),
url: responseURL()
}
var body = 'response' in xhr ? xhr.response : xhr.responseText
resolve(new Response(body, options))
}
xhr.onerror = function() {
reject(new TypeError('Network request failed'))
}
xhr.ontimeout = function() {
reject(new TypeError('Network request failed'))
}
xhr.open(request.method, request.url, true)
if (request.credentials === 'include') {
xhr.withCredentials = true
}
if ('responseType' in xhr && support.blob) {
xhr.responseType = 'blob'
}
request.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value)
})
xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
})
}
self.fetch.polyfill = true
})(typeof self !== 'undefined' ? self : this);
},{}],387:[function(require,module,exports){
module.exports={
"offset": {
"x": 0,
"y": 0
},
"types": [
{
"name": "I",
"size": {
"width": 5,
"height": 5
},
"data": [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
],
"position": [
[[0, 0], [-1, 0], [2, 0], [-1, 0], [2, 0]],
[[-1, 0], [0, 0], [0, 0], [0, -1], [0, 2]],
[[-1, -1], [1, -1], [-2, -1], [1, 0], [-2, 0]],
[[0, -1], [0, -1], [0, -1], [0, 1], [0, -2]]
]
},
{
"name": "O",
"size": {
"width": 3,
"height": 3
},
"data": [
[0, 1, 1],
[0, 1, 1],
[0, 0, 0]
],
"position": [
[[0, 0]],
[[0, 1]],
[[-1, 1]],
[[-1, 0]]
]
},
{
"name": "J",
"size": {
"width": 3,
"height": 3
},
"data": [
[1, 0, 0],
[1, 1, 1],
[0, 0, 0]
],
"position": [
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [1, 1], [0, -2], [1, -2]],
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [-1, 0], [-1, 1], [0, -2], [-1, -2]]
]
},
{
"name": "L",
"size": {
"width": 3,
"height": 3
},
"data": [
[0, 0, 1],
[1, 1, 1],
[0, 0, 0]
],
"position": [
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [1, 1], [0, -2], [1, -2]],
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [-1, 0], [-1, 1], [0, -2], [-1, -2]]
]
},
{
"name": "S",
"size": {
"width": 3,
"height": 3
},
"data": [
[0, 1, 1],
[1, 1, 0],
[0, 0, 0]
],
"position": [
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [1, 1], [0, -2], [1, -2]],
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [-1, 0], [-1, 1], [0, -2], [-1, -2]]
]
},
{
"name": "T",
"size": {
"width": 3,
"height": 3
},
"data": [
[0, 1, 0],
[1, 1, 1],
[0, 0, 0]
],
"position": [
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [1, 1], [0, -2], [1, -2]],
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [-1, 0], [-1, 1], [0, -2], [-1, -2]]
]
},
{
"name": "Z",
"size": {
"width": 3,
"height": 3
},
"data": [
[1, 1, 0],
[0, 1, 1],
[0, 0, 0]
],
"position": [
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [1, 0], [1, 1], [0, -2], [1, -2]],
[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]],
[[0, 0], [-1, 0], [-1, 1], [0, -2], [-1, -2]]
]
}
]
}
},{}],388:[function(require,module,exports){
module.exports={
"next": 3,
"config": {
"arr": 7,
"das": 1,
"drop-das": 1,
"delay": {
"show": 0,
"drop": 60,
"lock": 60
}
}
}
},{}],389:[function(require,module,exports){
module.exports={
"size": {
"width": 10,
"height": 20
},
"padding": {
"left": 0,
"right": 0,
"top": 20,
"bottom": 0
}
}
},{}],390:[function(require,module,exports){
module.exports={
"keys": [
"move-left",
"move-right",
"drop",
"hard-drop",
"rotate-left",
"rotate-right",
"hold"
],
"methods": {
"keyboard": {
"move-left": "ArrowLeft",
"move-right": "ArrowRight",
"drop": "ArrowDown",
"hard-drop": "ArrowUp",
"rotate-left": "KeyZ",
"rotate-right": "KeyX",
"hold": "Space"
}
}
}
},{}],391:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
var _engine = require("../data/engine.json");
var _engine2 = _interopRequireDefault(_engine);
var _ground = require("../data/ground.json");
var _ground2 = _interopRequireDefault(_ground);
var _block = require("../data/block.json");
var _block2 = _interopRequireDefault(_block);
var _block3 = require("../structs/block");
var _block4 = _interopRequireDefault(_block3);
var _ground3 = require("../structs/ground");
var _ground4 = _interopRequireDefault(_ground3);
var _random = require("../utils/random");
var _random2 = _interopRequireDefault(_random);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Core = function () {
function Core() {
_classCallCheck(this, Core);
this.random = new _random2.default();
this.ground = (0, _ground4.default)();
this.block = null;
this.maskBlock = null;
this.holdBlock = null;
this.hasHeld = false;
this.showBlock = true;
this.isLocked = false;
this.nexts = _ramda2.default.times(this.randomType.bind(this), _engine2.default.next);
}
_createClass(Core, [{
key: "randomType",
value: function randomType() {
return this.random.next(_block2.default.types.length);
}
}, {
key: "next",
value: function next() {
var block = (0, _block4.default)({
type: _ramda2.default.head(this.nexts)
});
var data = (0, _block3.getData)(block);
this.block = (0, _block3.moveTo)(block, Math.floor((_ground2.default.size.width - data.size.width) / 2 + _block2.default.offset.x), Math.floor(-data.size.height / 2 + _block2.default.offset.y));
this.hasHeld = false;
this.showBlock = true;
this.isLocked = false;
this.nexts = _ramda2.default.append(this.randomType(), _ramda2.default.tail(this.nexts));
this.calculateMask();
}
}, {
key: "calculateMask",
value: function calculateMask() {
this.maskBlock = (0, _block3.clone)(this.block);
while (this.checkAvailable((0, _block3.moveBy)(this.maskBlock, 0, 1))) {
this.maskBlock = (0, _block3.moveBy)(this.maskBlock, 0, 1);
}
}
}, {
key: "clearLines",
value: function clearLines() {
(0, _ground3.clearLines)(this.ground);
}
}, {
key: "hold",
value: function hold() {
var nextBlock = this.holdBlock;
this.holdBlock = this.block;
this.block = nextBlock;
if (!this.block) {
this.next();
} else {
this.calculateMask();
}
this.hasHeld = true;
}
}, {
key: "canHold",
value: function canHold() {
return !this.hasHeld;
}
}, {
key: "tryHold",
value: function tryHold() {
var result = void 0;
if (result = this.canHold()) {
this.hold();
}
return result;
}
}, {
key: "checkAvailable",
value: function checkAvailable() {
var block = arguments.length <= 0 || arguments[0] === undefined ? this.block : arguments[0];
return (0, _ground3.checkAvailable)(this.ground, block);
}
}, {
key: "isDead",
value: function isDead() {
return !this.checkAvailable();
}
}, {
key: "place",
value: function place() {
var block = arguments.length <= 0 || arguments[0] === undefined ? this.block : arguments[0];
return (0, _ground3.place)(this.ground, block);
}
}, {
key: "lock",
value: function lock() {
this.isLocked = true;
this.place();
}
}, {
key: "moveBy",
value: function moveBy(x, y) {
this.block = (0, _block3.moveBy)(this.block, x, y);
this.calculateMask();
}
}, {
key: "canMoveBy",
value: function canMoveBy(x, y) {
return this.checkAvailable((0, _block3.moveBy)(this.block, x, y));
}
}, {
key: "tryMoveBy",
value: function tryMoveBy(x, y) {
var result = void 0;
if (result = this.canMoveBy(x, y)) {
this.moveBy(x, y);
}
return result;
}
}, {
key: "moveLeft",
value: function moveLeft() {
this.moveBy(-1, 0);
}
}, {
key: "canMoveLeft",
value: function canMoveLeft() {
return this.canMoveBy(-1, 0);
}
}, {
key: "tryMoveLeft",
value: function tryMoveLeft() {
return this.tryMoveBy(-1, 0);
}
}, {
key: "moveRight",
value: function moveRight() {
this.moveBy(1, 0);
}
}, {
key: "canMoveRight",
value: function canMoveRight() {
return this.canMoveBy(1, 0);
}
}, {
key: "tryMoveRight",
value: function tryMoveRight() {
return this.tryMoveBy(1, 0);
}
}, {
key: "drop",
value: function drop() {
this.moveBy(0, 1);
}
}, {
key: "canDrop",
value: function canDrop() {
return this.canMoveBy(0, 1);
}
}, {
key: "tryDrop",
value: function tryDrop() {
return this.tryMoveBy(0, 1);
}
}, {
key: "rotate",
value: function rotate(direction) {
var offset = arguments.length <= 1 || arguments[1] === undefined ? [0, 0] : arguments[1];
this.block = (0, _block3.rotate)((0, _block3.moveBy)(this.block, offset[0], offset[1]), direction);
this.calculateMask();
}
}, {
key: "canRotate",
value: function canRotate(direction) {
var data = (0, _block3.getData)(this.block);
var rotatedData = (0, _block3.getData)((0, _block3.rotate)(this.block, direction));
for (var i = 0; i < data.position.length; i++) {
var offset = [data.position[i][0] - rotatedData.position[i][0], data.position[i][1] - rotatedData.position[i][1]];
var rotated = (0, _block3.rotate)((0, _block3.moveBy)(this.block, offset[0], offset[1]), direction);
if (this.checkAvailable(rotated)) {
return offset;
}
}
return null;
}
}, {
key: "tryRotate",
value: function tryRotate(direction) {
var result = void 0;
if (result = this.canRotate(direction)) {
this.rotate(direction, result);
}
return result;
}
}, {
key: "rotateLeft",
value: function rotateLeft(offset) {
this.rotate(_block3.ROTATE_LEFT, offset);
}
}, {
key: "canRotateLeft",
value: function canRotateLeft() {
return this.canRotate(_block3.ROTATE_LEFT);
}
}, {
key: "tryRotateLeft",
value: function tryRotateLeft() {
return this.tryRotate(_block3.ROTATE_LEFT);
}
}, {
key: "rotateRight",
value: function rotateRight(offset) {
this.rotate(_block3.ROTATE_RIGHT, offset);
}
}, {
key: "canRotateRight",
value: function canRotateRight() {
return this.canRotate(_block3.ROTATE_RIGHT);
}
}, {
key: "tryRotateRight",
value: function tryRotateRight() {
return this.tryRotate(_block3.ROTATE_RIGHT);
}
}]);
return Core;
}();
exports.default = Core;
},{"../data/block.json":387,"../data/engine.json":388,"../data/ground.json":389,"../structs/block":399,"../structs/ground":400,"../utils/random":402,"ramda":383}],392:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _loglevel = require("loglevel");
var _loglevel2 = _interopRequireDefault(_loglevel);
var _core = require("./core");
var _core2 = _interopRequireDefault(_core);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var State = {
Begin: "begin",
Create: "create",
DelayShow: "delay-show",
Show: "show",
Hold: "hold",
CheckDead: "check-dead",
CheckDrop: "check-drop",
DelayDrop: "delay-drop",
Drop: "drop",
DelayLock: "delay-lock",
Lock: "lock",
ClearLine: "clear-line",
End: "end"
};
var Key = {
MoveLeft: "move-left",
MoveRight: "move-right",
Drop: "drop",
HardDrop: "hard-drop",
RotateLeft: "rotate-left",
RotateRight: "rotate-right",
Hold: "hold"
};
var Keys = [Key.Hold, Key.HardDrop, Key.RotateLeft, Key.RotateRight, Key.MoveLeft, Key.MoveRight, Key.Drop];
var Engine = function () {
function Engine() {
_classCallCheck(this, Engine);
this.frame = 0;
this.core = new _core2.default();
this.state = State.Begin;
this.keyState = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
this.keyState[key] = {
isDown: false,
delayed: false,
start: -1,
count: -1,
previous: -1
};
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.delays = {
show: 0,
drop: 0,
lock: 0
};
}
_createClass(Engine, [{
key: "trace",
value: function trace() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_loglevel2.default.trace.apply(_loglevel2.default, ["%o [%s]", this.frame, String(this.state).toUpperCase()].concat(args));
}
}, {
key: "resetLockDelay",
value: function resetLockDelay() {
// TODO
this.delays.lock = 0;
}
}, {
key: "shouldActKey",
value: function shouldActKey(key, config) {
var state = this.keyState[key];
if (!state.isDown) {
return false;
}
// TODO: support state.delayed
// FIXME: when Key.MoveLeft & Key.MoveRight both down
switch (key) {
case Key.MoveLeft:
{
if (this.keyState[Key.MoveRight].isDown && this.keyState[Key.MoveRight].start > state.start) {
return false;
}
break;
}
case Key.MoveRight:
{
if (this.keyState[Key.MoveLeft].isDown && this.keyState[Key.MoveLeft].start >= state.start) {
return false;
}
break;
}
case Key.RotateLeft:
{
if (this.keyState[Key.RotateRight].isDown && this.keyState[Key.RotateRight].start > state.start) {
return false;
}
break;
}
case Key.RotateRight:
{
if (this.keyState[Key.RotateLeft].isDown && this.keyState[Key.RotateLeft].start >= state.start) {
return false;
}
break;
}
}
switch (key) {
case Key.Hold:
case Key.HardDrop:
case Key.RotateLeft:
case Key.RotateRight:
{
return state.count === 0 && state.previous !== state.count;
}
case Key.MoveLeft:
case Key.MoveRight:
{
if (state.count >= config.arr && (state.count - config.arr) % config.das === 0 && state.count - state.previous >= config.das) {
return true;
}
if (state.count === 0 && state.previous !== state.count) {
return true;
}
return false;
}
case Key.Drop:
{
return state.count % config["drop-das"] === 0 && state.count - state.previous >= config["drop-das"];
}
}
return false;
}
}, {
key: "actKey",
value: function actKey(key) {
var core = this.core;
var state = this.keyState[key];
state.previous = this.frame - state.start;
switch (key) {
case Key.MoveLeft:
{
return core.tryMoveLeft();
}
case Key.MoveRight:
{
return core.tryMoveRight();
}
case Key.Drop:
{
var result = void 0;
if (result = core.tryDrop()) {
this.delays.drop = 0;
}
return result;
}
case Key.HardDrop:
{
while (core.tryDrop()) {}
this.state = State.Lock;
return true;
}
case Key.RotateLeft:
{
var _result = void 0;
if (_result = core.tryRotateLeft()) {
this.state = State.CheckDrop;
}
return _result;
}
case Key.RotateRight:
{
var _result2 = void 0;
if (_result2 = core.tryRotateRight()) {
this.state = State.CheckDrop;
}
return _result2;
}
case Key.Hold:
{
var _result3 = void 0;
if (_result3 = core.canHold()) {
this.state = State.Hold;
}
return _result3;
}
}
return false;
}
}, {
key: "actInput",
value: function actInput(config) {
var keys = arguments.length <= 1 || arguments[1] === undefined ? Keys : arguments[1];
var previousState = this.state;
var hasMoved = false;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var key = _step2.value;
if (this.shouldActKey(key, config)) {
hasMoved = hasMoved || this.actKey(key);
if (previousState !== this.state) {
return hasMoved;
}
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return hasMoved;
}
}, {
key: "act",
value: function act(config) {
var core = this.core;
switch (this.state) {
case State.Begin:
{
this.trace();
this.state = State.Create;
break;
}
case State.Create:
{
core.next();
core.showBlock = false;
this.trace(core.block);
this.state = State.DelayShow;
break;
}
case State.DelayShow:
{
if (this.delays.show >= config.delay.show) {
this.delays.show = 0;
this.state = State.Show;
break;
}
this.delays.show++;
break;
}
case State.Show:
{
core.showBlock = true;
this.delays.drop = 0;
// TODO: IRS & IHS
this.trace(core.block);
this.state = State.CheckDead;
break;
}
case State.Hold:
{
core.hold();
this.delays.drop = 0;
this.trace(core.block);
this.state = State.CheckDead;
break;
}
case State.CheckDead:
{
if (core.isDead()) {
this.state = State.End;
break;
}
this.state = State.CheckDrop;
break;
}
case State.CheckDrop:
{
if (core.canDrop()) {
this.state = State.DelayDrop;
} else {
this.resetLockDelay();
this.state = State.DelayLock;
}
break;
}
case State.DelayDrop:
{
if (!core.canDrop()) {
this.state = State.CheckDrop;
break;
}
if (this.delays.drop >= config.delay.drop) {
this.delays.drop = 0;
this.state = State.Drop;
break;
}
if (this.actInput(config)) {
if (this.state !== State.DelayDrop) {
break;
}
this.state = State.CheckDrop;
break;
}
this.delays.drop++;
break;
}
case State.Drop:
{
core.drop();
this.state = State.CheckDrop;
break;
}
case State.DelayLock:
{
if (core.canDrop()) {
this.state = State.CheckDrop;
break;
}
if (this.delays.lock >= config.delay.lock) {
this.delays.lock = 0;
this.state = State.Lock;
break;
}
if (this.actInput(config)) {
if (this.state !== State.DelayLock) {
break;
}
this.state = State.CheckDrop;
break;
}
this.delays.lock++;
break;
}
case State.Lock:
{
core.lock();
this.trace();
this.state = State.ClearLine;
break;
}
case State.ClearLine:
{
core.clearLines();
this.state = State.Create;
break;
}
case State.End:
{
// TODO
this.trace();
break;
}
}
}
}, {
key: "nextKey",
value: function nextKey(key, isDown) {
var core = this.core;
var state = this.keyState[key];
var previousIsDown = state.isDown;
if (isDown) {
state.isDown = true;
if (!previousIsDown) {
if (!core.showBlock) {
state.delayed = true;
}
state.start = this.frame;
}
if (core.showBlock) {
state.delayed = false;
}
if (state.delayed) {
state.count = 0;
} else {
state.count++;
}
} else {
state.isDown = false;
state.delayed = false;
state.start = -1;
state.count = -1;
state.previous = -1;
}
}
}, {
key: "nextInput",
value: function nextInput(input) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = Keys[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var key = _step3.value;
this.nextKey(key, input[key]);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: "loop",
value: function loop(_ref) {
var config = _ref.config;
var input = _ref.input;
this.nextInput(input);
var previousState = null;
while (previousState !== this.state) {
previousState = this.state;
this.act(config);
}
}
}, {
key: "next",
value: function next(_ref2) {
var frame = _ref2.frame;
var config = _ref2.config;
var input = _ref2.input;
if (this.state === State.End) {
return {
action: "complete"
};
}
for (var __ = 0; __ < frame; __++) {
this.loop({ config: config, input: input });
this.frame++;
}
return {
action: "next",
state: this.state,
data: this.core,
delays: this.delays
};
}
}]);
return Engine;
}();
exports.default = Engine;
},{"./core":391,"loglevel":314}],393:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
var _create = require("@most/create");
var _create2 = _interopRequireDefault(_create);
var _engine = require("./engine");
var _engine2 = _interopRequireDefault(_engine);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _ramda2.default.curry(function (_ref, ticker) {
var config = _ref.config;
var input = _ref.input;
return (0, _create2.default)(function (_next, complete, error) {
var engine = new _engine2.default();
var subscription = ticker.sample(function (frame, config, input) {
return { frame: frame, config: config, input: input };
}, ticker, config, input).map(engine.next.bind(engine)).subscribe({
next: function next(data) {
return _ramda2.default.cond([[_ramda2.default.equals("complete"), _ramda2.default.always(complete)], [_ramda2.default.equals("error"), _ramda2.default.always(error)], [_ramda2.default.T, _ramda2.default.always(_next)]])(data.action)(data);
},
complete: complete, error: error
});
return function () {
return subscription.unsubscribe();
};
});
});
},{"./engine":392,"@most/create":2,"ramda":383}],394:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
var _engine = require("./data/engine.json");
var _engine2 = _interopRequireDefault(_engine);
var _input = require("./data/input.json");
var _input2 = _interopRequireDefault(_input);
var _storage = require("./utils/storage");
var _storage2 = _interopRequireDefault(_storage);
var _ticker = require("./utils/ticker");
var _ticker2 = _interopRequireDefault(_ticker);
var _keyboard = require("./input/keyboard");
var _keyboard2 = _interopRequireDefault(_keyboard);
var _keyMapper = require("./input/utils/key-mapper");
var _keyMapper2 = _interopRequireDefault(_keyMapper);
var _keyStore = require("./input/utils/key-store");
var _keyStore2 = _interopRequireDefault(_keyStore);
var _engine3 = require("./engine");
var _engine4 = _interopRequireDefault(_engine3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Game = function () {
function Game() {
_classCallCheck(this, Game);
var ticker = (0, _ticker2.default)();
var input = (0, _keyboard2.default)(document).thru((0, _keyMapper2.default)(_storage2.default.listen("input.keyboard").map(_ramda2.default.merge(_input2.default.methods.keyboard)))).thru((0, _keyStore2.default)(_input2.default.keys));
var config = _storage2.default.listen("engine.config").map(_ramda2.default.merge(_engine2.default.config));
this.stream = ticker.thru((0, _engine4.default)({ config: config, input: input }));
}
_createClass(Game, [{
key: "run",
value: function run(handler) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.subscription = _this.stream.subscribe({
next: handler,
complete: resolve,
error: reject
});
});
}
}, {
key: "destroy",
value: function destroy() {
this.subscription.unsubscribe();
}
}]);
return Game;
}();
exports.default = Game;
},{"./data/engine.json":388,"./data/input.json":390,"./engine":393,"./input/keyboard":395,"./input/utils/key-mapper":396,"./input/utils/key-store":397,"./utils/storage":403,"./utils/ticker":404,"ramda":383}],395:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _most = require("most");
var most = _interopRequireWildcard(_most);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
exports.default = function (root) {
return most.merge(most.fromEvent("keydown", root).map(function (event) {
return {
type: "down",
key: event.code
};
}), most.fromEvent("keyup", root).map(function (event) {
return {
type: "up",
key: event.code
};
}));
};
},{"most":381}],396:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _ramda2.default.curry(function (mapper, action) {
return action.sample(function (action, mapper) {
return {
type: action.type,
key: mapper[action.key]
};
}, action, mapper.map(_ramda2.default.invertObj)).filter(_ramda2.default.prop("key"));
});
},{"ramda":383}],397:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _ramda2.default.curry(function (keys, action) {
var state = _ramda2.default.zipObj(keys, _ramda2.default.repeat(false, keys.length));
return action.map(function (action) {
if (keys.includes(action.key)) {
state = _ramda2.default.assoc(action.key, action.type === "down", state);
}
return state;
}).startWith(state);
});
},{"ramda":383}],398:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _ground = require("./data/ground.json");
var _ground2 = _interopRequireDefault(_ground);
var _block = require("./structs/block");
var _ground3 = require("./structs/ground");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var WIDTH = _ground2.default.size.width;
var HEIGHT = _ground2.default.size.height;
var Renderer = function () {
function Renderer() {
_classCallCheck(this, Renderer);
// TODO
this.width = WIDTH * 20;
this.height = HEIGHT * 20;
this.canvas = document.createElement("canvas");
this.canvas.width = this.width * window.devicePixelRatio;
this.canvas.height = this.height * window.devicePixelRatio;
this.canvas.style.width = this.width + "px";
this.canvas.style.height = this.height + "px";
document.body.append(this.canvas);
this.context = this.canvas.getContext("2d");
this.context.scale(window.devicePixelRatio, window.devicePixelRatio);
}
_createClass(Renderer, [{
key: "drawUnit",
value: function drawUnit(x, y, type) {
var mask = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
if (type !== _ground3.EMPTY) {
this.context.fillStyle = mask ? "#cfd8dc" : "#607d8b";
} else {
this.context.fillStyle = "#fafafa";
}
this.context.fillRect(x * 20 + 1, y * 20 + 1, 20 - 2, 20 - 2);
}
}, {
key: "drawBlock",
value: function drawBlock(block) {
var mask = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var data = (0, _block.getData)(block);
for (var x = 0; x < data.size.width; x++) {
for (var y = 0; y < data.size.height; y++) {
if (data.data[y][x]) {
this.drawUnit(x + block.x, y + block.y, block.type, mask);
}
}
}
}
}, {
key: "drawGround",
value: function drawGround(ground) {
for (var x = 0; x < WIDTH; x++) {
for (var y = 0; y < HEIGHT; y++) {
this.drawUnit(x, y, (0, _ground3.get)(ground, x, y));
}
}
}
}, {
key: "render",
value: function render(_ref) {
var data = _ref.data;
this.context.clearRect(0, 0, this.width, this.height);
this.drawGround(data.ground);
this.drawBlock(data.maskBlock, true);
this.drawBlock(data.block);
}
}]);
return Renderer;
}();
exports.default = Renderer;
},{"./data/ground.json":389,"./structs/block":399,"./structs/ground":400}],399:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getData = exports.moveBy = exports.moveTo = exports.ROTATE_RIGHT = exports.ROTATE_LEFT = exports.rotate = exports.clone = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
var _block = require("../data/block.json");
var _block2 = _interopRequireDefault(_block);
var _matrix = require("../utils/matrix");
var matrix = _interopRequireWildcard(_matrix);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var types = _ramda2.default.addIndex(_ramda2.default.map)(function (item, type) {
return _ramda2.default.zipWith(function (data, position) {
return _extends({}, item, { type: type, data: data, position: position });
}, _ramda2.default.scan(matrix.rotate, item.data, _ramda2.default.range(1, 4)), item.position);
}, _block2.default.types);
exports.default = function () {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var type = _ref.type;
var _ref$rotate = _ref.rotate;
var rotate = _ref$rotate === undefined ? 0 : _ref$rotate;
var _ref$x = _ref.x;
var x = _ref$x === undefined ? 0 : _ref$x;
var _ref$y = _ref.y;
var y = _ref$y === undefined ? 0 : _ref$y;
return { type: type, rotate: rotate, x: x, y: y };
};
var clone = exports.clone = function clone(block) {
return _extends({}, block);
};
var rotate = exports.rotate = function rotate(block, direction) {
return _extends({}, block, {
rotate: _ramda2.default.mathMod(block.rotate + direction, 4)
});
};
var ROTATE_LEFT = exports.ROTATE_LEFT = -1;
var ROTATE_RIGHT = exports.ROTATE_RIGHT = 1;
var moveTo = exports.moveTo = function moveTo(block, x, y) {
return _extends({}, block, { x: x, y: y });
};
var moveBy = exports.moveBy = function moveBy(block, x, y) {
return _extends({}, block, {
x: block.x + x,
y: block.y + y
});
};
var getData = exports.getData = function getData(_ref2) {
var type = _ref2.type;
var rotate = _ref2.rotate;
return types[type][rotate];
};
},{"../data/block.json":387,"../utils/matrix":401,"ramda":383}],400:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clearLines = exports.clearLine = exports.isFull = exports.place = exports.checkAvailable = exports.set = exports.get = exports.isIn = exports.WALL = exports.EMPTY = undefined;
var _ground = require("../data/ground.json");
var _ground2 = _interopRequireDefault(_ground);
var _block = require("./block");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var WIDTH = _ground2.default.size.width;
var HEIGHT = _ground2.default.size.height;
var P_LEFT = _ground2.default.padding.left;
var P_RIGHT = _ground2.default.padding.right;
var P_TOP = _ground2.default.padding.top;
var P_BOTTOM = _ground2.default.padding.bottom;
var P_WIDTH = P_LEFT + WIDTH + P_RIGHT;
var P_HEIGHT = P_TOP + HEIGHT + P_BOTTOM;
var EMPTY = exports.EMPTY = -1;
var WALL = exports.WALL = 0xFF;
exports.default = function () {
return {
data: new Int8Array(P_WIDTH * P_HEIGHT).fill(EMPTY)
};
};
var isIn = exports.isIn = function isIn(ground, x, y) {
return x >= -P_LEFT && x < WIDTH + P_RIGHT && y >= -P_TOP && y < HEIGHT + P_BOTTOM;
};
var get = exports.get = function get(ground, x, y) {
if (!isIn(ground, x, y)) {
return WALL;
}
return ground.data[(P_TOP + y) * P_WIDTH + P_LEFT + x];
};
var set = exports.set = function set(ground, x, y, type) {
if (!isIn(ground, x, y)) {
return;
}
ground.data[(P_TOP + y) * P_WIDTH + P_LEFT + x] = type;
};
var checkAvailable = exports.checkAvailable = function checkAvailable(ground, block) {
var data = (0, _block.getData)(block);
for (var x = 0; x < data.size.width; x++) {
for (var y = 0; y < data.size.height; y++) {
if (data.data[y][x] && get(ground, x + block.x, y + block.y) !== EMPTY) {
return false;
}
}
}
return true;
};
var place = exports.place = function place(ground, block) {
var data = (0, _block.getData)(block);
for (var x = 0; x < data.size.width; x++) {
for (var y = 0; y < data.size.height; y++) {
if (data.data[y][x]) {
set(ground, x + block.x, y + block.y, block.type);
}
}
}
};
var isFull = exports.isFull = function isFull(ground, y) {
for (var x = -P_LEFT; x < WIDTH + P_RIGHT; x++) {
if (get(ground, x, y) === EMPTY) {
return false;
}
}
return true;
};
var clearLine = exports.clearLine = function clearLine(ground, lineY) {
for (var y = lineY; y > -P_TOP; y--) {
for (var x = -P_LEFT; x < WIDTH + P_RIGHT; x++) {
set(ground, x, y, get(ground, x, y - 1));
}
}
for (var _x = -P_LEFT; _x < WIDTH + P_RIGHT; _x++) {
set(ground, _x, -P_TOP, EMPTY);
}
};
var clearLines = exports.clearLines = function clearLines(ground) {
for (var y = -P_TOP; y < HEIGHT + P_BOTTOM; y++) {
if (isFull(ground, y)) {
clearLine(ground, y);
}
}
};
},{"../data/ground.json":389,"./block":399}],401:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.rotate = undefined;
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var rotate = exports.rotate = _ramda2.default.compose(_ramda2.default.map(_ramda2.default.reverse), _ramda2.default.transpose);
},{"ramda":383}],402:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _mersennetwister = require("mersennetwister");
var _mersennetwister2 = _interopRequireDefault(_mersennetwister);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Random = function () {
function Random() {
var seed = arguments.length <= 0 || arguments[0] === undefined ? Date.now() : arguments[0];
_classCallCheck(this, Random);
this.seed = seed;
this.internal = new _mersennetwister2.default(seed);
}
_createClass(Random, [{
key: "next",
value: function next(max) {
return this.internal.int() % max;
}
}]);
return Random;
}();
exports.default = Random;
},{"mersennetwister":315}],403:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _ramda = require("ramda");
var _ramda2 = _interopRequireDefault(_ramda);
var _most = require("most");
var _most2 = _interopRequireDefault(_most);
var _events = require("events");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Storage = function (_EventEmitter) {
_inherits(Storage, _EventEmitter);
function Storage(storage) {
_classCallCheck(this, Storage);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Storage).call(this));
_this.storage = storage;
_most2.default.fromEvent("storage", window).filter(_ramda2.default.propEq("storageArea", storage)).forEach(function (_ref) {
var key = _ref.key;
_this.emit("change", { key: key });
});
return _this;
}
_createClass(Storage, [{
key: "get",
value: function get(key) {
try {
return JSON.parse(this.storage.getItem(key));
} catch (error) {
return null;
}
}
}, {
key: "set",
value: function set(key, value) {
this.storage.setItem(key, JSON.stringify(value));
this.emit("change", { key: key });
}
}, {
key: "delete",
value: function _delete(key) {
this.storage.removeItem(key);
this.emit("change", { key: key });
}
}, {
key: "listen",
value: function listen(key) {
var _this2 = this;
return _most2.default.fromEvent("change", this).startWith({ key: key }).filter(_ramda2.default.propEq("key", key)).map(function () {
return _this2.get(key);
});
}
}]);
return Storage;
}(_events.EventEmitter);
var storage = new Storage(localStorage);
System.global.storage = storage;
exports.default = storage;
},{"events":313,"most":381,"ramda":383}],404:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _create = require("@most/create");
var _create2 = _interopRequireDefault(_create);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function () {
return (0, _create2.default)(function (next) {
var paused = false;
var handler = -1;
function callback() {
next(1);
if (!paused) {
handler = setTimeout(callback, 1000 / 20);
}
}
handler = setTimeout(callback, 1000 / 20);
return function () {
paused = true;
if (handler !== -1) {
cancelAnimationFrame(handler);
}
};
});
};
},{"@most/create":2}]},{},[1]);
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8" />
<title>Intris</title>
</head>
<body>
<script src="./build.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment