Created
November 28, 2019 12:58
-
-
Save aninde/5ad9b1d3613eeab39760805c7740be98 to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* Copyright (c) HANDSONCODE sp. z o. o. | |
* | |
* HANDSONTABLE is a software distributed by HANDSONCODE sp. z o. o., | |
* a Polish corporation, based in Gdynia, Poland, at 96/98 Aleja Zwycięstwa, | |
* registered with the National Court Register under number 538651, | |
* EU tax ID number: PL5862294002, share capital: PLN 62,800.00. | |
* | |
* This software is protected by applicable copyright laws, including | |
* international treaties, and dual-licensed – depending on whether | |
* your use is intended for or may result in commercial advantage | |
* or monetary compensation (commercial purposes), or not. | |
* | |
* If your use involves only such purposes as research, private study, | |
* evaluation and the like, you agree to be bound by the terms included | |
* in the "handsontable-non-commercial-license.pdf" file, available | |
* in the main directory of this software repository. | |
* | |
* By installing, copying, or otherwise using this software for | |
* commercial purposes, you agree to be bound by the terms included | |
* in the "handsontable-general-terms.pdf" file, available in the main | |
* directory of this software repository. | |
* | |
* HANDSONCODE PROVIDES THIS SOFTWARE ON AN "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND. IN NO EVENT | |
* AND UNDER NO LEGAL THEORY, SHALL HANDSONCODE BE LIABLE | |
* TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, | |
* INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING | |
* FROM USE OR INABILITY TO USE THIS SOFTWARE. | |
* | |
* Version: 7.2.2 | |
* Release date: 23/10/2019 (built at 28/11/2019 13:47:52) | |
*/ | |
(function webpackUniversalModuleDefinition(root, factory) { | |
if(typeof exports === 'object' && typeof module === 'object') | |
module.exports = factory(); | |
else if(typeof define === 'function' && define.amd) | |
define("Handsontable", [], factory); | |
else if(typeof exports === 'object') | |
exports["Handsontable"] = factory(); | |
else | |
root["Handsontable"] = factory(); | |
})(typeof self !== 'undefined' ? self : this, function() { | |
return /******/ (function(modules) { // webpackBootstrap | |
/******/ // The module cache | |
/******/ var installedModules = {}; | |
/******/ | |
/******/ // The require function | |
/******/ function __webpack_require__(moduleId) { | |
/******/ | |
/******/ // Check if module is in cache | |
/******/ if(installedModules[moduleId]) { | |
/******/ return installedModules[moduleId].exports; | |
/******/ } | |
/******/ // Create a new module (and put it into the cache) | |
/******/ var module = installedModules[moduleId] = { | |
/******/ i: moduleId, | |
/******/ l: false, | |
/******/ exports: {} | |
/******/ }; | |
/******/ | |
/******/ // Execute the module function | |
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); | |
/******/ | |
/******/ // Flag the module as loaded | |
/******/ module.l = true; | |
/******/ | |
/******/ // Return the exports of the module | |
/******/ return module.exports; | |
/******/ } | |
/******/ | |
/******/ | |
/******/ // expose the modules object (__webpack_modules__) | |
/******/ __webpack_require__.m = modules; | |
/******/ | |
/******/ // expose the module cache | |
/******/ __webpack_require__.c = installedModules; | |
/******/ | |
/******/ // define getter function for harmony exports | |
/******/ __webpack_require__.d = function(exports, name, getter) { | |
/******/ if(!__webpack_require__.o(exports, name)) { | |
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); | |
/******/ } | |
/******/ }; | |
/******/ | |
/******/ // define __esModule on exports | |
/******/ __webpack_require__.r = function(exports) { | |
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { | |
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); | |
/******/ } | |
/******/ Object.defineProperty(exports, '__esModule', { value: true }); | |
/******/ }; | |
/******/ | |
/******/ // create a fake namespace object | |
/******/ // mode & 1: value is a module id, require it | |
/******/ // mode & 2: merge all properties of value into the ns | |
/******/ // mode & 4: return value when already ns object | |
/******/ // mode & 8|1: behave like require | |
/******/ __webpack_require__.t = function(value, mode) { | |
/******/ if(mode & 1) value = __webpack_require__(value); | |
/******/ if(mode & 8) return value; | |
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; | |
/******/ var ns = Object.create(null); | |
/******/ __webpack_require__.r(ns); | |
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); | |
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); | |
/******/ return ns; | |
/******/ }; | |
/******/ | |
/******/ // getDefaultExport function for compatibility with non-harmony modules | |
/******/ __webpack_require__.n = function(module) { | |
/******/ var getter = module && module.__esModule ? | |
/******/ function getDefault() { return module['default']; } : | |
/******/ function getModuleExports() { return module; }; | |
/******/ __webpack_require__.d(getter, 'a', getter); | |
/******/ return getter; | |
/******/ }; | |
/******/ | |
/******/ // Object.prototype.hasOwnProperty.call | |
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; | |
/******/ | |
/******/ // __webpack_public_path__ | |
/******/ __webpack_require__.p = ""; | |
/******/ | |
/******/ | |
/******/ // Load entry module and return exports | |
/******/ return __webpack_require__(__webpack_require__.s = 406); | |
/******/ }) | |
/************************************************************************/ | |
/******/ ([ | |
/* 0 */ | |
/***/ (function(module, exports) { | |
function _interopRequireDefault(obj) { | |
return obj && obj.__esModule ? obj : { | |
"default": obj | |
}; | |
} | |
module.exports = _interopRequireDefault; | |
/***/ }), | |
/* 1 */ | |
/***/ (function(module, exports) { | |
function _classCallCheck(instance, Constructor) { | |
if (!(instance instanceof Constructor)) { | |
throw new TypeError("Cannot call a class as a function"); | |
} | |
} | |
module.exports = _classCallCheck; | |
/***/ }), | |
/* 2 */ | |
/***/ (function(module, exports) { | |
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); | |
} | |
} | |
function _createClass(Constructor, protoProps, staticProps) { | |
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | |
if (staticProps) _defineProperties(Constructor, staticProps); | |
return Constructor; | |
} | |
module.exports = _createClass; | |
/***/ }), | |
/* 3 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(17); | |
__webpack_require__(48); | |
__webpack_require__(15); | |
__webpack_require__(11); | |
exports.__esModule = true; | |
exports.to2dArray = to2dArray; | |
exports.extendArray = extendArray; | |
exports.pivot = pivot; | |
exports.arrayReduce = arrayReduce; | |
exports.arrayFilter = arrayFilter; | |
exports.arrayMap = arrayMap; | |
exports.arrayEach = arrayEach; | |
exports.arraySum = arraySum; | |
exports.arrayMax = arrayMax; | |
exports.arrayMin = arrayMin; | |
exports.arrayAvg = arrayAvg; | |
exports.arrayFlatten = arrayFlatten; | |
exports.arrayUnique = arrayUnique; | |
function to2dArray(arr) { | |
var ilen = arr.length; | |
var i = 0; | |
while (i < ilen) { | |
arr[i] = [arr[i]]; | |
i += 1; | |
} | |
} | |
function extendArray(arr, extension) { | |
var ilen = extension.length; | |
var i = 0; | |
while (i < ilen) { | |
arr.push(extension[i]); | |
i += 1; | |
} | |
} | |
function pivot(arr) { | |
var pivotedArr = []; | |
if (!arr || arr.length === 0 || !arr[0] || arr[0].length === 0) { | |
return pivotedArr; | |
} | |
var rowCount = arr.length; | |
var colCount = arr[0].length; | |
for (var i = 0; i < rowCount; i++) { | |
for (var j = 0; j < colCount; j++) { | |
if (!pivotedArr[j]) { | |
pivotedArr[j] = []; | |
} | |
pivotedArr[j][i] = arr[i][j]; | |
} | |
} | |
return pivotedArr; | |
} | |
/** | |
* A specialized version of `.reduce` for arrays without support for callback | |
* shorthands and `this` binding. | |
* | |
* {@link https://github.com/lodash/lodash/blob/master/lodash.js} | |
* | |
* @param {Array} array The array to iterate over. | |
* @param {Function} iteratee The function invoked per iteration. | |
* @param {*} [accumulator] The initial value. | |
* @param {Boolean} [initFromArray] Specify using the first element of `array` as the initial value. | |
* @returns {*} Returns the accumulated value. | |
*/ | |
function arrayReduce(array, iteratee, accumulator, initFromArray) { | |
var index = -1; | |
var iterable = array; | |
var result = accumulator; | |
if (!Array.isArray(array)) { | |
iterable = Array.from(array); | |
} | |
var length = iterable.length; | |
if (initFromArray && length) { | |
index += 1; | |
result = iterable[index]; | |
} | |
index += 1; | |
while (index < length) { | |
result = iteratee(result, iterable[index], index, iterable); | |
index += 1; | |
} | |
return result; | |
} | |
/** | |
* A specialized version of `.filter` for arrays without support for callback | |
* shorthands and `this` binding. | |
* | |
* {@link https://github.com/lodash/lodash/blob/master/lodash.js} | |
* | |
* @param {Array} array The array to iterate over. | |
* @param {Function} predicate The function invoked per iteration. | |
* @returns {Array} Returns the new filtered array. | |
*/ | |
function arrayFilter(array, predicate) { | |
var index = 0; | |
var iterable = array; | |
if (!Array.isArray(array)) { | |
iterable = Array.from(array); | |
} | |
var length = iterable.length; | |
var result = []; | |
var resIndex = -1; | |
while (index < length) { | |
var value = iterable[index]; | |
if (predicate(value, index, iterable)) { | |
resIndex += 1; | |
result[resIndex] = value; | |
} | |
index += 1; | |
} | |
return result; | |
} | |
/** | |
* A specialized version of `.map` for arrays without support for callback | |
* shorthands and `this` binding. | |
* | |
* @param {Array} array The array to iterate over. | |
* @param {Function} iteratee The function invoked per iteration. | |
* @returns {Array} Returns the new filtered array. | |
*/ | |
function arrayMap(array, iteratee) { | |
var index = 0; | |
var iterable = array; | |
if (!Array.isArray(array)) { | |
iterable = Array.from(array); | |
} | |
var length = iterable.length; | |
var result = []; | |
var resIndex = -1; | |
while (index < length) { | |
var value = iterable[index]; | |
resIndex += 1; | |
result[resIndex] = iteratee(value, index, iterable); | |
index += 1; | |
} | |
return result; | |
} | |
/** | |
* A specialized version of `.forEach` for arrays without support for callback | |
* shorthands and `this` binding. | |
* | |
* {@link https://github.com/lodash/lodash/blob/master/lodash.js} | |
* | |
* @param {Array|*} array The array to iterate over or an any element with implemented iterator protocol. | |
* @param {Function} iteratee The function invoked per iteration. | |
* @returns {Array} Returns `array`. | |
*/ | |
function arrayEach(array, iteratee) { | |
var index = 0; | |
var iterable = array; | |
if (!Array.isArray(array)) { | |
iterable = Array.from(array); | |
} | |
var length = iterable.length; | |
while (index < length) { | |
if (iteratee(iterable[index], index, iterable) === false) { | |
break; | |
} | |
index += 1; | |
} | |
return array; | |
} | |
/** | |
* Calculate sum value for each item of the array. | |
* | |
* @param {Array} array The array to process. | |
* @returns {Number} Returns calculated sum value. | |
*/ | |
function arraySum(array) { | |
return arrayReduce(array, function (a, b) { | |
return a + b; | |
}, 0); | |
} | |
/** | |
* Returns the highest value from an array. Can be array of numbers or array of strings. | |
* NOTICE: Mixed values is not supported. | |
* | |
* @param {Array} array The array to process. | |
* @returns {Number} Returns the highest value from an array. | |
*/ | |
function arrayMax(array) { | |
return arrayReduce(array, function (a, b) { | |
return a > b ? a : b; | |
}, Array.isArray(array) ? array[0] : void 0); | |
} | |
/** | |
* Returns the lowest value from an array. Can be array of numbers or array of strings. | |
* NOTICE: Mixed values is not supported. | |
* | |
* @param {Array} array The array to process. | |
* @returns {Number} Returns the lowest value from an array. | |
*/ | |
function arrayMin(array) { | |
return arrayReduce(array, function (a, b) { | |
return a < b ? a : b; | |
}, Array.isArray(array) ? array[0] : void 0); | |
} | |
/** | |
* Calculate average value for each item of the array. | |
* | |
* @param {Array} array The array to process. | |
* @returns {Number} Returns calculated average value. | |
*/ | |
function arrayAvg(array) { | |
if (!array.length) { | |
return 0; | |
} | |
return arraySum(array) / array.length; | |
} | |
/** | |
* Flatten multidimensional array. | |
* | |
* @param {Array} array Array of Arrays | |
* @returns {Array} | |
*/ | |
function arrayFlatten(array) { | |
return arrayReduce(array, function (initial, value) { | |
return initial.concat(Array.isArray(value) ? arrayFlatten(value) : value); | |
}, []); | |
} | |
/** | |
* Unique values in the array. | |
* | |
* @param {Array} array The array to process. | |
* @returns {Array} | |
*/ | |
function arrayUnique(array) { | |
var unique = []; | |
arrayEach(array, function (value) { | |
if (unique.indexOf(value) === -1) { | |
unique.push(value); | |
} | |
}); | |
return unique; | |
} | |
/***/ }), | |
/* 4 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(9); | |
__webpack_require__(39); | |
__webpack_require__(53); | |
exports.__esModule = true; | |
exports.duckSchema = duckSchema; | |
exports.inherit = inherit; | |
exports.extend = extend; | |
exports.deepExtend = deepExtend; | |
exports.deepClone = deepClone; | |
exports.clone = clone; | |
exports.mixin = mixin; | |
exports.isObjectEqual = isObjectEqual; | |
exports.isObject = isObject; | |
exports.defineGetter = defineGetter; | |
exports.objectEach = objectEach; | |
exports.getProperty = getProperty; | |
exports.deepObjectSize = deepObjectSize; | |
exports.createObjectPropListener = createObjectPropListener; | |
exports.hasOwnProperty = hasOwnProperty; | |
var _defineProperty2 = _interopRequireDefault(__webpack_require__(74)); | |
var _typeof2 = _interopRequireDefault(__webpack_require__(46)); | |
var _array = __webpack_require__(3); | |
/** | |
* Generate schema for passed object. | |
* | |
* @param {Array|Object} object | |
* @returns {Array|Object} | |
*/ | |
function duckSchema(object) { | |
var schema; | |
if (Array.isArray(object)) { | |
schema = []; | |
} else { | |
schema = {}; | |
objectEach(object, function (value, key) { | |
if (key === '__children') { | |
return; | |
} | |
if (value && (0, _typeof2.default)(value) === 'object' && !Array.isArray(value)) { | |
schema[key] = duckSchema(value); | |
} else if (Array.isArray(value)) { | |
if (value.length && (0, _typeof2.default)(value[0]) === 'object' && !Array.isArray(value[0])) { | |
schema[key] = [duckSchema(value[0])]; | |
} else { | |
schema[key] = []; | |
} | |
} else { | |
schema[key] = null; | |
} | |
}); | |
} | |
return schema; | |
} | |
/** | |
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. | |
* Creates temporary dummy function to call it as constructor. | |
* Described in ticket: https://github.com/handsontable/handsontable/pull/516 | |
* | |
* @param {Object} Child child class | |
* @param {Object} Parent parent class | |
* @return {Object} extended Child | |
*/ | |
function inherit(Child, Parent) { | |
Parent.prototype.constructor = Parent; | |
Child.prototype = new Parent(); | |
Child.prototype.constructor = Child; | |
return Child; | |
} | |
/** | |
* Perform shallow extend of a target object with extension's own properties. | |
* | |
* @param {Object} target An object that will receive the new properties. | |
* @param {Object} extension An object containing additional properties to merge into the target. | |
*/ | |
function extend(target, extension) { | |
objectEach(extension, function (value, key) { | |
target[key] = value; | |
}); | |
return target; | |
} | |
/** | |
* Perform deep extend of a target object with extension's own properties. | |
* | |
* @param {Object} target An object that will receive the new properties. | |
* @param {Object} extension An object containing additional properties to merge into the target. | |
*/ | |
function deepExtend(target, extension) { | |
objectEach(extension, function (value, key) { | |
if (extension[key] && (0, _typeof2.default)(extension[key]) === 'object') { | |
if (!target[key]) { | |
if (Array.isArray(extension[key])) { | |
target[key] = []; | |
} else if (Object.prototype.toString.call(extension[key]) === '[object Date]') { | |
target[key] = extension[key]; | |
} else { | |
target[key] = {}; | |
} | |
} | |
deepExtend(target[key], extension[key]); | |
} else { | |
target[key] = extension[key]; | |
} | |
}); | |
} | |
/** | |
* Perform deep clone of an object. | |
* WARNING! Only clones JSON properties. Will cause error when `obj` contains a function, Date, etc. | |
* | |
* @param {Object} obj An object that will be cloned | |
* @return {Object} | |
*/ | |
function deepClone(obj) { | |
if ((0, _typeof2.default)(obj) === 'object') { | |
return JSON.parse(JSON.stringify(obj)); | |
} | |
return obj; | |
} | |
/** | |
* Shallow clone object. | |
* | |
* @param {Object} object | |
* @returns {Object} | |
*/ | |
function clone(object) { | |
var result = {}; | |
objectEach(object, function (value, key) { | |
result[key] = value; | |
}); | |
return result; | |
} | |
/** | |
* Extend the Base object (usually prototype) of the functionality the `mixins` objects. | |
* | |
* @param {Object} Base Base object which will be extended. | |
* @param {Object} mixins The object of the functionality will be "copied". | |
* @returns {Object} | |
*/ | |
function mixin(Base) { | |
if (!Base.MIXINS) { | |
Base.MIXINS = []; | |
} | |
for (var _len = arguments.length, mixins = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
mixins[_key - 1] = arguments[_key]; | |
} | |
(0, _array.arrayEach)(mixins, function (mixinItem) { | |
Base.MIXINS.push(mixinItem.MIXIN_NAME); | |
objectEach(mixinItem, function (value, key) { | |
if (Base.prototype[key] !== void 0) { | |
throw new Error("Mixin conflict. Property '".concat(key, "' already exist and cannot be overwritten.")); | |
} | |
if (typeof value === 'function') { | |
Base.prototype[key] = value; | |
} else { | |
var getter = function _getter(property, initialValue) { | |
var propertyName = "_".concat(property); | |
var initValue = function initValue(newValue) { | |
var result = newValue; | |
if (Array.isArray(result) || isObject(result)) { | |
result = deepClone(result); | |
} | |
return result; | |
}; | |
return function () { | |
if (this[propertyName] === void 0) { | |
this[propertyName] = initValue(initialValue); | |
} | |
return this[propertyName]; | |
}; | |
}; | |
var setter = function _setter(property) { | |
var propertyName = "_".concat(property); | |
return function (newValue) { | |
this[propertyName] = newValue; | |
}; | |
}; | |
Object.defineProperty(Base.prototype, key, { | |
get: getter(key, value), | |
set: setter(key), | |
configurable: true | |
}); | |
} | |
}); | |
}); | |
return Base; | |
} | |
/** | |
* Checks if two objects or arrays are (deep) equal | |
* | |
* @param {Object|Array} object1 | |
* @param {Object|Array} object2 | |
* @returns {Boolean} | |
*/ | |
function isObjectEqual(object1, object2) { | |
return JSON.stringify(object1) === JSON.stringify(object2); | |
} | |
/** | |
* Determines whether given object is a plain Object. | |
* Note: String and Array are not plain Objects | |
* @param {*} obj | |
* @returns {boolean} | |
*/ | |
function isObject(obj) { | |
return Object.prototype.toString.call(obj) === '[object Object]'; | |
} | |
function defineGetter(object, property, value, options) { | |
options.value = value; | |
options.writable = options.writable !== false; | |
options.enumerable = options.enumerable !== false; | |
options.configurable = options.configurable !== false; | |
Object.defineProperty(object, property, options); | |
} | |
/** | |
* A specialized version of `.forEach` for objects. | |
* | |
* @param {Object} object The object to iterate over. | |
* @param {Function} iteratee The function invoked per iteration. | |
* @returns {Object} Returns `object`. | |
*/ | |
function objectEach(object, iteratee) { | |
// eslint-disable-next-line no-restricted-syntax | |
for (var key in object) { | |
if (!object.hasOwnProperty || object.hasOwnProperty && Object.prototype.hasOwnProperty.call(object, key)) { | |
if (iteratee(object[key], key, object) === false) { | |
break; | |
} | |
} | |
} | |
return object; | |
} | |
/** | |
* Get object property by its name. Access to sub properties can be achieved by dot notation (e.q. `'foo.bar.baz'`). | |
* | |
* @param {Object} object Object which value will be exported. | |
* @param {String} name Object property name. | |
* @returns {*} | |
*/ | |
function getProperty(object, name) { | |
var names = name.split('.'); | |
var result = object; | |
objectEach(names, function (nameItem) { | |
result = result[nameItem]; | |
if (result === void 0) { | |
result = void 0; | |
return false; | |
} | |
}); | |
return result; | |
} | |
/** | |
* Return object length (recursively). | |
* | |
* @param {*} object Object for which we want get length. | |
* @returns {Number} | |
*/ | |
function deepObjectSize(object) { | |
if (!isObject(object)) { | |
return 0; | |
} | |
var recursObjLen = function recursObjLen(obj) { | |
var result = 0; | |
if (isObject(obj)) { | |
objectEach(obj, function (key) { | |
result += recursObjLen(key); | |
}); | |
} else { | |
result += 1; | |
} | |
return result; | |
}; | |
return recursObjLen(object); | |
} | |
/** | |
* Create object with property where its value change will be observed. | |
* | |
* @param {*} [defaultValue=undefined] Default value. | |
* @param {String} [propertyToListen='value'] Property to listen. | |
* @returns {Object} | |
*/ | |
function createObjectPropListener(defaultValue) { | |
var _holder; | |
var propertyToListen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'value'; | |
var privateProperty = "_".concat(propertyToListen); | |
var holder = (_holder = { | |
_touched: false | |
}, (0, _defineProperty2.default)(_holder, privateProperty, defaultValue), (0, _defineProperty2.default)(_holder, "isTouched", function isTouched() { | |
return this._touched; | |
}), _holder); | |
Object.defineProperty(holder, propertyToListen, { | |
get: function get() { | |
return this[privateProperty]; | |
}, | |
set: function set(value) { | |
this._touched = true; | |
this[privateProperty] = value; | |
}, | |
enumerable: true, | |
configurable: true | |
}); | |
return holder; | |
} | |
/** | |
* Check if at specified `key` there is any value for `object`. | |
* | |
* @param {Object} object Object to search value at specyfic key. | |
* @param {String} key String key to check. | |
*/ | |
function hasOwnProperty(object, key) { | |
return Object.prototype.hasOwnProperty.call(object, key); | |
} | |
/***/ }), | |
/* 5 */ | |
/***/ (function(module, exports) { | |
function _getPrototypeOf(o) { | |
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | |
return o.__proto__ || Object.getPrototypeOf(o); | |
}; | |
return _getPrototypeOf(o); | |
} | |
module.exports = _getPrototypeOf; | |
/***/ }), | |
/* 6 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var _typeof = __webpack_require__(46); | |
var assertThisInitialized = __webpack_require__(30); | |
function _possibleConstructorReturn(self, call) { | |
if (call && (_typeof(call) === "object" || typeof call === "function")) { | |
return call; | |
} | |
return assertThisInitialized(self); | |
} | |
module.exports = _possibleConstructorReturn; | |
/***/ }), | |
/* 7 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var setPrototypeOf = __webpack_require__(215); | |
function _inherits(subClass, superClass) { | |
if (typeof superClass !== "function" && superClass !== null) { | |
throw new TypeError("Super expression must either be null or a function"); | |
} | |
subClass.prototype = Object.create(superClass && superClass.prototype, { | |
constructor: { | |
value: subClass, | |
writable: true, | |
configurable: true | |
} | |
}); | |
if (superClass) setPrototypeOf(subClass, superClass); | |
} | |
module.exports = _inherits; | |
/***/ }), | |
/* 8 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(17); | |
__webpack_require__(40); | |
__webpack_require__(27); | |
__webpack_require__(15); | |
__webpack_require__(49); | |
__webpack_require__(31); | |
__webpack_require__(168); | |
__webpack_require__(9); | |
__webpack_require__(112); | |
__webpack_require__(39); | |
__webpack_require__(35); | |
__webpack_require__(42); | |
__webpack_require__(53); | |
__webpack_require__(137); | |
exports.__esModule = true; | |
exports.getParent = getParent; | |
exports.getFrameElement = getFrameElement; | |
exports.getParentWindow = getParentWindow; | |
exports.hasAccessToParentWindow = hasAccessToParentWindow; | |
exports.closest = closest; | |
exports.closestDown = closestDown; | |
exports.isChildOf = isChildOf; | |
exports.isChildOfWebComponentTable = isChildOfWebComponentTable; | |
exports.polymerWrap = polymerWrap; | |
exports.polymerUnwrap = polymerUnwrap; | |
exports.index = index; | |
exports.overlayContainsElement = overlayContainsElement; | |
exports.hasClass = hasClass; | |
exports.addClass = addClass; | |
exports.removeClass = removeClass; | |
exports.removeTextNodes = removeTextNodes; | |
exports.empty = empty; | |
exports.fastInnerHTML = fastInnerHTML; | |
exports.fastInnerText = fastInnerText; | |
exports.isVisible = isVisible; | |
exports.offset = offset; | |
exports.getWindowScrollTop = getWindowScrollTop; | |
exports.getWindowScrollLeft = getWindowScrollLeft; | |
exports.getScrollTop = getScrollTop; | |
exports.getScrollLeft = getScrollLeft; | |
exports.getScrollableElement = getScrollableElement; | |
exports.getTrimmingContainer = getTrimmingContainer; | |
exports.getStyle = getStyle; | |
exports.matchesCSSRules = matchesCSSRules; | |
exports.getComputedStyle = getComputedStyle; | |
exports.outerWidth = outerWidth; | |
exports.outerHeight = outerHeight; | |
exports.innerHeight = innerHeight; | |
exports.innerWidth = innerWidth; | |
exports.addEvent = addEvent; | |
exports.removeEvent = removeEvent; | |
exports.getCaretPosition = getCaretPosition; | |
exports.getSelectionEndPosition = getSelectionEndPosition; | |
exports.getSelectionText = getSelectionText; | |
exports.clearTextSelection = clearTextSelection; | |
exports.setCaretPosition = setCaretPosition; | |
exports.getScrollbarWidth = getScrollbarWidth; | |
exports.hasVerticalScrollbar = hasVerticalScrollbar; | |
exports.hasHorizontalScrollbar = hasHorizontalScrollbar; | |
exports.setOverlayPosition = setOverlayPosition; | |
exports.getCssTransform = getCssTransform; | |
exports.resetCssTransform = resetCssTransform; | |
exports.isInput = isInput; | |
exports.isOutsideInput = isOutsideInput; | |
exports.selectElementIfAllowed = selectElementIfAllowed; | |
exports.HTML_CHARACTERS = void 0; | |
var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(33)); | |
var _browser = __webpack_require__(76); | |
var _feature = __webpack_require__(81); | |
/** | |
* Get the parent of the specified node in the DOM tree. | |
* | |
* @param {HTMLElement} element Element from which traversing is started. | |
* @param {Number} [level=0] Traversing deep level. | |
* @returns {HTMLElement|null} | |
*/ | |
function getParent(element) { | |
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; | |
var iteration = -1; | |
var parent = null; | |
var elementToCheck = element; | |
while (elementToCheck !== null) { | |
if (iteration === level) { | |
parent = elementToCheck; | |
break; | |
} | |
if (elementToCheck.host && elementToCheck.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { | |
elementToCheck = elementToCheck.host; | |
} else { | |
iteration += 1; | |
elementToCheck = elementToCheck.parentNode; | |
} | |
} | |
return parent; | |
} | |
/** | |
* Gets `frameElement` of the specified frame. Returns null if it is a top frame or if script has no access to read property. | |
* | |
* @param {Window} frame Frame from which should be get frameElement in safe way. | |
* @returns {HTMLIFrameElement|null} | |
*/ | |
function getFrameElement(frame) { | |
return Object.getPrototypeOf(frame.parent) && frame.frameElement; | |
} | |
/** | |
* Gets parent frame of the specified frame. Returns null if it is a top frame or if script has no access to read property. | |
* | |
* @param {Window} frame Frame from which should be get frameElement in safe way. | |
* @returns {Window|null} | |
*/ | |
function getParentWindow(frame) { | |
return getFrameElement(frame) && frame.parent; | |
} | |
/** | |
* Checks if script has access to read from parent frame of specified frame. | |
* @param {Window} frame Frame from which should be get frameElement in safe way. | |
*/ | |
function hasAccessToParentWindow(frame) { | |
return !!Object.getPrototypeOf(frame.parent); | |
} | |
/** | |
* Goes up the DOM tree (including given element) until it finds an element that matches the nodes or nodes name. | |
* This method goes up through web components. | |
* | |
* @param {HTMLElement} element Element from which traversing is started | |
* @param {Array} nodes Array of elements or Array of elements name | |
* @param {HTMLElement} [until] | |
* @returns {HTMLElement|null} | |
*/ | |
function closest(element, nodes, until) { | |
var elementToCheck = element; | |
while (elementToCheck !== null && elementToCheck !== until) { | |
if (elementToCheck.nodeType === Node.ELEMENT_NODE && (nodes.indexOf(elementToCheck.nodeName) > -1 || nodes.indexOf(elementToCheck) > -1)) { | |
return elementToCheck; | |
} | |
if (elementToCheck.host && elementToCheck.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { | |
elementToCheck = elementToCheck.host; | |
} else { | |
elementToCheck = elementToCheck.parentNode; | |
} | |
} | |
return null; | |
} | |
/** | |
* Goes "down" the DOM tree (including given element) until it finds an element that matches the nodes or nodes name. | |
* | |
* @param {HTMLElement} element Element from which traversing is started | |
* @param {Array} nodes Array of elements or Array of elements name | |
* @param {HTMLElement} [until] | |
* @returns {HTMLElement|null} | |
*/ | |
function closestDown(element, nodes, until) { | |
var matched = []; | |
var elementToCheck = element; | |
while (elementToCheck) { | |
elementToCheck = closest(elementToCheck, nodes, until); | |
if (!elementToCheck || until && !until.contains(elementToCheck)) { | |
break; | |
} | |
matched.push(elementToCheck); | |
if (elementToCheck.host && elementToCheck.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { | |
elementToCheck = elementToCheck.host; | |
} else { | |
elementToCheck = elementToCheck.parentNode; | |
} | |
} | |
var length = matched.length; | |
return length ? matched[length - 1] : null; | |
} | |
/** | |
* Goes up the DOM tree and checks if element is child of another element. | |
* | |
* @param child Child element | |
* @param {Object|String} parent Parent element OR selector of the parent element. | |
* If string provided, function returns `true` for the first occurrence of element with that class. | |
* @returns {Boolean} | |
*/ | |
function isChildOf(child, parent) { | |
var node = child.parentNode; | |
var queriedParents = []; | |
if (typeof parent === 'string') { | |
if (child.defaultView) { | |
queriedParents = Array.prototype.slice.call(child.querySelectorAll(parent), 0); | |
} else { | |
queriedParents = Array.prototype.slice.call(child.ownerDocument.querySelectorAll(parent), 0); | |
} | |
} else { | |
queriedParents.push(parent); | |
} | |
while (node !== null) { | |
if (queriedParents.indexOf(node) > -1) { | |
return true; | |
} | |
node = node.parentNode; | |
} | |
return false; | |
} | |
/** | |
* Check if an element is part of `hot-table` web component. | |
* | |
* @param {Element} element | |
* @returns {Boolean} | |
*/ | |
function isChildOfWebComponentTable(element) { | |
var hotTableName = 'hot-table'; | |
var result = false; | |
var parentNode = polymerWrap(element); | |
function isHotTable(testElement) { | |
return testElement.nodeType === Node.ELEMENT_NODE && testElement.nodeName === hotTableName.toUpperCase(); | |
} | |
while (parentNode !== null) { | |
if (isHotTable(parentNode)) { | |
result = true; | |
break; | |
} else if (parentNode.host && parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { | |
result = isHotTable(parentNode.host); | |
if (result) { | |
break; | |
} | |
parentNode = parentNode.host; | |
} | |
parentNode = parentNode.parentNode; | |
} | |
return result; | |
} | |
/* global Polymer wrap unwrap */ | |
/** | |
* Wrap element into polymer/webcomponent container if exists | |
* | |
* @param element | |
* @returns {*} | |
*/ | |
function polymerWrap(element) { | |
return typeof Polymer !== 'undefined' && typeof wrap === 'function' ? wrap(element) : element; | |
} | |
/** | |
* Unwrap element from polymer/webcomponent container if exists | |
* | |
* @param element | |
* @returns {*} | |
*/ | |
function polymerUnwrap(element) { | |
return typeof Polymer !== 'undefined' && typeof unwrap === 'function' ? unwrap(element) : element; | |
} | |
/** | |
* Counts index of element within its parent | |
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable | |
* Otherwise would need to check for nodeType or use previousElementSibling | |
* | |
* @see http://jsperf.com/sibling-index/10 | |
* @param {Element} element | |
* @returns {Number} | |
*/ | |
function index(element) { | |
var i = 0; | |
var elementToCheck = element; | |
if (elementToCheck.previousSibling) { | |
/* eslint-disable no-cond-assign */ | |
while (elementToCheck = elementToCheck.previousSibling) { | |
i += 1; | |
} | |
} | |
return i; | |
} | |
/** | |
* Check if the provided overlay contains the provided element | |
* | |
* @param {String} overlay | |
* @param {HTMLElement} element | |
* @param {HTMLElement} root | |
* @returns {boolean} | |
*/ | |
function overlayContainsElement(overlayType, element, root) { | |
var overlayElement = root.parentElement.querySelector(".ht_clone_".concat(overlayType)); | |
return overlayElement ? overlayElement.contains(element) : null; | |
} | |
var _hasClass; | |
var _addClass; | |
var _removeClass; | |
function filterEmptyClassNames(classNames) { | |
if (!classNames || !classNames.length) { | |
return []; | |
} | |
return classNames.filter(function (x) { | |
return !!x; | |
}); | |
} | |
if ((0, _feature.isClassListSupported)()) { | |
var isSupportMultipleClassesArg = function isSupportMultipleClassesArg(rootDocument) { | |
var element = rootDocument.createElement('div'); | |
element.classList.add('test', 'test2'); | |
return element.classList.contains('test2'); | |
}; | |
_hasClass = function _hasClass(element, className) { | |
if (element.classList === void 0 || typeof className !== 'string' || className === '') { | |
return false; | |
} | |
return element.classList.contains(className); | |
}; | |
_addClass = function _addClass(element, classes) { | |
var rootDocument = element.ownerDocument; | |
var className = classes; | |
if (typeof className === 'string') { | |
className = className.split(' '); | |
} | |
className = filterEmptyClassNames(className); | |
if (className.length > 0) { | |
if (isSupportMultipleClassesArg(rootDocument)) { | |
var _element$classList; | |
(_element$classList = element.classList).add.apply(_element$classList, (0, _toConsumableArray2.default)(className)); | |
} else { | |
var len = 0; | |
while (className && className[len]) { | |
element.classList.add(className[len]); | |
len += 1; | |
} | |
} | |
} | |
}; | |
_removeClass = function _removeClass(element, classes) { | |
var className = classes; | |
if (typeof className === 'string') { | |
className = className.split(' '); | |
} | |
className = filterEmptyClassNames(className); | |
if (className.length > 0) { | |
if (isSupportMultipleClassesArg) { | |
var _element$classList2; | |
(_element$classList2 = element.classList).remove.apply(_element$classList2, (0, _toConsumableArray2.default)(className)); | |
} else { | |
var len = 0; | |
while (className && className[len]) { | |
element.classList.remove(className[len]); | |
len += 1; | |
} | |
} | |
} | |
}; | |
} else { | |
var createClassNameRegExp = function createClassNameRegExp(className) { | |
return new RegExp("(\\s|^)".concat(className, "(\\s|$)")); | |
}; | |
_hasClass = function _hasClass(element, className) { | |
// http://snipplr.com/view/3561/addclass-removeclass-hasclass/ | |
return element.className !== void 0 && createClassNameRegExp(className).test(element.className); | |
}; | |
_addClass = function _addClass(element, classes) { | |
var len = 0; | |
var _className = element.className; | |
var className = classes; | |
if (typeof className === 'string') { | |
className = className.split(' '); | |
} | |
if (_className === '') { | |
_className = className.join(' '); | |
} else { | |
while (className && className[len]) { | |
if (!createClassNameRegExp(className[len]).test(_className)) { | |
_className += " ".concat(className[len]); | |
} | |
len += 1; | |
} | |
} | |
element.className = _className; | |
}; | |
_removeClass = function _removeClass(element, classes) { | |
var len = 0; | |
var _className = element.className; | |
var className = classes; | |
if (typeof className === 'string') { | |
className = className.split(' '); | |
} | |
while (className && className[len]) { | |
// String.prototype.trim is defined in polyfill.js | |
_className = _className.replace(createClassNameRegExp(className[len]), ' ').trim(); | |
len += 1; | |
} | |
if (element.className !== _className) { | |
element.className = _className; | |
} | |
}; | |
} | |
/** | |
* Checks if element has class name | |
* | |
* @param {HTMLElement} element | |
* @param {String} className Class name to check | |
* @returns {Boolean} | |
*/ | |
function hasClass(element, className) { | |
return _hasClass(element, className); | |
} | |
/** | |
* Add class name to an element | |
* | |
* @param {HTMLElement} element | |
* @param {String|Array} className Class name as string or array of strings | |
*/ | |
function addClass(element, className) { | |
return _addClass(element, className); | |
} | |
/** | |
* Remove class name from an element | |
* | |
* @param {HTMLElement} element | |
* @param {String|Array} className Class name as string or array of strings | |
*/ | |
function removeClass(element, className) { | |
return _removeClass(element, className); | |
} | |
function removeTextNodes(element, parent) { | |
if (element.nodeType === 3) { | |
parent.removeChild(element); // bye text nodes! | |
} else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(element.nodeName) > -1) { | |
var childs = element.childNodes; | |
for (var i = childs.length - 1; i >= 0; i--) { | |
removeTextNodes(childs[i], element); | |
} | |
} | |
} | |
/** | |
* Remove childs function | |
* WARNING - this doesn't unload events and data attached by jQuery | |
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9 | |
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method | |
* | |
* @param element | |
* @returns {void} | |
*/ | |
// | |
function empty(element) { | |
var child; | |
/* eslint-disable no-cond-assign */ | |
while (child = element.lastChild) { | |
element.removeChild(child); | |
} | |
} | |
var HTML_CHARACTERS = /(<(.*)>|&(.*);)/; | |
/** | |
* Insert content into element trying avoid innerHTML method. | |
* @returns {void} | |
*/ | |
exports.HTML_CHARACTERS = HTML_CHARACTERS; | |
function fastInnerHTML(element, content) { | |
if (HTML_CHARACTERS.test(content)) { | |
element.innerHTML = content; | |
} else { | |
fastInnerText(element, content); | |
} | |
} | |
/** | |
* Insert text content into element | |
* @returns {Boolean} | |
*/ | |
function fastInnerText(element, content) { | |
var child = element.firstChild; | |
if (child && child.nodeType === 3 && child.nextSibling === null) { | |
// fast lane - replace existing text node | |
if (_feature.isTextContentSupported) { | |
// http://jsperf.com/replace-text-vs-reuse | |
child.textContent = content; | |
} else { | |
// http://jsperf.com/replace-text-vs-reuse | |
child.data = content; | |
} | |
} else { | |
// slow lane - empty element and insert a text node | |
empty(element); | |
element.appendChild(element.ownerDocument.createTextNode(content)); | |
} | |
} | |
/** | |
* Returns true if element is attached to the DOM and visible, false otherwise | |
* @param elem | |
* @returns {boolean} | |
*/ | |
function isVisible(elem) { | |
var documentElement = elem.ownerDocument.documentElement; | |
var next = elem; | |
while (polymerUnwrap(next) !== documentElement) { | |
// until <html> reached | |
if (next === null) { | |
// parent detached from DOM | |
return false; | |
} else if (next.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { | |
if (next.host) { | |
// this is Web Components Shadow DOM | |
// see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation | |
// according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet | |
if (next.host.impl) { | |
// Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled | |
return isVisible(next.host.impl); | |
} else if (next.host) { | |
// Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled | |
return isVisible(next.host); | |
} | |
throw new Error('Lost in Web Components world'); | |
} else { | |
return false; // this is a node detached from document in IE8 | |
} | |
} else if (next.style && next.style.display === 'none') { | |
return false; | |
} | |
next = next.parentNode; | |
} | |
return true; | |
} | |
/** | |
* Returns elements top and left offset relative to the document. Function is not compatible with jQuery offset. | |
* | |
* @param {HTMLElement} elem | |
* @returns {Object} Returns object with `top` and `left` props | |
*/ | |
function offset(elem) { | |
var rootDocument = elem.ownerDocument; | |
var rootWindow = rootDocument.defaultView; | |
var documentElement = rootDocument.documentElement; | |
var elementToCheck = elem; | |
var offsetLeft; | |
var offsetTop; | |
var lastElem; | |
var box; | |
if ((0, _feature.hasCaptionProblem)() && elementToCheck.firstChild && elementToCheck.firstChild.nodeName === 'CAPTION') { | |
// fixes problem with Firefox ignoring <caption> in TABLE offset (see also export outerHeight) | |
// http://jsperf.com/offset-vs-getboundingclientrect/8 | |
box = elementToCheck.getBoundingClientRect(); | |
return { | |
top: box.top + (rootWindow.pageYOffset || documentElement.scrollTop) - (documentElement.clientTop || 0), | |
left: box.left + (rootWindow.pageXOffset || documentElement.scrollLeft) - (documentElement.clientLeft || 0) | |
}; | |
} | |
offsetLeft = elementToCheck.offsetLeft; | |
offsetTop = elementToCheck.offsetTop; | |
lastElem = elementToCheck; | |
/* eslint-disable no-cond-assign */ | |
while (elementToCheck = elementToCheck.offsetParent) { | |
// from my observation, document.body always has scrollLeft/scrollTop == 0 | |
if (elementToCheck === rootDocument.body) { | |
break; | |
} | |
offsetLeft += elementToCheck.offsetLeft; | |
offsetTop += elementToCheck.offsetTop; | |
lastElem = elementToCheck; | |
} // slow - http://jsperf.com/offset-vs-getboundingclientrect/6 | |
if (lastElem && lastElem.style.position === 'fixed') { | |
// if(lastElem !== document.body) { //faster but does gives false positive in Firefox | |
offsetLeft += rootWindow.pageXOffset || documentElement.scrollLeft; | |
offsetTop += rootWindow.pageYOffset || documentElement.scrollTop; | |
} | |
return { | |
left: offsetLeft, | |
top: offsetTop | |
}; | |
} | |
/** | |
* Returns the document's scrollTop property. | |
* | |
* @param {Window} rootWindow | |
* @returns {Number} | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getWindowScrollTop() { | |
var rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; | |
var res = rootWindow.scrollY; | |
if (res === void 0) { | |
// IE8-11 | |
res = rootWindow.document.documentElement.scrollTop; | |
} | |
return res; | |
} | |
/** | |
* Returns the document's scrollLeft property. | |
* | |
* @param {Window} rootWindow | |
* @returns {Number} | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getWindowScrollLeft() { | |
var rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; | |
var res = rootWindow.scrollX; | |
if (res === void 0) { | |
// IE8-11 | |
res = rootWindow.document.documentElement.scrollLeft; | |
} | |
return res; | |
} | |
/** | |
* Returns the provided element's scrollTop property. | |
* | |
* @param element | |
* @param {Window} rootWindow | |
* @returns {Number} | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getScrollTop(element) { | |
var rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; | |
if (element === rootWindow) { | |
return getWindowScrollTop(rootWindow); | |
} | |
return element.scrollTop; | |
} | |
/** | |
* Returns the provided element's scrollLeft property. | |
* | |
* @param element | |
* @param {Window} rootWindow | |
* @returns {Number} | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getScrollLeft(element) { | |
var rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; | |
if (element === rootWindow) { | |
return getWindowScrollLeft(rootWindow); | |
} | |
return element.scrollLeft; | |
} | |
/** | |
* Returns a DOM element responsible for scrolling of the provided element. | |
* | |
* @param {HTMLElement} element | |
* @returns {HTMLElement} Element's scrollable parent | |
*/ | |
function getScrollableElement(element) { | |
var rootDocument = element.ownerDocument; | |
var rootWindow = rootDocument ? rootDocument.defaultView : void 0; | |
if (!rootDocument) { | |
rootDocument = element.document ? element.document : element; | |
rootWindow = rootDocument.defaultView; | |
} | |
var props = ['auto', 'scroll']; | |
var supportedGetComputedStyle = (0, _feature.isGetComputedStyleSupported)(); | |
var el = element.parentNode; | |
while (el && el.style && rootDocument.body !== el) { | |
var _el$style = el.style, | |
overflow = _el$style.overflow, | |
overflowX = _el$style.overflowX, | |
overflowY = _el$style.overflowY; | |
if ([overflow, overflowX, overflowY].includes('scroll')) { | |
return el; | |
} else if (supportedGetComputedStyle) { | |
var _rootWindow$getComput = rootWindow.getComputedStyle(el); | |
overflow = _rootWindow$getComput.overflow; | |
overflowX = _rootWindow$getComput.overflowX; | |
overflowY = _rootWindow$getComput.overflowY; | |
if (props.includes(overflow) || props.includes(overflowX) || props.includes(overflowY)) { | |
return el; | |
} | |
} // The '+ 1' after the scrollHeight/scrollWidth is to prevent problems with zoomed out Chrome. | |
if (el.clientHeight <= el.scrollHeight + 1 && (props.includes(overflowY) || props.includes(overflow))) { | |
return el; | |
} | |
if (el.clientWidth <= el.scrollWidth + 1 && (props.includes(overflowX) || props.includes(overflow))) { | |
return el; | |
} | |
el = el.parentNode; | |
} | |
return rootWindow; | |
} | |
/** | |
* Returns a DOM element responsible for trimming the provided element. | |
* | |
* @param {HTMLElement} base Base element | |
* @returns {HTMLElement} Base element's trimming parent | |
*/ | |
function getTrimmingContainer(base) { | |
var rootDocument = base.ownerDocument; | |
var rootWindow = rootDocument.defaultView; | |
var el = base.parentNode; | |
while (el && el.style && rootDocument.body !== el) { | |
if (el.style.overflow !== 'visible' && el.style.overflow !== '') { | |
return el; | |
} | |
var computedStyle = getComputedStyle(el, rootWindow); | |
var allowedProperties = ['scroll', 'hidden', 'auto']; | |
var property = computedStyle.getPropertyValue('overflow'); | |
var propertyY = computedStyle.getPropertyValue('overflow-y'); | |
var propertyX = computedStyle.getPropertyValue('overflow-x'); | |
if (allowedProperties.includes(property) || allowedProperties.includes(propertyY) || allowedProperties.includes(propertyX)) { | |
return el; | |
} | |
el = el.parentNode; | |
} | |
return rootWindow; | |
} | |
/** | |
* Returns a style property for the provided element. (Be it an inline or external style). | |
* | |
* @param {HTMLElement} element | |
* @param {String} prop Wanted property | |
* @param {Window} rootWindow | |
* @returns {String|undefined} Element's style property | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getStyle(element, prop) { | |
var rootWindow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window; | |
if (!element) { | |
return; | |
} else if (element === rootWindow) { | |
if (prop === 'width') { | |
return "".concat(rootWindow.innerWidth, "px"); | |
} else if (prop === 'height') { | |
return "".concat(rootWindow.innerHeight, "px"); | |
} | |
return; | |
} | |
var styleProp = element.style[prop]; | |
if (styleProp !== '' && styleProp !== void 0) { | |
return styleProp; | |
} | |
var computedStyle = getComputedStyle(element, rootWindow); | |
if (computedStyle[prop] !== '' && computedStyle[prop] !== void 0) { | |
return computedStyle[prop]; | |
} | |
} | |
/** | |
* Verifies if element fit to provided CSSRule. | |
* | |
* @param {Element} element Element to verify with selector text. | |
* @param {CSSRule} rule Selector text from CSSRule. | |
* @returns {Boolean} | |
*/ | |
function matchesCSSRules(element, rule) { | |
var selectorText = rule.selectorText; | |
var result = false; | |
if (rule.type === CSSRule.STYLE_RULE && selectorText) { | |
if (element.msMatchesSelector) { | |
result = element.msMatchesSelector(selectorText); | |
} else if (element.matches) { | |
result = element.matches(selectorText); | |
} | |
} | |
return result; | |
} | |
/** | |
* Returns a computed style object for the provided element. (Needed if style is declared in external stylesheet). | |
* | |
* @param element | |
* @param {Window} rootWindow | |
* @returns {IEElementStyle|CssStyle} Elements computed style object | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getComputedStyle(element) { | |
var rootWindow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window; | |
return element.currentStyle || rootWindow.getComputedStyle(element); | |
} | |
/** | |
* Returns the element's outer width. | |
* | |
* @param element | |
* @returns {number} Element's outer width | |
*/ | |
function outerWidth(element) { | |
return element.offsetWidth; | |
} | |
/** | |
* Returns the element's outer height | |
* | |
* @param elem | |
* @returns {number} Element's outer height | |
*/ | |
function outerHeight(elem) { | |
if ((0, _feature.hasCaptionProblem)() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { | |
// fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight | |
// jQuery (1.10.1) still has this unsolved | |
// may be better to just switch to getBoundingClientRect | |
// http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/ | |
// http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html | |
// http://bugs.jquery.com/ticket/2196 | |
// http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140 | |
return elem.offsetHeight + elem.firstChild.offsetHeight; | |
} | |
return elem.offsetHeight; | |
} | |
/** | |
* Returns the element's inner height. | |
* | |
* @param element | |
* @returns {number} Element's inner height | |
*/ | |
function innerHeight(element) { | |
return element.clientHeight || element.innerHeight; | |
} | |
/** | |
* Returns the element's inner width. | |
* | |
* @param element | |
* @returns {number} Element's inner width | |
*/ | |
function innerWidth(element) { | |
return element.clientWidth || element.innerWidth; | |
} | |
function addEvent(element, event, callback) { | |
var rootWindow = element.defaultView; | |
if (!rootWindow) { | |
rootWindow = element.document ? element : element.ownerDocument.defaultView; | |
} | |
if (rootWindow.addEventListener) { | |
element.addEventListener(event, callback, false); | |
} else { | |
element.attachEvent("on".concat(event), callback); | |
} | |
} | |
function removeEvent(element, event, callback) { | |
var rootWindow = element.defaultView; | |
if (!rootWindow) { | |
rootWindow = element.document ? element : element.ownerDocument.defaultView; | |
} | |
if (rootWindow.removeEventListener) { | |
element.removeEventListener(event, callback, false); | |
} else { | |
element.detachEvent("on".concat(event), callback); | |
} | |
} | |
/** | |
* Returns caret position in text input | |
* | |
* @author https://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea | |
* @returns {Number} | |
*/ | |
function getCaretPosition(el) { | |
var rootDocument = el.ownerDocument; | |
if (el.selectionStart) { | |
return el.selectionStart; | |
} else if (rootDocument.selection) { | |
// IE8 | |
el.focus(); | |
var r = rootDocument.selection.createRange(); | |
if (r === null) { | |
return 0; | |
} | |
var re = el.createTextRange(); | |
var rc = re.duplicate(); | |
re.moveToBookmark(r.getBookmark()); | |
rc.setEndPoint('EndToStart', re); | |
return rc.text.length; | |
} | |
return 0; | |
} | |
/** | |
* Returns end of the selection in text input | |
* | |
* @returns {Number} | |
*/ | |
function getSelectionEndPosition(el) { | |
var rootDocument = el.ownerDocument; | |
if (el.selectionEnd) { | |
return el.selectionEnd; | |
} else if (rootDocument.selection) { | |
// IE8 | |
var r = rootDocument.selection.createRange(); | |
if (r === null) { | |
return 0; | |
} | |
var re = el.createTextRange(); | |
return re.text.indexOf(r.text) + r.text.length; | |
} | |
return 0; | |
} | |
/** | |
* Returns text under selection. | |
* | |
* @param {Window} rootWindow | |
* @returns {String} | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getSelectionText() { | |
var rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; | |
var rootDocument = rootWindow.document; | |
var text = ''; | |
if (rootWindow.getSelection) { | |
text = rootWindow.getSelection().toString(); | |
} else if (rootDocument.selection && rootDocument.selection.type !== 'Control') { | |
text = rootDocument.selection.createRange().text; | |
} | |
return text; | |
} | |
/** | |
* Cross-platform helper to clear text selection. | |
* | |
* @param {Window} rootWindow | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function clearTextSelection() { | |
var rootWindow = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; | |
var rootDocument = rootWindow.document; // http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript | |
if (rootWindow.getSelection) { | |
if (rootWindow.getSelection().empty) { | |
// Chrome | |
rootWindow.getSelection().empty(); | |
} else if (rootWindow.getSelection().removeAllRanges) { | |
// Firefox | |
rootWindow.getSelection().removeAllRanges(); | |
} | |
} else if (rootDocument.selection) { | |
// IE? | |
rootDocument.selection.empty(); | |
} | |
} | |
/** | |
* Sets caret position in text input. | |
* | |
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ | |
* @param {Element} element | |
* @param {Number} pos | |
* @param {Number} endPos | |
*/ | |
function setCaretPosition(element, pos, endPos) { | |
if (endPos === void 0) { | |
endPos = pos; | |
} | |
if (element.setSelectionRange) { | |
element.focus(); | |
try { | |
element.setSelectionRange(pos, endPos); | |
} catch (err) { | |
var elementParent = element.parentNode; | |
var parentDisplayValue = elementParent.style.display; | |
elementParent.style.display = 'block'; | |
element.setSelectionRange(pos, endPos); | |
elementParent.style.display = parentDisplayValue; | |
} | |
} else if (element.createTextRange) { | |
// IE8 | |
var range = element.createTextRange(); | |
range.collapse(true); | |
range.moveEnd('character', endPos); | |
range.moveStart('character', pos); | |
range.select(); | |
} | |
} | |
var cachedScrollbarWidth; | |
/** | |
* Helper to calculate scrollbar width. | |
* Source: https://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes | |
* | |
* @private | |
* @param {Document} rootDocument | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function walkontableCalculateScrollbarWidth() { | |
var rootDocument = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; | |
var inner = rootDocument.createElement('div'); | |
inner.style.height = '200px'; | |
inner.style.width = '100%'; | |
var outer = rootDocument.createElement('div'); | |
outer.style.boxSizing = 'content-box'; | |
outer.style.height = '150px'; | |
outer.style.left = '0px'; | |
outer.style.overflow = 'hidden'; | |
outer.style.position = 'absolute'; | |
outer.style.top = '0px'; | |
outer.style.width = '200px'; | |
outer.style.visibility = 'hidden'; | |
outer.appendChild(inner); | |
(rootDocument.body || rootDocument.documentElement).appendChild(outer); | |
var w1 = inner.offsetWidth; | |
outer.style.overflow = 'scroll'; | |
var w2 = inner.offsetWidth; | |
if (w1 === w2) { | |
w2 = outer.clientWidth; | |
} | |
(rootDocument.body || rootDocument.documentElement).removeChild(outer); | |
return w1 - w2; | |
} | |
/** | |
* Returns the computed width of the native browser scroll bar. | |
* | |
* @param {Document} rootDocument | |
* @returns {Number} width | |
*/ | |
// eslint-disable-next-line no-restricted-globals | |
function getScrollbarWidth() { | |
var rootDocument = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document; | |
if (cachedScrollbarWidth === void 0) { | |
cachedScrollbarWidth = walkontableCalculateScrollbarWidth(rootDocument); | |
} | |
return cachedScrollbarWidth; | |
} | |
/** | |
* Checks if the provided element has a vertical scrollbar. | |
* | |
* @param {HTMLElement} element | |
* @returns {Boolean} | |
*/ | |
function hasVerticalScrollbar(element) { | |
return element.offsetWidth !== element.clientWidth; | |
} | |
/** | |
* Checks if the provided element has a vertical scrollbar. | |
* | |
* @param {HTMLElement} element | |
* @returns {Boolean} | |
*/ | |
function hasHorizontalScrollbar(element) { | |
return element.offsetHeight !== element.clientHeight; | |
} | |
/** | |
* Sets overlay position depending on it's type and used browser | |
*/ | |
function setOverlayPosition(overlayElem, left, top) { | |
if ((0, _browser.isIE8)() || (0, _browser.isIE9)()) { | |
overlayElem.style.top = top; | |
overlayElem.style.left = left; | |
} else if ((0, _browser.isSafari)()) { | |
overlayElem.style['-webkit-transform'] = "translate3d(".concat(left, ",").concat(top, ",0)"); | |
overlayElem.style['-webkit-transform'] = "translate3d(".concat(left, ",").concat(top, ",0)"); | |
} else { | |
overlayElem.style.transform = "translate3d(".concat(left, ",").concat(top, ",0)"); | |
} | |
} | |
function getCssTransform(element) { | |
var transform; | |
if (element.style.transform && (transform = element.style.transform) !== '') { | |
return ['transform', transform]; | |
} else if (element.style['-webkit-transform'] && (transform = element.style['-webkit-transform']) !== '') { | |
return ['-webkit-transform', transform]; | |
} | |
return -1; | |
} | |
function resetCssTransform(element) { | |
if (element.style.transform && element.style.transform !== '') { | |
element.style.transform = ''; | |
} else if (element.style['-webkit-transform'] && element.style['-webkit-transform'] !== '') { | |
element.style['-webkit-transform'] = ''; | |
} | |
} | |
/** | |
* Determines if the given DOM element is an input field. | |
* Notice: By 'input' we mean input, textarea and select nodes | |
* | |
* @param {HTMLElement} element - DOM element | |
* @returns {Boolean} | |
*/ | |
function isInput(element) { | |
var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; | |
return element && (inputs.indexOf(element.nodeName) > -1 || element.contentEditable === 'true'); | |
} | |
/** | |
* Determines if the given DOM element is an input field placed OUTSIDE of HOT. | |
* Notice: By 'input' we mean input, textarea and select nodes | |
* | |
* @param {HTMLElement} element - DOM element | |
* @returns {Boolean} | |
*/ | |
function isOutsideInput(element) { | |
return isInput(element) && element.className.indexOf('handsontableInput') === -1 && element.className.indexOf('HandsontableCopyPaste') === -1; | |
} | |
/** | |
* Check if the given DOM element can be focused (by using "select" method). | |
* | |
* @param {HTMLElement} element - DOM element | |
*/ | |
function selectElementIfAllowed(element) { | |
var activeElement = element.ownerDocument.activeElement; | |
if (!isOutsideInput(activeElement)) { | |
element.select(); | |
} | |
} | |
/***/ }), | |
/* 9 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var redefine = __webpack_require__(73); | |
var toString = __webpack_require__(416); | |
var ObjectPrototype = Object.prototype; | |
// `Object.prototype.toString` method | |
// https://tc39.github.io/ecma262/#sec-object.prototype.tostring | |
if (toString !== ObjectPrototype.toString) { | |
redefine(ObjectPrototype, 'toString', toString, { unsafe: true }); | |
} | |
/***/ }), | |
/* 10 */ | |
/***/ (function(module, exports) { | |
function _getRequireWildcardCache() { | |
if (typeof WeakMap !== "function") return null; | |
var cache = new WeakMap(); | |
_getRequireWildcardCache = function _getRequireWildcardCache() { | |
return cache; | |
}; | |
return cache; | |
} | |
function _interopRequireWildcard(obj) { | |
if (obj && obj.__esModule) { | |
return obj; | |
} | |
var cache = _getRequireWildcardCache(); | |
if (cache && cache.has(obj)) { | |
return cache.get(obj); | |
} | |
var newObj = {}; | |
if (obj != null) { | |
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; | |
for (var key in obj) { | |
if (Object.prototype.hasOwnProperty.call(obj, key)) { | |
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; | |
if (desc && (desc.get || desc.set)) { | |
Object.defineProperty(newObj, key, desc); | |
} else { | |
newObj[key] = obj[key]; | |
} | |
} | |
} | |
} | |
newObj["default"] = obj; | |
if (cache) { | |
cache.set(obj, newObj); | |
} | |
return newObj; | |
} | |
module.exports = _interopRequireWildcard; | |
/***/ }), | |
/* 11 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var charAt = __webpack_require__(154).charAt; | |
var InternalStateModule = __webpack_require__(88); | |
var defineIterator = __webpack_require__(152); | |
var STRING_ITERATOR = 'String Iterator'; | |
var setInternalState = InternalStateModule.set; | |
var getInternalState = InternalStateModule.getterFor(STRING_ITERATOR); | |
// `String.prototype[@@iterator]` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator | |
defineIterator(String, 'String', function (iterated) { | |
setInternalState(this, { | |
type: STRING_ITERATOR, | |
string: String(iterated), | |
index: 0 | |
}); | |
// `%StringIteratorPrototype%.next` method | |
// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next | |
}, function next() { | |
var state = getInternalState(this); | |
var string = state.string; | |
var index = state.index; | |
var point; | |
if (index >= string.length) return { value: undefined, done: true }; | |
point = charAt(string, index); | |
state.index += point.length; | |
return { value: point, done: false }; | |
}); | |
/***/ }), | |
/* 12 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var toIndexedObject = __webpack_require__(67); | |
var addToUnscopables = __webpack_require__(102); | |
var Iterators = __webpack_require__(104); | |
var InternalStateModule = __webpack_require__(88); | |
var defineIterator = __webpack_require__(152); | |
var ARRAY_ITERATOR = 'Array Iterator'; | |
var setInternalState = InternalStateModule.set; | |
var getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR); | |
// `Array.prototype.entries` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.entries | |
// `Array.prototype.keys` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.keys | |
// `Array.prototype.values` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.values | |
// `Array.prototype[@@iterator]` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator | |
// `CreateArrayIterator` internal method | |
// https://tc39.github.io/ecma262/#sec-createarrayiterator | |
module.exports = defineIterator(Array, 'Array', function (iterated, kind) { | |
setInternalState(this, { | |
type: ARRAY_ITERATOR, | |
target: toIndexedObject(iterated), // target | |
index: 0, // next index | |
kind: kind // kind | |
}); | |
// `%ArrayIteratorPrototype%.next` method | |
// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next | |
}, function () { | |
var state = getInternalState(this); | |
var target = state.target; | |
var kind = state.kind; | |
var index = state.index++; | |
if (!target || index >= target.length) { | |
state.target = undefined; | |
return { value: undefined, done: true }; | |
} | |
if (kind == 'keys') return { value: index, done: false }; | |
if (kind == 'values') return { value: target[index], done: false }; | |
return { value: [index, target[index]], done: false }; | |
}, 'values'); | |
// argumentsList[@@iterator] is %ArrayProto_values% | |
// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject | |
// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject | |
Iterators.Arguments = Iterators.Array; | |
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables | |
addToUnscopables('keys'); | |
addToUnscopables('values'); | |
addToUnscopables('entries'); | |
/***/ }), | |
/* 13 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var global = __webpack_require__(38); | |
var DOMIterables = __webpack_require__(209); | |
var ArrayIteratorMethods = __webpack_require__(12); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var wellKnownSymbol = __webpack_require__(37); | |
var ITERATOR = wellKnownSymbol('iterator'); | |
var TO_STRING_TAG = wellKnownSymbol('toStringTag'); | |
var ArrayValues = ArrayIteratorMethods.values; | |
for (var COLLECTION_NAME in DOMIterables) { | |
var Collection = global[COLLECTION_NAME]; | |
var CollectionPrototype = Collection && Collection.prototype; | |
if (CollectionPrototype) { | |
// some Chrome versions have non-configurable methods on DOMTokenList | |
if (CollectionPrototype[ITERATOR] !== ArrayValues) try { | |
createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues); | |
} catch (error) { | |
CollectionPrototype[ITERATOR] = ArrayValues; | |
} | |
if (!CollectionPrototype[TO_STRING_TAG]) { | |
createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME); | |
} | |
if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) { | |
// some Chrome versions have non-configurable methods on DOMTokenList | |
if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try { | |
createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]); | |
} catch (error) { | |
CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME]; | |
} | |
} | |
} | |
} | |
/***/ }), | |
/* 14 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_VALUE = exports.FILTERS_BUTTONS_PLACEHOLDER_SEARCH = exports.FILTERS_BUTTONS_CANCEL = exports.FILTERS_BUTTONS_OK = exports.FILTERS_BUTTONS_CLEAR = exports.FILTERS_BUTTONS_SELECT_ALL = exports.FILTERS_VALUES_BLANK_CELLS = exports.FILTERS_LABELS_DISJUNCTION = exports.FILTERS_LABELS_CONJUNCTION = exports.FILTERS_DIVS_FILTER_BY_VALUE = exports.FILTERS_DIVS_FILTER_BY_CONDITION = exports.FILTERS_CONDITIONS_YESTERDAY = exports.FILTERS_CONDITIONS_TOMORROW = exports.FILTERS_CONDITIONS_TODAY = exports.FILTERS_CONDITIONS_BEFORE = exports.FILTERS_CONDITIONS_AFTER = exports.FILTERS_CONDITIONS_NOT_BETWEEN = exports.FILTERS_CONDITIONS_BETWEEN = exports.FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_LESS_THAN = exports.FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = exports.FILTERS_CONDITIONS_GREATER_THAN = exports.FILTERS_CONDITIONS_BY_VALUE = exports.FILTERS_CONDITIONS_NOT_CONTAIN = exports.FILTERS_CONDITIONS_CONTAINS = exports.FILTERS_CONDITIONS_ENDS_WITH = exports.FILTERS_CONDITIONS_BEGINS_WITH = exports.FILTERS_CONDITIONS_NOT_EQUAL = exports.FILTERS_CONDITIONS_EQUAL = exports.FILTERS_CONDITIONS_NOT_EMPTY = exports.FILTERS_CONDITIONS_EMPTY = exports.FILTERS_CONDITIONS_NONE = exports.FILTERS_CONDITIONS_NAMESPACE = exports.FILTERS_NAMESPACE = exports.CONTEXTMENU_ITEMS_SHOW_ROW = exports.CONTEXTMENU_ITEMS_HIDE_ROW = exports.CONTEXTMENU_ITEMS_SHOW_COLUMN = exports.CONTEXTMENU_ITEMS_HIDE_COLUMN = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = exports.CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = exports.CONTEXTMENU_ITEMS_REMOVE_BORDERS = exports.CONTEXTMENU_ITEMS_BORDERS_LEFT = exports.CONTEXTMENU_ITEMS_BORDERS_BOTTOM = exports.CONTEXTMENU_ITEMS_BORDERS_RIGHT = exports.CONTEXTMENU_ITEMS_BORDERS_TOP = exports.CONTEXTMENU_ITEMS_BORDERS = exports.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = exports.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = exports.CONTEXTMENU_ITEMS_ALIGNMENT_TOP = exports.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = exports.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = exports.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = exports.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = exports.CONTEXTMENU_ITEMS_ALIGNMENT = exports.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = exports.CONTEXTMENU_ITEMS_REMOVE_COMMENT = exports.CONTEXTMENU_ITEMS_EDIT_COMMENT = exports.CONTEXTMENU_ITEMS_ADD_COMMENT = exports.CONTEXTMENU_ITEMS_UNMERGE_CELLS = exports.CONTEXTMENU_ITEMS_MERGE_CELLS = exports.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_FREEZE_COLUMN = exports.CONTEXTMENU_ITEMS_CUT = exports.CONTEXTMENU_ITEMS_COPY = exports.CONTEXTMENU_ITEMS_CLEAR_COLUMN = exports.CONTEXTMENU_ITEMS_READ_ONLY = exports.CONTEXTMENU_ITEMS_REDO = exports.CONTEXTMENU_ITEMS_UNDO = exports.CONTEXTMENU_ITEMS_REMOVE_COLUMN = exports.CONTEXTMENU_ITEMS_REMOVE_ROW = exports.CONTEXTMENU_ITEMS_INSERT_RIGHT = exports.CONTEXTMENU_ITEMS_INSERT_LEFT = exports.CONTEXTMENU_ITEMS_ROW_BELOW = exports.CONTEXTMENU_ITEMS_ROW_ABOVE = exports.CONTEXTMENU_ITEMS_NO_ITEMS = exports.CONTEXT_MENU_ITEMS_NAMESPACE = void 0; | |
/** | |
* Constants for parts of translation. | |
*/ | |
var CONTEXT_MENU_ITEMS_NAMESPACE = 'ContextMenu:items'; | |
exports.CONTEXT_MENU_ITEMS_NAMESPACE = CONTEXT_MENU_ITEMS_NAMESPACE; | |
var CONTEXTMENU_ITEMS_NO_ITEMS = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".noItems"); | |
exports.CONTEXTMENU_ITEMS_NO_ITEMS = CONTEXTMENU_ITEMS_NO_ITEMS; | |
var CONTEXTMENU_ITEMS_ROW_ABOVE = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".insertRowAbove"); | |
exports.CONTEXTMENU_ITEMS_ROW_ABOVE = CONTEXTMENU_ITEMS_ROW_ABOVE; | |
var CONTEXTMENU_ITEMS_ROW_BELOW = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".insertRowBelow"); | |
exports.CONTEXTMENU_ITEMS_ROW_BELOW = CONTEXTMENU_ITEMS_ROW_BELOW; | |
var CONTEXTMENU_ITEMS_INSERT_LEFT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".insertColumnOnTheLeft"); | |
exports.CONTEXTMENU_ITEMS_INSERT_LEFT = CONTEXTMENU_ITEMS_INSERT_LEFT; | |
var CONTEXTMENU_ITEMS_INSERT_RIGHT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".insertColumnOnTheRight"); | |
exports.CONTEXTMENU_ITEMS_INSERT_RIGHT = CONTEXTMENU_ITEMS_INSERT_RIGHT; | |
var CONTEXTMENU_ITEMS_REMOVE_ROW = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".removeRow"); | |
exports.CONTEXTMENU_ITEMS_REMOVE_ROW = CONTEXTMENU_ITEMS_REMOVE_ROW; | |
var CONTEXTMENU_ITEMS_REMOVE_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".removeColumn"); | |
exports.CONTEXTMENU_ITEMS_REMOVE_COLUMN = CONTEXTMENU_ITEMS_REMOVE_COLUMN; | |
var CONTEXTMENU_ITEMS_UNDO = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".undo"); | |
exports.CONTEXTMENU_ITEMS_UNDO = CONTEXTMENU_ITEMS_UNDO; | |
var CONTEXTMENU_ITEMS_REDO = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".redo"); | |
exports.CONTEXTMENU_ITEMS_REDO = CONTEXTMENU_ITEMS_REDO; | |
var CONTEXTMENU_ITEMS_READ_ONLY = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".readOnly"); | |
exports.CONTEXTMENU_ITEMS_READ_ONLY = CONTEXTMENU_ITEMS_READ_ONLY; | |
var CONTEXTMENU_ITEMS_CLEAR_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".clearColumn"); | |
exports.CONTEXTMENU_ITEMS_CLEAR_COLUMN = CONTEXTMENU_ITEMS_CLEAR_COLUMN; | |
var CONTEXTMENU_ITEMS_COPY = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".copy"); | |
exports.CONTEXTMENU_ITEMS_COPY = CONTEXTMENU_ITEMS_COPY; | |
var CONTEXTMENU_ITEMS_CUT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".cut"); | |
exports.CONTEXTMENU_ITEMS_CUT = CONTEXTMENU_ITEMS_CUT; | |
var CONTEXTMENU_ITEMS_FREEZE_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".freezeColumn"); | |
exports.CONTEXTMENU_ITEMS_FREEZE_COLUMN = CONTEXTMENU_ITEMS_FREEZE_COLUMN; | |
var CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".unfreezeColumn"); | |
exports.CONTEXTMENU_ITEMS_UNFREEZE_COLUMN = CONTEXTMENU_ITEMS_UNFREEZE_COLUMN; | |
var CONTEXTMENU_ITEMS_MERGE_CELLS = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".mergeCells"); | |
exports.CONTEXTMENU_ITEMS_MERGE_CELLS = CONTEXTMENU_ITEMS_MERGE_CELLS; | |
var CONTEXTMENU_ITEMS_UNMERGE_CELLS = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".unmergeCells"); | |
exports.CONTEXTMENU_ITEMS_UNMERGE_CELLS = CONTEXTMENU_ITEMS_UNMERGE_CELLS; | |
var CONTEXTMENU_ITEMS_ADD_COMMENT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".addComment"); | |
exports.CONTEXTMENU_ITEMS_ADD_COMMENT = CONTEXTMENU_ITEMS_ADD_COMMENT; | |
var CONTEXTMENU_ITEMS_EDIT_COMMENT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".editComment"); | |
exports.CONTEXTMENU_ITEMS_EDIT_COMMENT = CONTEXTMENU_ITEMS_EDIT_COMMENT; | |
var CONTEXTMENU_ITEMS_REMOVE_COMMENT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".removeComment"); | |
exports.CONTEXTMENU_ITEMS_REMOVE_COMMENT = CONTEXTMENU_ITEMS_REMOVE_COMMENT; | |
var CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".readOnlyComment"); | |
exports.CONTEXTMENU_ITEMS_READ_ONLY_COMMENT = CONTEXTMENU_ITEMS_READ_ONLY_COMMENT; | |
var CONTEXTMENU_ITEMS_ALIGNMENT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT = CONTEXTMENU_ITEMS_ALIGNMENT; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.left"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_LEFT = CONTEXTMENU_ITEMS_ALIGNMENT_LEFT; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.center"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_CENTER = CONTEXTMENU_ITEMS_ALIGNMENT_CENTER; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.right"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT = CONTEXTMENU_ITEMS_ALIGNMENT_RIGHT; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.justify"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY = CONTEXTMENU_ITEMS_ALIGNMENT_JUSTIFY; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_TOP = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.top"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_TOP = CONTEXTMENU_ITEMS_ALIGNMENT_TOP; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.middle"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE = CONTEXTMENU_ITEMS_ALIGNMENT_MIDDLE; | |
var CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".align.bottom"); | |
exports.CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM = CONTEXTMENU_ITEMS_ALIGNMENT_BOTTOM; | |
var CONTEXTMENU_ITEMS_BORDERS = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders"); | |
exports.CONTEXTMENU_ITEMS_BORDERS = CONTEXTMENU_ITEMS_BORDERS; | |
var CONTEXTMENU_ITEMS_BORDERS_TOP = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders.top"); | |
exports.CONTEXTMENU_ITEMS_BORDERS_TOP = CONTEXTMENU_ITEMS_BORDERS_TOP; | |
var CONTEXTMENU_ITEMS_BORDERS_RIGHT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders.right"); | |
exports.CONTEXTMENU_ITEMS_BORDERS_RIGHT = CONTEXTMENU_ITEMS_BORDERS_RIGHT; | |
var CONTEXTMENU_ITEMS_BORDERS_BOTTOM = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders.bottom"); | |
exports.CONTEXTMENU_ITEMS_BORDERS_BOTTOM = CONTEXTMENU_ITEMS_BORDERS_BOTTOM; | |
var CONTEXTMENU_ITEMS_BORDERS_LEFT = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders.left"); | |
exports.CONTEXTMENU_ITEMS_BORDERS_LEFT = CONTEXTMENU_ITEMS_BORDERS_LEFT; | |
var CONTEXTMENU_ITEMS_REMOVE_BORDERS = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".borders.remove"); | |
exports.CONTEXTMENU_ITEMS_REMOVE_BORDERS = CONTEXTMENU_ITEMS_REMOVE_BORDERS; | |
var CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".nestedHeaders.insertChildRow"); | |
exports.CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD = CONTEXTMENU_ITEMS_NESTED_ROWS_INSERT_CHILD; | |
var CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".nestedHeaders.detachFromParent"); | |
exports.CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD = CONTEXTMENU_ITEMS_NESTED_ROWS_DETACH_CHILD; | |
var CONTEXTMENU_ITEMS_HIDE_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".hideColumn"); | |
exports.CONTEXTMENU_ITEMS_HIDE_COLUMN = CONTEXTMENU_ITEMS_HIDE_COLUMN; | |
var CONTEXTMENU_ITEMS_SHOW_COLUMN = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".showColumn"); | |
exports.CONTEXTMENU_ITEMS_SHOW_COLUMN = CONTEXTMENU_ITEMS_SHOW_COLUMN; | |
var CONTEXTMENU_ITEMS_HIDE_ROW = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".hideRow"); | |
exports.CONTEXTMENU_ITEMS_HIDE_ROW = CONTEXTMENU_ITEMS_HIDE_ROW; | |
var CONTEXTMENU_ITEMS_SHOW_ROW = "".concat(CONTEXT_MENU_ITEMS_NAMESPACE, ".showRow"); | |
exports.CONTEXTMENU_ITEMS_SHOW_ROW = CONTEXTMENU_ITEMS_SHOW_ROW; | |
var FILTERS_NAMESPACE = 'Filters:'; | |
exports.FILTERS_NAMESPACE = FILTERS_NAMESPACE; | |
var FILTERS_CONDITIONS_NAMESPACE = "".concat(FILTERS_NAMESPACE, "conditions"); | |
exports.FILTERS_CONDITIONS_NAMESPACE = FILTERS_CONDITIONS_NAMESPACE; | |
var FILTERS_CONDITIONS_NONE = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".none"); | |
exports.FILTERS_CONDITIONS_NONE = FILTERS_CONDITIONS_NONE; | |
var FILTERS_CONDITIONS_EMPTY = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isEmpty"); | |
exports.FILTERS_CONDITIONS_EMPTY = FILTERS_CONDITIONS_EMPTY; | |
var FILTERS_CONDITIONS_NOT_EMPTY = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isNotEmpty"); | |
exports.FILTERS_CONDITIONS_NOT_EMPTY = FILTERS_CONDITIONS_NOT_EMPTY; | |
var FILTERS_CONDITIONS_EQUAL = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isEqualTo"); | |
exports.FILTERS_CONDITIONS_EQUAL = FILTERS_CONDITIONS_EQUAL; | |
var FILTERS_CONDITIONS_NOT_EQUAL = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isNotEqualTo"); | |
exports.FILTERS_CONDITIONS_NOT_EQUAL = FILTERS_CONDITIONS_NOT_EQUAL; | |
var FILTERS_CONDITIONS_BEGINS_WITH = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".beginsWith"); | |
exports.FILTERS_CONDITIONS_BEGINS_WITH = FILTERS_CONDITIONS_BEGINS_WITH; | |
var FILTERS_CONDITIONS_ENDS_WITH = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".endsWith"); | |
exports.FILTERS_CONDITIONS_ENDS_WITH = FILTERS_CONDITIONS_ENDS_WITH; | |
var FILTERS_CONDITIONS_CONTAINS = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".contains"); | |
exports.FILTERS_CONDITIONS_CONTAINS = FILTERS_CONDITIONS_CONTAINS; | |
var FILTERS_CONDITIONS_NOT_CONTAIN = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".doesNotContain"); | |
exports.FILTERS_CONDITIONS_NOT_CONTAIN = FILTERS_CONDITIONS_NOT_CONTAIN; | |
var FILTERS_CONDITIONS_BY_VALUE = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".byValue"); | |
exports.FILTERS_CONDITIONS_BY_VALUE = FILTERS_CONDITIONS_BY_VALUE; | |
var FILTERS_CONDITIONS_GREATER_THAN = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".greaterThan"); | |
exports.FILTERS_CONDITIONS_GREATER_THAN = FILTERS_CONDITIONS_GREATER_THAN; | |
var FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".greaterThanOrEqualTo"); | |
exports.FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL = FILTERS_CONDITIONS_GREATER_THAN_OR_EQUAL; | |
var FILTERS_CONDITIONS_LESS_THAN = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".lessThan"); | |
exports.FILTERS_CONDITIONS_LESS_THAN = FILTERS_CONDITIONS_LESS_THAN; | |
var FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".lessThanOrEqualTo"); | |
exports.FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL = FILTERS_CONDITIONS_LESS_THAN_OR_EQUAL; | |
var FILTERS_CONDITIONS_BETWEEN = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isBetween"); | |
exports.FILTERS_CONDITIONS_BETWEEN = FILTERS_CONDITIONS_BETWEEN; | |
var FILTERS_CONDITIONS_NOT_BETWEEN = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".isNotBetween"); | |
exports.FILTERS_CONDITIONS_NOT_BETWEEN = FILTERS_CONDITIONS_NOT_BETWEEN; | |
var FILTERS_CONDITIONS_AFTER = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".after"); | |
exports.FILTERS_CONDITIONS_AFTER = FILTERS_CONDITIONS_AFTER; | |
var FILTERS_CONDITIONS_BEFORE = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".before"); | |
exports.FILTERS_CONDITIONS_BEFORE = FILTERS_CONDITIONS_BEFORE; | |
var FILTERS_CONDITIONS_TODAY = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".today"); | |
exports.FILTERS_CONDITIONS_TODAY = FILTERS_CONDITIONS_TODAY; | |
var FILTERS_CONDITIONS_TOMORROW = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".tomorrow"); | |
exports.FILTERS_CONDITIONS_TOMORROW = FILTERS_CONDITIONS_TOMORROW; | |
var FILTERS_CONDITIONS_YESTERDAY = "".concat(FILTERS_CONDITIONS_NAMESPACE, ".yesterday"); | |
exports.FILTERS_CONDITIONS_YESTERDAY = FILTERS_CONDITIONS_YESTERDAY; | |
var FILTERS_DIVS_FILTER_BY_CONDITION = "".concat(FILTERS_NAMESPACE, "labels.filterByCondition"); | |
exports.FILTERS_DIVS_FILTER_BY_CONDITION = FILTERS_DIVS_FILTER_BY_CONDITION; | |
var FILTERS_DIVS_FILTER_BY_VALUE = "".concat(FILTERS_NAMESPACE, "labels.filterByValue"); | |
exports.FILTERS_DIVS_FILTER_BY_VALUE = FILTERS_DIVS_FILTER_BY_VALUE; | |
var FILTERS_LABELS_CONJUNCTION = "".concat(FILTERS_NAMESPACE, "labels.conjunction"); | |
exports.FILTERS_LABELS_CONJUNCTION = FILTERS_LABELS_CONJUNCTION; | |
var FILTERS_LABELS_DISJUNCTION = "".concat(FILTERS_NAMESPACE, "labels.disjunction"); | |
exports.FILTERS_LABELS_DISJUNCTION = FILTERS_LABELS_DISJUNCTION; | |
var FILTERS_VALUES_BLANK_CELLS = "".concat(FILTERS_NAMESPACE, "values.blankCells"); | |
exports.FILTERS_VALUES_BLANK_CELLS = FILTERS_VALUES_BLANK_CELLS; | |
var FILTERS_BUTTONS_SELECT_ALL = "".concat(FILTERS_NAMESPACE, "buttons.selectAll"); | |
exports.FILTERS_BUTTONS_SELECT_ALL = FILTERS_BUTTONS_SELECT_ALL; | |
var FILTERS_BUTTONS_CLEAR = "".concat(FILTERS_NAMESPACE, "buttons.clear"); | |
exports.FILTERS_BUTTONS_CLEAR = FILTERS_BUTTONS_CLEAR; | |
var FILTERS_BUTTONS_OK = "".concat(FILTERS_NAMESPACE, "buttons.ok"); | |
exports.FILTERS_BUTTONS_OK = FILTERS_BUTTONS_OK; | |
var FILTERS_BUTTONS_CANCEL = "".concat(FILTERS_NAMESPACE, "buttons.cancel"); | |
exports.FILTERS_BUTTONS_CANCEL = FILTERS_BUTTONS_CANCEL; | |
var FILTERS_BUTTONS_PLACEHOLDER_SEARCH = "".concat(FILTERS_NAMESPACE, "buttons.placeholder.search"); | |
exports.FILTERS_BUTTONS_PLACEHOLDER_SEARCH = FILTERS_BUTTONS_PLACEHOLDER_SEARCH; | |
var FILTERS_BUTTONS_PLACEHOLDER_VALUE = "".concat(FILTERS_NAMESPACE, "buttons.placeholder.value"); | |
exports.FILTERS_BUTTONS_PLACEHOLDER_VALUE = FILTERS_BUTTONS_PLACEHOLDER_VALUE; | |
var FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = "".concat(FILTERS_NAMESPACE, "buttons.placeholder.secondValue"); | |
exports.FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE = FILTERS_BUTTONS_PLACEHOLDER_SECOND_VALUE; | |
/***/ }), | |
/* 15 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var $indexOf = __webpack_require__(149).indexOf; | |
var sloppyArrayMethod = __webpack_require__(107); | |
var nativeIndexOf = [].indexOf; | |
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0; | |
var SLOPPY_METHOD = sloppyArrayMethod('indexOf'); | |
// `Array.prototype.indexOf` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof | |
$({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || SLOPPY_METHOD }, { | |
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { | |
return NEGATIVE_ZERO | |
// convert -0 to +0 | |
? nativeIndexOf.apply(this, arguments) || 0 | |
: $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); | |
} | |
}); | |
/***/ }), | |
/* 16 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var superPropBase = __webpack_require__(459); | |
function _get(target, property, receiver) { | |
if (typeof Reflect !== "undefined" && Reflect.get) { | |
module.exports = _get = Reflect.get; | |
} else { | |
module.exports = _get = function _get(target, property, receiver) { | |
var base = superPropBase(target, property); | |
if (!base) return; | |
var desc = Object.getOwnPropertyDescriptor(base, property); | |
if (desc.get) { | |
return desc.get.call(receiver); | |
} | |
return desc.value; | |
}; | |
} | |
return _get(target, property, receiver || target); | |
} | |
module.exports = _get; | |
/***/ }), | |
/* 17 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var fails = __webpack_require__(28); | |
var isArray = __webpack_require__(106); | |
var isObject = __webpack_require__(44); | |
var toObject = __webpack_require__(62); | |
var toLength = __webpack_require__(52); | |
var createProperty = __webpack_require__(108); | |
var arraySpeciesCreate = __webpack_require__(160); | |
var arrayMethodHasSpeciesSupport = __webpack_require__(109); | |
var wellKnownSymbol = __webpack_require__(37); | |
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); | |
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; | |
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; | |
var IS_CONCAT_SPREADABLE_SUPPORT = !fails(function () { | |
var array = []; | |
array[IS_CONCAT_SPREADABLE] = false; | |
return array.concat()[0] !== array; | |
}); | |
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); | |
var isConcatSpreadable = function (O) { | |
if (!isObject(O)) return false; | |
var spreadable = O[IS_CONCAT_SPREADABLE]; | |
return spreadable !== undefined ? !!spreadable : isArray(O); | |
}; | |
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; | |
// `Array.prototype.concat` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.concat | |
// with adding support of @@isConcatSpreadable and @@species | |
$({ target: 'Array', proto: true, forced: FORCED }, { | |
concat: function concat(arg) { // eslint-disable-line no-unused-vars | |
var O = toObject(this); | |
var A = arraySpeciesCreate(O, 0); | |
var n = 0; | |
var i, k, length, len, E; | |
for (i = -1, length = arguments.length; i < length; i++) { | |
E = i === -1 ? O : arguments[i]; | |
if (isConcatSpreadable(E)) { | |
len = toLength(E.length); | |
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); | |
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); | |
} else { | |
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); | |
createProperty(A, n++, E); | |
} | |
} | |
A.length = n; | |
return A; | |
} | |
}); | |
/***/ }), | |
/* 18 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var arrayWithHoles = __webpack_require__(222); | |
var iterableToArrayLimit = __webpack_require__(423); | |
var nonIterableRest = __webpack_require__(223); | |
function _slicedToArray(arr, i) { | |
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); | |
} | |
module.exports = _slicedToArray; | |
/***/ }), | |
/* 19 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(9); | |
__webpack_require__(39); | |
__webpack_require__(42); | |
exports.__esModule = true; | |
exports.isNumeric = isNumeric; | |
exports.rangeEach = rangeEach; | |
exports.rangeEachReverse = rangeEachReverse; | |
exports.valueAccordingPercent = valueAccordingPercent; | |
var _typeof2 = _interopRequireDefault(__webpack_require__(46)); | |
/** | |
* Checks if value of n is a numeric one | |
* http://jsperf.com/isnan-vs-isnumeric/4 | |
* @param n | |
* @returns {boolean} | |
*/ | |
function isNumeric(n) { | |
/* eslint-disable */ | |
var t = (0, _typeof2.default)(n); | |
return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == 'number' && !(n instanceof Date) : false; | |
} | |
/** | |
* A specialized version of `.forEach` defined by ranges. | |
* | |
* @param {Number} rangeFrom The number from start iterate. | |
* @param {Number|Function} rangeTo The number where finish iterate or function as a iteratee. | |
* @param {Function} [iteratee] The function invoked per iteration. | |
*/ | |
function rangeEach(rangeFrom, rangeTo, iteratee) { | |
var index = -1; | |
if (typeof rangeTo === 'function') { | |
iteratee = rangeTo; | |
rangeTo = rangeFrom; | |
} else { | |
index = rangeFrom - 1; | |
} | |
while (++index <= rangeTo) { | |
if (iteratee(index) === false) { | |
break; | |
} | |
} | |
} | |
/** | |
* A specialized version of `.forEach` defined by ranges iterable in reverse order. | |
* | |
* @param {Number} rangeFrom The number from start iterate. | |
* @param {Number|Function} rangeTo The number where finish iterate or function as a iteratee. | |
* @param {Function} [iteratee] The function invoked per iteration. | |
*/ | |
function rangeEachReverse(rangeFrom, rangeTo, iteratee) { | |
var index = rangeFrom + 1; | |
if (typeof rangeTo === 'function') { | |
iteratee = rangeTo; | |
rangeTo = 0; | |
} | |
while (--index >= rangeTo) { | |
if (iteratee(index) === false) { | |
break; | |
} | |
} | |
} | |
/** | |
* Calculate value from percent. | |
* | |
* @param {Number} value Base value from percent will be calculated. | |
* @param {String|Number} percent Can be Number or String (eq. `'33%'`). | |
* @returns {Number} | |
*/ | |
function valueAccordingPercent(value, percent) { | |
percent = parseInt(percent.toString().replace('%', ''), 10); | |
percent = parseInt(value * percent / 100, 10); | |
return percent; | |
} | |
/***/ }), | |
/* 20 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(12); | |
__webpack_require__(65); | |
__webpack_require__(9); | |
__webpack_require__(11); | |
__webpack_require__(23); | |
__webpack_require__(13); | |
exports.__esModule = true; | |
exports.registerPlugin = registerPlugin; | |
exports.getPlugin = getPlugin; | |
exports.getRegistredPluginNames = getRegistredPluginNames; | |
exports.getPluginName = getPluginName; | |
var _pluginHooks = _interopRequireDefault(__webpack_require__(45)); | |
var _object = __webpack_require__(4); | |
var _string = __webpack_require__(77); | |
/** | |
* Utility to register plugins and common namespace for keeping reference to all plugins classes | |
*/ | |
var registeredPlugins = new WeakMap(); | |
/** | |
* Registers plugin under given name | |
* | |
* @param {String} pluginName | |
* @param {Function} PluginClass | |
*/ | |
function registerPlugin(pluginName, PluginClass) { | |
var correctedPluginName = (0, _string.toUpperCaseFirst)(pluginName); | |
_pluginHooks.default.getSingleton().add('construct', function () { | |
if (!registeredPlugins.has(this)) { | |
registeredPlugins.set(this, {}); | |
} | |
var holder = registeredPlugins.get(this); | |
if (!holder[correctedPluginName]) { | |
holder[correctedPluginName] = new PluginClass(this); | |
} | |
}); | |
_pluginHooks.default.getSingleton().add('afterDestroy', function () { | |
if (registeredPlugins.has(this)) { | |
var pluginsHolder = registeredPlugins.get(this); | |
(0, _object.objectEach)(pluginsHolder, function (plugin) { | |
return plugin.destroy(); | |
}); | |
registeredPlugins.delete(this); | |
} | |
}); | |
} | |
/** | |
* @param {Object} instance | |
* @param {String|Function} pluginName | |
* @returns {Function} pluginClass Returns plugin instance if exists or `undefined` if not exists. | |
*/ | |
function getPlugin(instance, pluginName) { | |
if (typeof pluginName !== 'string') { | |
throw Error('Only strings can be passed as "plugin" parameter'); | |
} | |
var _pluginName = (0, _string.toUpperCaseFirst)(pluginName); | |
if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[_pluginName]) { | |
return void 0; | |
} | |
return registeredPlugins.get(instance)[_pluginName]; | |
} | |
/** | |
* Get all registred plugins names for concrete Handsontable instance. | |
* | |
* @param {Object} hotInstance | |
* @returns {Array} | |
*/ | |
function getRegistredPluginNames(hotInstance) { | |
return registeredPlugins.has(hotInstance) ? Object.keys(registeredPlugins.get(hotInstance)) : []; | |
} | |
/** | |
* Get plugin name. | |
* | |
* @param {Object} hotInstance | |
* @param {Object} plugin | |
* @returns {String|null} | |
*/ | |
function getPluginName(hotInstance, plugin) { | |
var pluginName = null; | |
if (registeredPlugins.has(hotInstance)) { | |
(0, _object.objectEach)(registeredPlugins.get(hotInstance), function (pluginInstance, name) { | |
if (pluginInstance === plugin) { | |
pluginName = name; | |
} | |
}); | |
} | |
return pluginName; | |
} | |
/***/ }), | |
/* 21 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var global = __webpack_require__(38); | |
var getOwnPropertyDescriptor = __webpack_require__(92).f; | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var redefine = __webpack_require__(73); | |
var setGlobal = __webpack_require__(148); | |
var copyConstructorProperties = __webpack_require__(193); | |
var isForced = __webpack_require__(130); | |
/* | |
options.target - name of the target object | |
options.global - target is the global object | |
options.stat - export as static methods of target | |
options.proto - export as prototype methods of target | |
options.real - real prototype method for the `pure` version | |
options.forced - export even if the native feature is available | |
options.bind - bind methods to the target, required for the `pure` version | |
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version | |
options.unsafe - use the simple assignment of property instead of delete + defineProperty | |
options.sham - add a flag to not completely full polyfills | |
options.enumerable - export as enumerable property | |
options.noTargetGet - prevent calling a getter on target | |
*/ | |
module.exports = function (options, source) { | |
var TARGET = options.target; | |
var GLOBAL = options.global; | |
var STATIC = options.stat; | |
var FORCED, target, key, targetProperty, sourceProperty, descriptor; | |
if (GLOBAL) { | |
target = global; | |
} else if (STATIC) { | |
target = global[TARGET] || setGlobal(TARGET, {}); | |
} else { | |
target = (global[TARGET] || {}).prototype; | |
} | |
if (target) for (key in source) { | |
sourceProperty = source[key]; | |
if (options.noTargetGet) { | |
descriptor = getOwnPropertyDescriptor(target, key); | |
targetProperty = descriptor && descriptor.value; | |
} else targetProperty = target[key]; | |
FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); | |
// contained in target | |
if (!FORCED && targetProperty !== undefined) { | |
if (typeof sourceProperty === typeof targetProperty) continue; | |
copyConstructorProperties(sourceProperty, targetProperty); | |
} | |
// add a flag to not completely full polyfills | |
if (options.sham || (targetProperty && targetProperty.sham)) { | |
createNonEnumerableProperty(sourceProperty, 'sham', true); | |
} | |
// extend global | |
redefine(target, key, sourceProperty, options); | |
} | |
}; | |
/***/ }), | |
/* 22 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(15); | |
__webpack_require__(12); | |
__webpack_require__(34); | |
__webpack_require__(9); | |
__webpack_require__(11); | |
__webpack_require__(23); | |
__webpack_require__(13); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _object = __webpack_require__(4); | |
var _array = __webpack_require__(3); | |
var _plugins = __webpack_require__(20); | |
var privatePool = new WeakMap(); | |
var initializedPlugins = null; | |
/** | |
* @util | |
*/ | |
var BasePlugin = | |
/*#__PURE__*/ | |
function () { | |
/** | |
* @param {Object} hotInstance Handsontable instance. | |
*/ | |
function BasePlugin(hotInstance) { | |
var _this = this; | |
(0, _classCallCheck2.default)(this, BasePlugin); | |
/** | |
* Handsontable instance. | |
* | |
* @type {Core} | |
*/ | |
(0, _object.defineGetter)(this, 'hot', hotInstance, { | |
writable: false | |
}); | |
privatePool.set(this, { | |
hooks: {} | |
}); | |
initializedPlugins = null; | |
this.pluginName = null; | |
this.pluginsInitializedCallbacks = []; | |
this.isPluginsReady = false; | |
this.enabled = false; | |
this.initialized = false; | |
this.hot.addHook('afterPluginsInitialized', function () { | |
return _this.onAfterPluginsInitialized(); | |
}); | |
this.hot.addHook('afterUpdateSettings', function (newSettings) { | |
return _this.onUpdateSettings(newSettings); | |
}); | |
this.hot.addHook('beforeInit', function () { | |
return _this.init(); | |
}); | |
} | |
(0, _createClass2.default)(BasePlugin, [{ | |
key: "init", | |
value: function init() { | |
this.pluginName = (0, _plugins.getPluginName)(this.hot, this); | |
if (this.isEnabled && this.isEnabled()) { | |
this.enablePlugin(); | |
} | |
if (!initializedPlugins) { | |
initializedPlugins = (0, _plugins.getRegistredPluginNames)(this.hot); | |
} | |
if (initializedPlugins.indexOf(this.pluginName) >= 0) { | |
initializedPlugins.splice(initializedPlugins.indexOf(this.pluginName), 1); | |
} | |
if (!initializedPlugins.length) { | |
this.hot.runHooks('afterPluginsInitialized'); | |
} | |
this.initialized = true; | |
} | |
/** | |
* Enable plugin for this Handsontable instance. | |
*/ | |
}, { | |
key: "enablePlugin", | |
value: function enablePlugin() { | |
this.enabled = true; | |
} | |
/** | |
* Disable plugin for this Handsontable instance. | |
*/ | |
}, { | |
key: "disablePlugin", | |
value: function disablePlugin() { | |
if (this.eventManager) { | |
this.eventManager.clear(); | |
} | |
this.clearHooks(); | |
this.enabled = false; | |
} | |
/** | |
* Add listener to plugin hooks system. | |
* | |
* @param {String} name | |
* @param {Function} callback | |
*/ | |
}, { | |
key: "addHook", | |
value: function addHook(name, callback) { | |
privatePool.get(this).hooks[name] = privatePool.get(this).hooks[name] || []; | |
var hooks = privatePool.get(this).hooks[name]; | |
this.hot.addHook(name, callback); | |
hooks.push(callback); | |
privatePool.get(this).hooks[name] = hooks; | |
} | |
/** | |
* Remove all hooks listeners by hook name. | |
* | |
* @param {String} name | |
*/ | |
}, { | |
key: "removeHooks", | |
value: function removeHooks(name) { | |
var _this2 = this; | |
(0, _array.arrayEach)(privatePool.get(this).hooks[name] || [], function (callback) { | |
_this2.hot.removeHook(name, callback); | |
}); | |
} | |
/** | |
* Clear all hooks. | |
*/ | |
}, { | |
key: "clearHooks", | |
value: function clearHooks() { | |
var _this3 = this; | |
var hooks = privatePool.get(this).hooks; | |
(0, _object.objectEach)(hooks, function (callbacks, name) { | |
return _this3.removeHooks(name); | |
}); | |
hooks.length = 0; | |
} | |
/** | |
* Register function which will be immediately called after all plugins initialized. | |
* | |
* @param {Function} callback | |
*/ | |
}, { | |
key: "callOnPluginsReady", | |
value: function callOnPluginsReady(callback) { | |
if (this.isPluginsReady) { | |
callback(); | |
} else { | |
this.pluginsInitializedCallbacks.push(callback); | |
} | |
} | |
/** | |
* On after plugins initialized listener. | |
* | |
* @private | |
*/ | |
}, { | |
key: "onAfterPluginsInitialized", | |
value: function onAfterPluginsInitialized() { | |
(0, _array.arrayEach)(this.pluginsInitializedCallbacks, function (callback) { | |
return callback(); | |
}); | |
this.pluginsInitializedCallbacks.length = 0; | |
this.isPluginsReady = true; | |
} | |
/** | |
* On update settings listener. | |
* | |
* @private | |
*/ | |
}, { | |
key: "onUpdateSettings", | |
value: function onUpdateSettings() { | |
if (this.isEnabled) { | |
if (this.enabled && !this.isEnabled()) { | |
this.disablePlugin(); | |
} | |
if (!this.enabled && this.isEnabled()) { | |
this.enablePlugin(); | |
} | |
if (this.enabled && this.isEnabled()) { | |
this.updatePlugin(); | |
} | |
} | |
} | |
/** | |
* Updates the plugin to use the latest options you have specified. | |
* | |
* @private | |
*/ | |
}, { | |
key: "updatePlugin", | |
value: function updatePlugin() {} | |
/** | |
* Destroy plugin. | |
*/ | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
var _this4 = this; | |
if (this.eventManager) { | |
this.eventManager.destroy(); | |
} | |
this.clearHooks(); | |
(0, _object.objectEach)(this, function (value, property) { | |
if (property !== 'hot') { | |
_this4[property] = null; | |
} | |
}); | |
delete this.t; | |
delete this.hot; | |
} | |
}]); | |
return BasePlugin; | |
}(); | |
var _default = BasePlugin; | |
exports.default = _default; | |
/***/ }), | |
/* 23 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var global = __webpack_require__(38); | |
var redefineAll = __webpack_require__(155); | |
var InternalMetadataModule = __webpack_require__(133); | |
var collection = __webpack_require__(134); | |
var collectionWeak = __webpack_require__(208); | |
var isObject = __webpack_require__(44); | |
var enforceIternalState = __webpack_require__(88).enforce; | |
var NATIVE_WEAK_MAP = __webpack_require__(192); | |
var IS_IE11 = !global.ActiveXObject && 'ActiveXObject' in global; | |
var isExtensible = Object.isExtensible; | |
var InternalWeakMap; | |
var wrapper = function (get) { | |
return function WeakMap() { | |
return get(this, arguments.length ? arguments[0] : undefined); | |
}; | |
}; | |
// `WeakMap` constructor | |
// https://tc39.github.io/ecma262/#sec-weakmap-constructor | |
var $WeakMap = module.exports = collection('WeakMap', wrapper, collectionWeak, true, true); | |
// IE11 WeakMap frozen keys fix | |
// We can't use feature detection because it crash some old IE builds | |
// https://github.com/zloirock/core-js/issues/485 | |
if (NATIVE_WEAK_MAP && IS_IE11) { | |
InternalWeakMap = collectionWeak.getConstructor(wrapper, 'WeakMap', true); | |
InternalMetadataModule.REQUIRED = true; | |
var WeakMapPrototype = $WeakMap.prototype; | |
var nativeDelete = WeakMapPrototype['delete']; | |
var nativeHas = WeakMapPrototype.has; | |
var nativeGet = WeakMapPrototype.get; | |
var nativeSet = WeakMapPrototype.set; | |
redefineAll(WeakMapPrototype, { | |
'delete': function (key) { | |
if (isObject(key) && !isExtensible(key)) { | |
var state = enforceIternalState(this); | |
if (!state.frozen) state.frozen = new InternalWeakMap(); | |
return nativeDelete.call(this, key) || state.frozen['delete'](key); | |
} return nativeDelete.call(this, key); | |
}, | |
has: function has(key) { | |
if (isObject(key) && !isExtensible(key)) { | |
var state = enforceIternalState(this); | |
if (!state.frozen) state.frozen = new InternalWeakMap(); | |
return nativeHas.call(this, key) || state.frozen.has(key); | |
} return nativeHas.call(this, key); | |
}, | |
get: function get(key) { | |
if (isObject(key) && !isExtensible(key)) { | |
var state = enforceIternalState(this); | |
if (!state.frozen) state.frozen = new InternalWeakMap(); | |
return nativeHas.call(this, key) ? nativeGet.call(this, key) : state.frozen.get(key); | |
} return nativeGet.call(this, key); | |
}, | |
set: function set(key, value) { | |
if (isObject(key) && !isExtensible(key)) { | |
var state = enforceIternalState(this); | |
if (!state.frozen) state.frozen = new InternalWeakMap(); | |
nativeHas.call(this, key) ? nativeSet.call(this, key, value) : state.frozen.set(key, value); | |
} else nativeSet.call(this, key, value); | |
return this; | |
} | |
}); | |
} | |
/***/ }), | |
/* 24 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(9); | |
__webpack_require__(39); | |
__webpack_require__(432); | |
__webpack_require__(227); | |
__webpack_require__(42); | |
__webpack_require__(53); | |
exports.__esModule = true; | |
exports.stringify = stringify; | |
exports.isDefined = isDefined; | |
exports.isUndefined = isUndefined; | |
exports.isEmpty = isEmpty; | |
exports.isRegExp = isRegExp; | |
exports._injectProductInfo = _injectProductInfo; | |
var _taggedTemplateLiteral2 = _interopRequireDefault(__webpack_require__(69)); | |
var _typeof2 = _interopRequireDefault(__webpack_require__(46)); | |
var _moment = _interopRequireDefault(__webpack_require__(64)); | |
var _templateLiteralTag = __webpack_require__(70); | |
function _templateObject6() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable is missing. Use your purchased key to activate the product. \n Alternatively, you can activate Handsontable to use for non-commercial purposes by \n passing the key: 'non-commercial-and-evaluation'. \n <a href=\"https://handsontable.com/docs/tutorial-license-key.html\" target=\"_blank\">Read more</a> about it in \n the documentation or contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."], ["\n The license key for Handsontable is missing. Use your purchased key to activate the product.\\x20\n Alternatively, you can activate Handsontable to use for non-commercial purposes by\\x20\n passing the key: 'non-commercial-and-evaluation'.\\x20\n <a href=\"https://handsontable.com/docs/tutorial-license-key.html\" target=\"_blank\">Read more</a> about it in\\x20\n the documentation or contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."]); | |
_templateObject6 = function _templateObject6() { | |
return data; | |
}; | |
return data; | |
} | |
function _templateObject5() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable expired on ", ", and is not valid for the installed \n version ", ". <a href=\"https://handsontable.com/pricing\" target=\"_blank\">Renew</a> your \n license key or downgrade to a version released prior to ", ". If you need any \n help, contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."], ["\n The license key for Handsontable expired on ", ", and is not valid for the installed\\x20\n version ", ". <a href=\"https://handsontable.com/pricing\" target=\"_blank\">Renew</a> your\\x20\n license key or downgrade to a version released prior to ", ". If you need any\\x20\n help, contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."]); | |
_templateObject5 = function _templateObject5() { | |
return data; | |
}; | |
return data; | |
} | |
function _templateObject4() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable is invalid. \n <a href=\"https://handsontable.com/docs/tutorial-license-key.html\" target=\"_blank\">Read more</a> on how to \n install it properly or contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."], ["\n The license key for Handsontable is invalid.\\x20\n <a href=\"https://handsontable.com/docs/tutorial-license-key.html\" target=\"_blank\">Read more</a> on how to\\x20\n install it properly or contact us at <a href=\"mailto:[email protected]\">[email protected]</a>."]); | |
_templateObject4 = function _templateObject4() { | |
return data; | |
}; | |
return data; | |
} | |
function _templateObject3() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable is missing. Use your purchased key to activate the product. \n Alternatively, you can activate Handsontable to use for non-commercial purposes by \n passing the key: 'non-commercial-and-evaluation'. If you need any help, contact \n us at [email protected]."], ["\n The license key for Handsontable is missing. Use your purchased key to activate the product.\\x20\n Alternatively, you can activate Handsontable to use for non-commercial purposes by\\x20\n passing the key: 'non-commercial-and-evaluation'. If you need any help, contact\\x20\n us at [email protected]."]); | |
_templateObject3 = function _templateObject3() { | |
return data; | |
}; | |
return data; | |
} | |
function _templateObject2() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable expired on ", ", and is not valid for the installed \n version ", ". Renew your license key at handsontable.com or downgrade to a version released prior \n to ", ". If you need any help, contact us at [email protected]."], ["\n The license key for Handsontable expired on ", ", and is not valid for the installed\\x20\n version ", ". Renew your license key at handsontable.com or downgrade to a version released prior\\x20\n to ", ". If you need any help, contact us at [email protected]."]); | |
_templateObject2 = function _templateObject2() { | |
return data; | |
}; | |
return data; | |
} | |
function _templateObject() { | |
var data = (0, _taggedTemplateLiteral2.default)(["\n The license key for Handsontable is invalid. \n If you need any help, contact us at [email protected]."], ["\n The license key for Handsontable is invalid.\\x20\n If you need any help, contact us at [email protected]."]); | |
_templateObject = function _templateObject() { | |
return data; | |
}; | |
return data; | |
} | |
/** | |
* Converts any value to string. | |
* | |
* @param {*} value | |
* @returns {String} | |
*/ | |
function stringify(value) { | |
var result; | |
switch ((0, _typeof2.default)(value)) { | |
case 'string': | |
case 'number': | |
result = "".concat(value); | |
break; | |
case 'object': | |
result = value === null ? '' : value.toString(); | |
break; | |
case 'undefined': | |
result = ''; | |
break; | |
default: | |
result = value.toString(); | |
break; | |
} | |
return result; | |
} | |
/** | |
* Checks if given variable is defined. | |
* | |
* @param {*} variable Variable to check. | |
* @returns {Boolean} | |
*/ | |
function isDefined(variable) { | |
return typeof variable !== 'undefined'; | |
} | |
/** | |
* Checks if given variable is undefined. | |
* | |
* @param {*} variable Variable to check. | |
* @returns {Boolean} | |
*/ | |
function isUndefined(variable) { | |
return typeof variable === 'undefined'; | |
} | |
/** | |
* Check if given variable is null, empty string or undefined. | |
* | |
* @param {*} variable Variable to check. | |
* @returns {Boolean} | |
*/ | |
function isEmpty(variable) { | |
return variable === null || variable === '' || isUndefined(variable); | |
} | |
/** | |
* Check if given variable is a regular expression. | |
* | |
* @param {*} variable Variable to check. | |
* @returns {Boolean} | |
*/ | |
function isRegExp(variable) { | |
return Object.prototype.toString.call(variable) === '[object RegExp]'; | |
} | |
/* eslint-disable */ | |
var _m = '\x6C\x65\x6E\x67\x74\x68'; | |
var _hd = function _hd(v) { | |
return parseInt(v, 16); | |
}; | |
var _pi = function _pi(v) { | |
return parseInt(v, 10); | |
}; | |
var _ss = function _ss(v, s, l) { | |
return v['\x73\x75\x62\x73\x74\x72'](s, l); | |
}; | |
var _cp = function _cp(v) { | |
return v['\x63\x6F\x64\x65\x50\x6F\x69\x6E\x74\x41\x74'](0) - 65; | |
}; | |
var _norm = function _norm(v) { | |
return "".concat(v).replace(/\-/g, ''); | |
}; | |
var _extractTime = function _extractTime(v) { | |
return _hd(_ss(_norm(v), _hd('12'), _cp('\x46'))) / (_hd(_ss(_norm(v), _cp('\x42'), ~~![][_m])) || 9); | |
}; | |
var _ignored = function _ignored() { | |
return typeof location !== 'undefined' && /^([a-z0-9\-]+\.)?\x68\x61\x6E\x64\x73\x6F\x6E\x74\x61\x62\x6C\x65\x2E\x63\x6F\x6D$/i.test(location.host); | |
}; | |
var _notified = false; | |
var consoleMessages = { | |
invalid: function invalid() { | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject()); | |
}, | |
expired: function expired(_ref) { | |
var keyValidityDate = _ref.keyValidityDate, | |
hotVersion = _ref.hotVersion; | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject2(), keyValidityDate, hotVersion, keyValidityDate); | |
}, | |
missing: function missing() { | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject3()); | |
}, | |
non_commercial: function non_commercial() { | |
return ''; | |
} | |
}; | |
var domMessages = { | |
invalid: function invalid() { | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject4()); | |
}, | |
expired: function expired(_ref2) { | |
var keyValidityDate = _ref2.keyValidityDate, | |
hotVersion = _ref2.hotVersion; | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject5(), keyValidityDate, hotVersion, keyValidityDate); | |
}, | |
missing: function missing() { | |
return (0, _templateLiteralTag.toSingleLine)(_templateObject6()); | |
}, | |
non_commercial: function non_commercial() { | |
return ''; | |
} | |
}; | |
function _injectProductInfo(key, element) { | |
var hasValidType = !isEmpty(key); | |
var isNonCommercial = typeof key === 'string' && key.toLowerCase() === 'non-commercial-and-evaluation'; | |
var hotVersion = "7.2.2"; | |
var keyValidityDate; | |
var consoleMessageState = 'invalid'; | |
var domMessageState = 'invalid'; | |
key = _norm(key || ''); | |
var schemaValidity = _checkKeySchema(key); | |
if (hasValidType || isNonCommercial || schemaValidity) { | |
if (schemaValidity) { | |
var releaseDate = (0, _moment.default)("23/10/2019", 'DD/MM/YYYY'); | |
var releaseDays = Math.floor(releaseDate.toDate().getTime() / 8.64e7); | |
var keyValidityDays = _extractTime(key); | |
keyValidityDate = (0, _moment.default)((keyValidityDays + 1) * 8.64e7, 'x').format('MMMM DD, YYYY'); | |
if (releaseDays > keyValidityDays) { | |
var daysAfterRelease = (0, _moment.default)().diff(releaseDate, 'days'); | |
consoleMessageState = daysAfterRelease <= 1 ? 'valid' : 'expired'; | |
domMessageState = daysAfterRelease <= 15 ? 'valid' : 'expired'; | |
} else { | |
consoleMessageState = 'valid'; | |
domMessageState = 'valid'; | |
} | |
} else if (isNonCommercial) { | |
consoleMessageState = 'non_commercial'; | |
domMessageState = 'valid'; | |
} else { | |
consoleMessageState = 'invalid'; | |
domMessageState = 'invalid'; | |
} | |
} else { | |
consoleMessageState = 'missing'; | |
domMessageState = 'missing'; | |
} | |
if (_ignored()) { | |
consoleMessageState = 'valid'; | |
domMessageState = 'valid'; | |
} | |
if (!_notified && consoleMessageState !== 'valid') { | |
var message = consoleMessages[consoleMessageState]({ | |
keyValidityDate: keyValidityDate, | |
hotVersion: hotVersion | |
}); | |
if (message) { | |
console[consoleMessageState === 'non_commercial' ? 'info' : 'warn'](consoleMessages[consoleMessageState]({ | |
keyValidityDate: keyValidityDate, | |
hotVersion: hotVersion | |
})); | |
} | |
_notified = true; | |
} | |
if (domMessageState !== 'valid' && element.parentNode) { | |
var _message = domMessages[domMessageState]({ | |
keyValidityDate: keyValidityDate, | |
hotVersion: hotVersion | |
}); | |
if (_message) { | |
var messageNode = document.createElement('div'); | |
messageNode.id = 'hot-display-license-info'; | |
messageNode.innerHTML = domMessages[domMessageState]({ | |
keyValidityDate: keyValidityDate, | |
hotVersion: hotVersion | |
}); | |
element.parentNode.insertBefore(messageNode, element.nextSibling); | |
} | |
} | |
} | |
function _checkKeySchema(v) { | |
var z = [][_m]; | |
var p = z; | |
if (v[_m] !== _cp('\x5A')) { | |
return false; | |
} | |
for (var c = '', i = '\x42\x3C\x48\x34\x50\x2B'.split(''), j = _cp(i.shift()); j; j = _cp(i.shift() || 'A')) { | |
--j < ''[_m] ? p = p | (_pi("".concat(_pi(_hd(c) + (_hd(_ss(v, Math.abs(j), 2)) + []).padStart(2, '0')))) % 97 || 2) >> 1 : c = _ss(v, j, !j ? 6 : i[_m] === 1 ? 9 : 8); | |
} | |
return p === z; | |
} | |
/* eslint-enable */ | |
/***/ }), | |
/* 25 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(34); | |
exports.__esModule = true; | |
exports.getListenersCounter = getListenersCounter; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _element = __webpack_require__(8); | |
var _object = __webpack_require__(4); | |
var _feature = __webpack_require__(81); | |
var _event = __webpack_require__(32); | |
/** | |
* Counter which tracks unregistered listeners (useful for detecting memory leaks). | |
* | |
* @type {Number} | |
*/ | |
var listenersCounter = 0; | |
/** | |
* Event DOM manager for internal use in Handsontable. | |
* | |
* @class EventManager | |
* @util | |
*/ | |
var EventManager = | |
/*#__PURE__*/ | |
function () { | |
/** | |
* @param {Object} [context=null] | |
* @private | |
*/ | |
function EventManager() { | |
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | |
(0, _classCallCheck2.default)(this, EventManager); | |
this.context = context || this; | |
if (!this.context.eventListeners) { | |
this.context.eventListeners = []; // TODO perf It would be more performant if every instance of EventManager tracked its own listeners only | |
} | |
} | |
/** | |
* Register specified listener (`eventName`) to the element. | |
* | |
* @param {Element} element Target element. | |
* @param {String} eventName Event name. | |
* @param {Function} callback Function which will be called after event occur. | |
* @param {AddEventListenerOptions|Boolean} [options] Listener options if object or useCapture if boolean. | |
* @returns {Function} Returns function which you can easily call to remove that event | |
*/ | |
(0, _createClass2.default)(EventManager, [{ | |
key: "addEventListener", | |
value: function addEventListener(element, eventName, callback) { | |
var _this = this; | |
var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; | |
var context = this.context; | |
function callbackProxy(event) { | |
callback.call(this, extendEvent(context, event)); | |
} | |
if (typeof options !== 'boolean' && !(0, _feature.isPassiveEventSupported)()) { | |
options = false; | |
} | |
this.context.eventListeners.push({ | |
element: element, | |
event: eventName, | |
callback: callback, | |
callbackProxy: callbackProxy, | |
options: options, | |
eventManager: this | |
}); | |
element.addEventListener(eventName, callbackProxy, options); | |
listenersCounter += 1; | |
return function () { | |
_this.removeEventListener(element, eventName, callback); | |
}; | |
} | |
/** | |
* Remove the event listener previously registered. | |
* | |
* @param {Element} element Target element. | |
* @param {String} eventName Event name. | |
* @param {Function} callback Function to remove from the event target. It must be the same as during registration listener. | |
* @param {Boolean} [onlyOwnEvents] Whether whould remove only events registered using this instance of EventManager | |
*/ | |
}, { | |
key: "removeEventListener", | |
value: function removeEventListener(element, eventName, callback) { | |
var onlyOwnEvents = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; | |
var len = this.context.eventListeners.length; | |
var tmpEvent; | |
while (len) { | |
len -= 1; | |
tmpEvent = this.context.eventListeners[len]; | |
if (tmpEvent.event === eventName && tmpEvent.element === element) { | |
if (callback && callback !== tmpEvent.callback) { | |
/* eslint-disable no-continue */ | |
continue; | |
} | |
if (onlyOwnEvents && tmpEvent.eventManager !== this) { | |
continue; | |
} | |
this.context.eventListeners.splice(len, 1); | |
tmpEvent.element.removeEventListener(tmpEvent.event, tmpEvent.callbackProxy, tmpEvent.options); | |
listenersCounter -= 1; | |
} | |
} | |
} | |
/** | |
* Clear all previously registered events. | |
* | |
* @private | |
* @since 0.15.0-beta3 | |
* @param {Boolean} [onlyOwnEvents] Whether whould remove only events registered using this instance of EventManager | |
*/ | |
}, { | |
key: "clearEvents", | |
value: function clearEvents() { | |
var onlyOwnEvents = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; | |
if (!this.context) { | |
return; | |
} | |
var len = this.context.eventListeners.length; | |
while (len) { | |
len -= 1; | |
var event = this.context.eventListeners[len]; | |
if (event) { | |
this.removeEventListener(event.element, event.event, event.callback, onlyOwnEvents); | |
} | |
} | |
} | |
/** | |
* Clear all previously registered events. | |
*/ | |
}, { | |
key: "clear", | |
value: function clear() { | |
this.clearEvents(); | |
} | |
/** | |
* Destroy instance of EventManager, clearing all events of the context | |
*/ | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
this.clearEvents(); | |
this.context = null; | |
} | |
/** | |
* Destroy instance of EventManager, clearing only the own events | |
*/ | |
}, { | |
key: "destroyWithOwnEventsOnly", | |
value: function destroyWithOwnEventsOnly() { | |
this.clearEvents(true); | |
this.context = null; | |
} | |
/** | |
* Trigger event at the specified target element. | |
* | |
* @param {Element} element Target element. | |
* @param {String} eventName Event name. | |
*/ | |
}, { | |
key: "fireEvent", | |
value: function fireEvent(element, eventName) { | |
var rootDocument = element.document; | |
var rootWindow = element; | |
if (!rootDocument) { | |
rootDocument = element.ownerDocument ? element.ownerDocument : element; | |
rootWindow = rootDocument.defaultView; | |
} | |
var options = { | |
bubbles: true, | |
cancelable: eventName !== 'mousemove', | |
view: rootWindow, | |
detail: 0, | |
screenX: 0, | |
screenY: 0, | |
clientX: 1, | |
clientY: 1, | |
ctrlKey: false, | |
altKey: false, | |
shiftKey: false, | |
metaKey: false, | |
button: 0, | |
relatedTarget: undefined | |
}; | |
var event; | |
if (rootDocument.createEvent) { | |
event = rootDocument.createEvent('MouseEvents'); | |
event.initMouseEvent(eventName, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget || rootDocument.body.parentNode); | |
} else { | |
event = rootDocument.createEventObject(); | |
} | |
if (element.dispatchEvent) { | |
element.dispatchEvent(event); | |
} else { | |
element.fireEvent("on".concat(eventName), event); | |
} | |
} | |
}]); | |
return EventManager; | |
}(); | |
/** | |
* @param {Object} context | |
* @param {Event} event | |
* @private | |
* @returns {*} | |
*/ | |
function extendEvent(context, event) { | |
var componentName = 'HOT-TABLE'; | |
var isHotTableSpotted; | |
var fromElement; | |
var realTarget; | |
var target; | |
var len; | |
event.isTargetWebComponent = false; | |
event.realTarget = event.target; | |
var nativeStopImmediatePropagation = event.stopImmediatePropagation; | |
event.stopImmediatePropagation = function () { | |
nativeStopImmediatePropagation.apply(this); | |
(0, _event.stopImmediatePropagation)(this); | |
}; | |
if (!EventManager.isHotTableEnv) { | |
return event; | |
} // eslint-disable-next-line no-param-reassign | |
event = (0, _element.polymerWrap)(event); | |
len = event.path ? event.path.length : 0; | |
while (len) { | |
len -= 1; | |
if (event.path[len].nodeName === componentName) { | |
isHotTableSpotted = true; | |
} else if (isHotTableSpotted && event.path[len].shadowRoot) { | |
target = event.path[len]; | |
break; | |
} | |
if (len === 0 && !target) { | |
target = event.path[len]; | |
} | |
} | |
if (!target) { | |
target = event.target; | |
} | |
event.isTargetWebComponent = true; | |
if ((0, _feature.isWebComponentSupportedNatively)()) { | |
event.realTarget = event.srcElement || event.toElement; | |
} else if ((0, _object.hasOwnProperty)(context, 'hot') || context.isHotTableEnv || context.wtTable) { | |
// Polymer doesn't support `event.target` property properly we must emulate it ourselves | |
if ((0, _object.hasOwnProperty)(context, 'hot')) { | |
// Custom element | |
fromElement = context.hot ? context.hot.view.wt.wtTable.TABLE : null; | |
} else if (context.isHotTableEnv) { | |
// Handsontable.Core | |
fromElement = context.view.activeWt.wtTable.TABLE.parentNode.parentNode; | |
} else if (context.wtTable) { | |
// Walkontable | |
fromElement = context.wtTable.TABLE.parentNode.parentNode; | |
} | |
realTarget = (0, _element.closest)(event.target, [componentName], fromElement); | |
if (realTarget) { | |
event.realTarget = fromElement.querySelector(componentName) || event.target; | |
} else { | |
event.realTarget = event.target; | |
} | |
} | |
Object.defineProperty(event, 'target', { | |
get: function get() { | |
return (0, _element.polymerWrap)(target); | |
}, | |
enumerable: true, | |
configurable: true | |
}); | |
return event; | |
} | |
var _default = EventManager; | |
exports.default = _default; | |
function getListenersCounter() { | |
return listenersCounter; | |
} | |
/***/ }), | |
/* 26 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireWildcard = __webpack_require__(10); | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
exports.Renderer = void 0; | |
var _viewportColumns = _interopRequireDefault(__webpack_require__(216)); | |
exports.ViewportColumnsCalculator = _viewportColumns.default; | |
var _viewportRows = _interopRequireDefault(__webpack_require__(217)); | |
exports.ViewportRowsCalculator = _viewportRows.default; | |
var _coords = _interopRequireDefault(__webpack_require__(111)); | |
exports.CellCoords = _coords.default; | |
var _range = _interopRequireDefault(__webpack_require__(218)); | |
exports.CellRange = _range.default; | |
var _column = _interopRequireDefault(__webpack_require__(219)); | |
exports.ColumnFilter = _column.default; | |
var _row = _interopRequireDefault(__webpack_require__(220)); | |
exports.RowFilter = _row.default; | |
var _master = _interopRequireDefault(__webpack_require__(221)); | |
exports.MasterTable = _master.default; | |
var _left = _interopRequireDefault(__webpack_require__(447)); | |
exports.LeftOverlay = _left.default; | |
var _top = _interopRequireDefault(__webpack_require__(449)); | |
exports.TopOverlay = _top.default; | |
var _topLeftCorner = _interopRequireDefault(__webpack_require__(451)); | |
exports.TopLeftCornerOverlay = _topLeftCorner.default; | |
var _bottom = _interopRequireDefault(__webpack_require__(453)); | |
exports.BottomOverlay = _bottom.default; | |
var _bottomLeftCorner = _interopRequireDefault(__webpack_require__(455)); | |
exports.BottomLeftCornerOverlay = _bottomLeftCorner.default; | |
var _selectionHandle = _interopRequireDefault(__webpack_require__(358)); | |
exports.SelectionHandle = _selectionHandle.default; | |
var _core = _interopRequireDefault(__webpack_require__(348)); | |
exports.default = _core.default; | |
exports.Core = _core.default; | |
var _event = _interopRequireDefault(__webpack_require__(349)); | |
exports.Event = _event.default; | |
var _overlays = _interopRequireDefault(__webpack_require__(350)); | |
exports.Overlays = _overlays.default; | |
var _scroll = _interopRequireDefault(__webpack_require__(351)); | |
exports.Scroll = _scroll.default; | |
var _selection = _interopRequireDefault(__webpack_require__(457)); | |
exports.Selection = _selection.default; | |
var _settings = _interopRequireDefault(__webpack_require__(352)); | |
exports.Settings = _settings.default; | |
var Renderer = _interopRequireWildcard(__webpack_require__(224)); | |
exports.Renderer = Renderer; | |
var _orderView = __webpack_require__(138); | |
exports.OrderView = _orderView.OrderView; | |
exports.SharedOrderView = _orderView.SharedOrderView; | |
var _viewport = _interopRequireDefault(__webpack_require__(353)); | |
exports.Viewport = _viewport.default; | |
var _eventManager = __webpack_require__(25); | |
exports.getListenersCounter = _eventManager.getListenersCounter; | |
var _pathsRenderer = _interopRequireWildcard(__webpack_require__(170)); | |
exports.getSvgPathsRenderer = _pathsRenderer.default; | |
exports.precalculateStylesAndCommands = _pathsRenderer.precalculateStylesAndCommands; | |
var _resizer = _interopRequireDefault(__webpack_require__(171)); | |
exports.getSvgResizer = _resizer.default; | |
/***/ }), | |
/* 27 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var $includes = __webpack_require__(149).includes; | |
var addToUnscopables = __webpack_require__(102); | |
// `Array.prototype.includes` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.includes | |
$({ target: 'Array', proto: true }, { | |
includes: function includes(el /* , fromIndex = 0 */) { | |
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); | |
} | |
}); | |
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables | |
addToUnscopables('includes'); | |
/***/ }), | |
/* 28 */ | |
/***/ (function(module, exports) { | |
module.exports = function (exec) { | |
try { | |
return !!exec(); | |
} catch (error) { | |
return true; | |
} | |
}; | |
/***/ }), | |
/* 29 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(17); | |
exports.__esModule = true; | |
exports.getCondition = getCondition; | |
exports.getConditionDescriptor = getConditionDescriptor; | |
exports.registerCondition = registerCondition; | |
exports.conditions = void 0; | |
var conditions = {}; | |
/** | |
* Get condition closure with pre-bound arguments. | |
* | |
* @param {String} name Condition name. | |
* @param {Array} args Condition arguments. | |
* @returns {Function} | |
*/ | |
exports.conditions = conditions; | |
function getCondition(name, args) { | |
if (!conditions[name]) { | |
throw Error("Filter condition \"".concat(name, "\" does not exist.")); | |
} | |
var _conditions$name = conditions[name], | |
condition = _conditions$name.condition, | |
descriptor = _conditions$name.descriptor; | |
var conditionArguments = args; | |
if (descriptor.inputValuesDecorator) { | |
conditionArguments = descriptor.inputValuesDecorator(conditionArguments); | |
} | |
return function (dataRow) { | |
return condition.apply(dataRow.meta.instance, [].concat([dataRow], [conditionArguments])); | |
}; | |
} | |
/** | |
* Get condition object descriptor which defines some additional informations about this condition. | |
* | |
* @param {String} name Condition name. | |
* @returns {Object} | |
*/ | |
function getConditionDescriptor(name) { | |
if (!conditions[name]) { | |
throw Error("Filter condition \"".concat(name, "\" does not exist.")); | |
} | |
return conditions[name].descriptor; | |
} | |
/** | |
* Condition registerer. | |
* | |
* @param {String} name Condition name. | |
* @param {Function} condition Condition function | |
* @param {Object} descriptor Condition descriptor | |
*/ | |
function registerCondition(name, condition, descriptor) { | |
descriptor.key = name; | |
conditions[name] = { | |
condition: condition, | |
descriptor: descriptor | |
}; | |
} | |
/***/ }), | |
/* 30 */ | |
/***/ (function(module, exports) { | |
function _assertThisInitialized(self) { | |
if (self === void 0) { | |
throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); | |
} | |
return self; | |
} | |
module.exports = _assertThisInitialized; | |
/***/ }), | |
/* 31 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var isObject = __webpack_require__(44); | |
var isArray = __webpack_require__(106); | |
var toAbsoluteIndex = __webpack_require__(129); | |
var toLength = __webpack_require__(52); | |
var toIndexedObject = __webpack_require__(67); | |
var createProperty = __webpack_require__(108); | |
var arrayMethodHasSpeciesSupport = __webpack_require__(109); | |
var wellKnownSymbol = __webpack_require__(37); | |
var SPECIES = wellKnownSymbol('species'); | |
var nativeSlice = [].slice; | |
var max = Math.max; | |
// `Array.prototype.slice` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.slice | |
// fallback for not array-like ES3 strings and DOM objects | |
$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, { | |
slice: function slice(start, end) { | |
var O = toIndexedObject(this); | |
var length = toLength(O.length); | |
var k = toAbsoluteIndex(start, length); | |
var fin = toAbsoluteIndex(end === undefined ? length : end, length); | |
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible | |
var Constructor, result, n; | |
if (isArray(O)) { | |
Constructor = O.constructor; | |
// cross-realm fallback | |
if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { | |
Constructor = undefined; | |
} else if (isObject(Constructor)) { | |
Constructor = Constructor[SPECIES]; | |
if (Constructor === null) Constructor = undefined; | |
} | |
if (Constructor === Array || Constructor === undefined) { | |
return nativeSlice.call(O, k, fin); | |
} | |
} | |
result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0)); | |
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]); | |
result.length = n; | |
return result; | |
} | |
}); | |
/***/ }), | |
/* 32 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.stopImmediatePropagation = stopImmediatePropagation; | |
exports.isImmediatePropagationStopped = isImmediatePropagationStopped; | |
exports.stopPropagation = stopPropagation; | |
exports.pageX = pageX; | |
exports.pageY = pageY; | |
exports.isRightClick = isRightClick; | |
exports.isLeftClick = isLeftClick; | |
var _element = __webpack_require__(8); | |
/** | |
* Prevent other listeners of the same event from being called. | |
* | |
* @param {Event} event | |
*/ | |
function stopImmediatePropagation(event) { | |
event.isImmediatePropagationEnabled = false; | |
event.cancelBubble = true; | |
} | |
/** | |
* Check if event was stopped by `stopImmediatePropagation`. | |
* | |
* @param event {Event} | |
* @returns {Boolean} | |
*/ | |
function isImmediatePropagationStopped(event) { | |
return event.isImmediatePropagationEnabled === false; | |
} | |
/** | |
* Prevent further propagation of the current event (prevent bubbling). | |
* | |
* @param event {Event} | |
*/ | |
function stopPropagation(event) { | |
// ie8 | |
// http://msdn.microsoft.com/en-us/library/ie/ff975462(v=vs.85).aspx | |
if (typeof event.stopPropagation === 'function') { | |
event.stopPropagation(); | |
} else { | |
event.cancelBubble = true; | |
} | |
} | |
/** | |
* Get horizontal coordinate of the event object relative to the whole document. | |
* | |
* @param {Event} event | |
* @returns {Number} | |
*/ | |
function pageX(event) { | |
if (event.pageX) { | |
return event.pageX; | |
} | |
var rootWindow = event.target.ownerDocument.defaultView; | |
return event.clientX + (0, _element.getWindowScrollLeft)(rootWindow); | |
} | |
/** | |
* Get vertical coordinate of the event object relative to the whole document. | |
* | |
* @param {Event} event | |
* @returns {Number} | |
*/ | |
function pageY(event) { | |
if (event.pageY) { | |
return event.pageY; | |
} | |
var frame = event.target.ownerDocument.defaultView; | |
var offset = (0, _element.getWindowScrollTop)(frame); | |
frame = (0, _element.getParentWindow)(frame); | |
while (frame) { | |
offset -= (0, _element.getWindowScrollTop)(frame); | |
frame = (0, _element.getParentWindow)(frame); | |
} | |
return event.clientY + offset; | |
} | |
/** | |
* Check if provided event was triggered by clicking the right mouse button. | |
* | |
* @param {Event} event DOM Event. | |
* @returns {Boolean} | |
*/ | |
function isRightClick(event) { | |
return event.button === 2; | |
} | |
/** | |
* Check if provided event was triggered by clicking the left mouse button. | |
* | |
* @param {Event} event DOM Event. | |
* @returns {Boolean} | |
*/ | |
function isLeftClick(event) { | |
return event.button === 0; | |
} | |
/***/ }), | |
/* 33 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var arrayWithoutHoles = __webpack_require__(418); | |
var iterableToArray = __webpack_require__(212); | |
var nonIterableSpread = __webpack_require__(419); | |
function _toConsumableArray(arr) { | |
return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); | |
} | |
module.exports = _toConsumableArray; | |
/***/ }), | |
/* 34 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var toAbsoluteIndex = __webpack_require__(129); | |
var toInteger = __webpack_require__(79); | |
var toLength = __webpack_require__(52); | |
var toObject = __webpack_require__(62); | |
var arraySpeciesCreate = __webpack_require__(160); | |
var createProperty = __webpack_require__(108); | |
var arrayMethodHasSpeciesSupport = __webpack_require__(109); | |
var max = Math.max; | |
var min = Math.min; | |
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; | |
var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; | |
// `Array.prototype.splice` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.splice | |
// with adding support of @@species | |
$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('splice') }, { | |
splice: function splice(start, deleteCount /* , ...items */) { | |
var O = toObject(this); | |
var len = toLength(O.length); | |
var actualStart = toAbsoluteIndex(start, len); | |
var argumentsLength = arguments.length; | |
var insertCount, actualDeleteCount, A, k, from, to; | |
if (argumentsLength === 0) { | |
insertCount = actualDeleteCount = 0; | |
} else if (argumentsLength === 1) { | |
insertCount = 0; | |
actualDeleteCount = len - actualStart; | |
} else { | |
insertCount = argumentsLength - 2; | |
actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart); | |
} | |
if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { | |
throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); | |
} | |
A = arraySpeciesCreate(O, actualDeleteCount); | |
for (k = 0; k < actualDeleteCount; k++) { | |
from = actualStart + k; | |
if (from in O) createProperty(A, k, O[from]); | |
} | |
A.length = actualDeleteCount; | |
if (insertCount < actualDeleteCount) { | |
for (k = actualStart; k < len - actualDeleteCount; k++) { | |
from = k + actualDeleteCount; | |
to = k + insertCount; | |
if (from in O) O[to] = O[from]; | |
else delete O[to]; | |
} | |
for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; | |
} else if (insertCount > actualDeleteCount) { | |
for (k = len - actualDeleteCount; k > actualStart; k--) { | |
from = k + actualDeleteCount - 1; | |
to = k + insertCount - 1; | |
if (from in O) O[to] = O[from]; | |
else delete O[to]; | |
} | |
} | |
for (k = 0; k < insertCount; k++) { | |
O[k + actualStart] = arguments[k + 2]; | |
} | |
O.length = len - actualDeleteCount + insertCount; | |
return A; | |
} | |
}); | |
/***/ }), | |
/* 35 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var notARegExp = __webpack_require__(166); | |
var requireObjectCoercible = __webpack_require__(54); | |
var correctIsRegExpLogic = __webpack_require__(167); | |
// `String.prototype.includes` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype.includes | |
$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, { | |
includes: function includes(searchString /* , position = 0 */) { | |
return !!~String(requireObjectCoercible(this)) | |
.indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined); | |
} | |
}); | |
/***/ }), | |
/* 36 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var $ = __webpack_require__(21); | |
var global = __webpack_require__(38); | |
var userAgent = __webpack_require__(169); | |
var slice = [].slice; | |
var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check | |
var wrap = function (scheduler) { | |
return function (handler, timeout /* , ...arguments */) { | |
var boundArgs = arguments.length > 2; | |
var args = boundArgs ? slice.call(arguments, 2) : undefined; | |
return scheduler(boundArgs ? function () { | |
// eslint-disable-next-line no-new-func | |
(typeof handler == 'function' ? handler : Function(handler)).apply(this, args); | |
} : handler, timeout); | |
}; | |
}; | |
// ie9- setTimeout & setInterval additional parameters fix | |
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers | |
$({ global: true, bind: true, forced: MSIE }, { | |
// `setTimeout` method | |
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout | |
setTimeout: wrap(global.setTimeout), | |
// `setInterval` method | |
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval | |
setInterval: wrap(global.setInterval) | |
}); | |
/***/ }), | |
/* 37 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var global = __webpack_require__(38); | |
var shared = __webpack_require__(99); | |
var uid = __webpack_require__(127); | |
var NATIVE_SYMBOL = __webpack_require__(198); | |
var Symbol = global.Symbol; | |
var store = shared('wks'); | |
module.exports = function (name) { | |
return store[name] || (store[name] = NATIVE_SYMBOL && Symbol[name] | |
|| (NATIVE_SYMBOL ? Symbol : uid)('Symbol.' + name)); | |
}; | |
/***/ }), | |
/* 38 */ | |
/***/ (function(module, exports) { | |
var check = function (it) { | |
return it && it.Math == Math && it; | |
}; | |
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 | |
module.exports = | |
// eslint-disable-next-line no-undef | |
check(typeof globalThis == 'object' && globalThis) || | |
check(typeof window == 'object' && window) || | |
check(typeof self == 'object' && self) || | |
check(typeof global == 'object' && global) || | |
// eslint-disable-next-line no-new-func | |
Function('return this')(); | |
/***/ }), | |
/* 39 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var redefine = __webpack_require__(73); | |
var anObject = __webpack_require__(47); | |
var fails = __webpack_require__(28); | |
var flags = __webpack_require__(161); | |
var TO_STRING = 'toString'; | |
var RegExpPrototype = RegExp.prototype; | |
var nativeToString = RegExpPrototype[TO_STRING]; | |
var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; }); | |
// FF44- RegExp#toString has a wrong name | |
var INCORRECT_NAME = nativeToString.name != TO_STRING; | |
// `RegExp.prototype.toString` method | |
// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring | |
if (NOT_GENERIC || INCORRECT_NAME) { | |
redefine(RegExp.prototype, TO_STRING, function toString() { | |
var R = anObject(this); | |
var p = String(R.source); | |
var rf = R.flags; | |
var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf); | |
return '/' + p + '/' + f; | |
}, { unsafe: true }); | |
} | |
/***/ }), | |
/* 40 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var $filter = __webpack_require__(89).filter; | |
var arrayMethodHasSpeciesSupport = __webpack_require__(109); | |
// `Array.prototype.filter` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.filter | |
// with adding support of @@species | |
$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, { | |
filter: function filter(callbackfn /* , thisArg */) { | |
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); | |
} | |
}); | |
/***/ }), | |
/* 41 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var collection = __webpack_require__(134); | |
var collectionStrong = __webpack_require__(210); | |
// `Map` constructor | |
// https://tc39.github.io/ecma262/#sec-map-objects | |
module.exports = collection('Map', function (get) { | |
return function Map() { return get(this, arguments.length ? arguments[0] : undefined); }; | |
}, collectionStrong, true); | |
/***/ }), | |
/* 42 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var fixRegExpWellKnownSymbolLogic = __webpack_require__(135); | |
var anObject = __webpack_require__(47); | |
var toObject = __webpack_require__(62); | |
var toLength = __webpack_require__(52); | |
var toInteger = __webpack_require__(79); | |
var requireObjectCoercible = __webpack_require__(54); | |
var advanceStringIndex = __webpack_require__(164); | |
var regExpExec = __webpack_require__(136); | |
var max = Math.max; | |
var min = Math.min; | |
var floor = Math.floor; | |
var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; | |
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; | |
var maybeToString = function (it) { | |
return it === undefined ? it : String(it); | |
}; | |
// @@replace logic | |
fixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) { | |
return [ | |
// `String.prototype.replace` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype.replace | |
function replace(searchValue, replaceValue) { | |
var O = requireObjectCoercible(this); | |
var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; | |
return replacer !== undefined | |
? replacer.call(searchValue, O, replaceValue) | |
: nativeReplace.call(String(O), searchValue, replaceValue); | |
}, | |
// `RegExp.prototype[@@replace]` method | |
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace | |
function (regexp, replaceValue) { | |
var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); | |
if (res.done) return res.value; | |
var rx = anObject(regexp); | |
var S = String(this); | |
var functionalReplace = typeof replaceValue === 'function'; | |
if (!functionalReplace) replaceValue = String(replaceValue); | |
var global = rx.global; | |
if (global) { | |
var fullUnicode = rx.unicode; | |
rx.lastIndex = 0; | |
} | |
var results = []; | |
while (true) { | |
var result = regExpExec(rx, S); | |
if (result === null) break; | |
results.push(result); | |
if (!global) break; | |
var matchStr = String(result[0]); | |
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); | |
} | |
var accumulatedResult = ''; | |
var nextSourcePosition = 0; | |
for (var i = 0; i < results.length; i++) { | |
result = results[i]; | |
var matched = String(result[0]); | |
var position = max(min(toInteger(result.index), S.length), 0); | |
var captures = []; | |
// NOTE: This is equivalent to | |
// captures = result.slice(1).map(maybeToString) | |
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in | |
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and | |
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. | |
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); | |
var namedCaptures = result.groups; | |
if (functionalReplace) { | |
var replacerArgs = [matched].concat(captures, position, S); | |
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); | |
var replacement = String(replaceValue.apply(undefined, replacerArgs)); | |
} else { | |
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); | |
} | |
if (position >= nextSourcePosition) { | |
accumulatedResult += S.slice(nextSourcePosition, position) + replacement; | |
nextSourcePosition = position + matched.length; | |
} | |
} | |
return accumulatedResult + S.slice(nextSourcePosition); | |
} | |
]; | |
// https://tc39.github.io/ecma262/#sec-getsubstitution | |
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { | |
var tailPos = position + matched.length; | |
var m = captures.length; | |
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; | |
if (namedCaptures !== undefined) { | |
namedCaptures = toObject(namedCaptures); | |
symbols = SUBSTITUTION_SYMBOLS; | |
} | |
return nativeReplace.call(replacement, symbols, function (match, ch) { | |
var capture; | |
switch (ch.charAt(0)) { | |
case '$': return '$'; | |
case '&': return matched; | |
case '`': return str.slice(0, position); | |
case "'": return str.slice(tailPos); | |
case '<': | |
capture = namedCaptures[ch.slice(1, -1)]; | |
break; | |
default: // \d\d? | |
var n = +ch; | |
if (n === 0) return match; | |
if (n > m) { | |
var f = floor(n / 10); | |
if (f === 0) return match; | |
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); | |
return match; | |
} | |
capture = captures[n - 1]; | |
} | |
return capture === undefined ? '' : capture; | |
}); | |
} | |
}); | |
/***/ }), | |
/* 43 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
exports.getRenderer = _getItem; | |
exports.getRegisteredRenderers = exports.getRegisteredRendererNames = exports.hasRenderer = exports.registerRenderer = void 0; | |
var _staticRegister2 = _interopRequireDefault(__webpack_require__(80)); | |
var _cellDecorator = _interopRequireDefault(__webpack_require__(460)); | |
var _autocompleteRenderer = _interopRequireDefault(__webpack_require__(461)); | |
var _checkboxRenderer = _interopRequireDefault(__webpack_require__(462)); | |
var _htmlRenderer = _interopRequireDefault(__webpack_require__(463)); | |
var _numericRenderer = _interopRequireDefault(__webpack_require__(464)); | |
var _passwordRenderer = _interopRequireDefault(__webpack_require__(465)); | |
var _textRenderer = _interopRequireDefault(__webpack_require__(466)); | |
var _staticRegister = (0, _staticRegister2.default)('renderers'), | |
register = _staticRegister.register, | |
getItem = _staticRegister.getItem, | |
hasItem = _staticRegister.hasItem, | |
getNames = _staticRegister.getNames, | |
getValues = _staticRegister.getValues; | |
exports.getRegisteredRenderers = getValues; | |
exports.getRegisteredRendererNames = getNames; | |
exports.hasRenderer = hasItem; | |
exports.registerRenderer = register; | |
register('base', _cellDecorator.default); | |
register('autocomplete', _autocompleteRenderer.default); | |
register('checkbox', _checkboxRenderer.default); | |
register('html', _htmlRenderer.default); | |
register('numeric', _numericRenderer.default); | |
register('password', _passwordRenderer.default); | |
register('text', _textRenderer.default); | |
/** | |
* Retrieve renderer function. | |
* | |
* @param {String} name Renderer identification. | |
* @returns {Function} Returns renderer function. | |
*/ | |
function _getItem(name) { | |
if (typeof name === 'function') { | |
return name; | |
} | |
if (!hasItem(name)) { | |
throw Error("No registered renderer found under \"".concat(name, "\" name")); | |
} | |
return getItem(name); | |
} | |
/***/ }), | |
/* 44 */ | |
/***/ (function(module, exports) { | |
module.exports = function (it) { | |
return typeof it === 'object' ? it !== null : typeof it === 'function'; | |
}; | |
/***/ }), | |
/* 45 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(15); | |
__webpack_require__(34); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _array = __webpack_require__(3); | |
var _object = __webpack_require__(4); | |
/** | |
* @description | |
* Handsontable events are the common interface that function in 2 ways: as __callbacks__ and as __hooks__. | |
* | |
* @example | |
* | |
* ```js | |
* // Using events as callbacks: | |
* ... | |
* const hot1 = new Handsontable(document.getElementById('example1'), { | |
* afterChange: function(changes, source) { | |
* $.ajax({ | |
* url: "save.php', | |
* data: change | |
* }); | |
* } | |
* }); | |
* ... | |
* ``` | |
* | |
* ```js | |
* // Using events as plugin hooks: | |
* ... | |
* const hot1 = new Handsontable(document.getElementById('example1'), { | |
* myPlugin: true | |
* }); | |
* | |
* const hot2 = new Handsontable(document.getElementById('example2'), { | |
* myPlugin: false | |
* }); | |
* | |
* // global hook | |
* Handsontable.hooks.add('afterChange', function() { | |
* // Fired twice - for hot1 and hot2 | |
* if (this.getSettings().myPlugin) { | |
* // function body - will only run for hot1 | |
* } | |
* }); | |
* | |
* // local hook (has same effect as a callback) | |
* hot2.addHook('afterChange', function() { | |
* // function body - will only run in #example2 | |
* }); | |
* ``` | |
* ... | |
*/ | |
// @TODO: Move plugin description hooks to plugin? | |
var REGISTERED_HOOKS = [ | |
/** | |
* Fired after resetting a cell's meta. This happens when the {@link Core#updateSettings} method is called. | |
* | |
* @event Hooks#afterCellMetaReset | |
*/ | |
'afterCellMetaReset', | |
/** | |
* Fired after one or more cells has been changed. The changes are triggered in any situation when the | |
* value is entered using an editor or changed using API (e.q setDataAtCell) | |
* | |
* __Note:__ For performance reasons, the `changes` array is null for `"loadData"` source. | |
* | |
* @event Hooks#afterChange | |
* @param {Array} changes 2D array containing information about each of the edited cells `[[row, prop, oldVal, newVal], ...]`. | |
* @param {String} [source] String that identifies source of hook call ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
* @example | |
* ```js | |
* new Handsontable(element, { | |
* afterChange: (changes) => { | |
* changes.forEach(([row, prop, oldValue, newValue]) => { | |
* // Some logic... | |
* }); | |
* } | |
* }) | |
* ``` | |
*/ | |
'afterChange', | |
/** | |
* Fired by {@link ObserveChanges} plugin after detecting changes in the data source. This hook is fired when | |
* {@link Options#observeChanges} option is enabled. | |
* | |
* @event Hooks#afterChangesObserved | |
*/ | |
'afterChangesObserved', | |
/** | |
* Fired each time user opens {@link ContextMenu} and after setting up the Context Menu's default options. These options are a collection | |
* which user can select by setting an array of keys or an array of objects in {@link Options#contextMenu} option. | |
* | |
* @event Hooks#afterContextMenuDefaultOptions | |
* @param {Array} predefinedItems An array of objects containing information about the pre-defined Context Menu items. | |
*/ | |
'afterContextMenuDefaultOptions', | |
/** | |
* Fired each time user opens {@link ContextMenu} plugin before setting up the Context Menu's items but after filtering these options by | |
* user (`contextMenu` option). This hook can by helpful to determine if user use specified menu item or to set up | |
* one of the menu item to by always visible. | |
* | |
* @event Hooks#beforeContextMenuSetItems | |
* @param {Object[]} menuItems An array of objects containing information about to generated Context Menu items. | |
*/ | |
'beforeContextMenuSetItems', | |
/** | |
* Fired by {@link DropdownMenu} plugin after setting up the Dropdown Menu's default options. These options are a | |
* collection which user can select by setting an array of keys or an array of objects in {@link Options#dropdownMenu} | |
* option. | |
* | |
* @event Hooks#afterDropdownMenuDefaultOptions | |
* @param {Object[]} predefinedItems An array of objects containing information about the pre-defined Context Menu items. | |
*/ | |
'afterDropdownMenuDefaultOptions', | |
/** | |
* Fired by {@link DropdownMenu} plugin before setting up the Dropdown Menu's items but after filtering these options | |
* by user (`dropdownMenu` option). This hook can by helpful to determine if user use specified menu item or to set | |
* up one of the menu item to by always visible. | |
* | |
* @event Hooks#beforeDropdownMenuSetItems | |
* @param {Object[]} menuItems An array of objects containing information about to generated Dropdown Menu items. | |
*/ | |
'beforeDropdownMenuSetItems', | |
/** | |
* Fired by {@link ContextMenu} plugin after hiding the Context Menu. This hook is fired when {@link Options#contextMenu} | |
* option is enabled. | |
* | |
* @event Hooks#afterContextMenuHide | |
* @param {Object} context The Context Menu plugin instance. | |
*/ | |
'afterContextMenuHide', | |
/** | |
* Fired by {@link ContextMenu} plugin before opening the Context Menu. This hook is fired when {@link Options#contextMenu} | |
* option is enabled. | |
* | |
* @event Hooks#beforeContextMenuShow | |
* @param {Object} context The Context Menu instance. | |
*/ | |
'beforeContextMenuShow', | |
/** | |
* Fired by {@link ContextMenu} plugin after opening the Context Menu. This hook is fired when {@link Options#contextMenu} | |
* option is enabled. | |
* | |
* @event Hooks#afterContextMenuShow | |
* @param {Object} context The Context Menu plugin instance. | |
*/ | |
'afterContextMenuShow', | |
/** | |
* Fired by {@link CopyPaste} plugin after reaching the copy limit while copying data. This hook is fired when | |
* {@link Options#copyPaste} option is enabled. | |
* | |
* @event Hooks#afterCopyLimit | |
* @param {Number} selectedRows Count of selected copyable rows. | |
* @param {Number} selectedColumns Count of selected copyable columns. | |
* @param {Number} copyRowsLimit Current copy rows limit. | |
* @param {Number} copyColumnsLimit Current copy columns limit. | |
*/ | |
'afterCopyLimit', | |
/** | |
* Fired before created a new column. | |
* | |
* @event Hooks#beforeCreateCol | |
* @param {Number} index Represents the visual index of first newly created column in the data source array. | |
* @param {Number} amount Number of newly created columns in the data source array. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link http://docs.handsontable.com/tutorial-using-callbacks.html#page-source-definition}). | |
* @returns {*} If `false` then creating columns is cancelled. | |
* @example | |
* ```js | |
* // Return `false` to cancel column inserting. | |
* new Handsontable(element, { | |
* beforeCreateCol: function(data, coords) { | |
* return false; | |
* } | |
* }); | |
* ``` | |
*/ | |
'beforeCreateCol', | |
/** | |
* Fired after created a new column. | |
* | |
* @event Hooks#afterCreateCol | |
* @param {Number} index Represents the visual index of first newly created column in the data source. | |
* @param {Number} amount Number of newly created columns in the data source. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterCreateCol', | |
/** | |
* Fired before created a new row. | |
* | |
* @event Hooks#beforeCreateRow | |
* @param {Number} index Represents the visual index of first newly created row in the data source array. | |
* @param {Number} amount Number of newly created rows in the data source array. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'beforeCreateRow', | |
/** | |
* Fired after created a new row. | |
* | |
* @event Hooks#afterCreateRow | |
* @param {Number} index Represents the visual index of first newly created row in the data source array. | |
* @param {Number} amount Number of newly created rows in the data source array. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterCreateRow', | |
/** | |
* Fired after the current cell is deselected. | |
* | |
* @event Hooks#afterDeselect | |
*/ | |
'afterDeselect', | |
/** | |
* Fired after destroying the Handsontable instance. | |
* | |
* @event Hooks#afterDestroy | |
*/ | |
'afterDestroy', | |
/** | |
* General hook which captures `keydown` events attached to the document body. These events are delegated to the | |
* hooks system and consumed by Core and internal modules (e.g plugins, editors). | |
* | |
* @event Hooks#afterDocumentKeyDown | |
* @param {Event} event A native `keydown` event object. | |
*/ | |
'afterDocumentKeyDown', | |
/** | |
* Fired inside the Walkontable's selection `draw` method. Can be used to add additional class names to cells, depending on the current selection. | |
* | |
* @event Hooks#afterDrawSelection | |
* @param {Number} currentRow Row index of the currently processed cell. | |
* @param {Number} currentColumn Column index of the currently cell. | |
* @param {Number[]} cornersOfSelection Array of the current selection in a form of `[startRow, startColumn, endRow, endColumn]`. | |
* @param {Number|undefined} layerLevel Number indicating which layer of selection is currently processed. | |
* @since 0.38.1 | |
* @returns {String|undefined} Can return a `String`, which will act as an additional `className` to be added to the currently processed cell. | |
*/ | |
'afterDrawSelection', | |
/** | |
* Fired inside the Walkontable's `refreshSelections` method. Can be used to remove additional class names from all cells in the table. | |
* | |
* @event Hooks#beforeRemoveCellClassNames | |
* @since 0.38.1 | |
* @returns {String[]|undefined} Can return an `Array` of `String`s. Each of these strings will act like class names to be removed from all the cells in the table. | |
*/ | |
'beforeRemoveCellClassNames', | |
/** | |
* Fired after getting the cell settings. | |
* | |
* @event Hooks#afterGetCellMeta | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {Object} cellProperties Object containing the cell properties. | |
*/ | |
'afterGetCellMeta', | |
/** | |
* Fired after retrieving information about a column header and appending it to the table header. | |
* | |
* @event Hooks#afterGetColHeader | |
* @param {Number} column Visual column index. | |
* @param {HTMLTableCellElement} TH Header's TH element. | |
*/ | |
'afterGetColHeader', | |
/** | |
* Fired after retrieving information about a row header and appending it to the table header. | |
* | |
* @event Hooks#afterGetRowHeader | |
* @param {Number} row Visual row index. | |
* @param {HTMLTableCellElement} TH Header's TH element. | |
*/ | |
'afterGetRowHeader', | |
/** | |
* Fired after the Handsontable instance is initiated. | |
* | |
* @event Hooks#afterInit | |
*/ | |
'afterInit', | |
/** | |
* Fired after new data is loaded (by `loadData` or `updateSettings` method) into the data source array. | |
* | |
* @event Hooks#afterLoadData | |
* @param {Array} sourceData Array of arrays or array of objects containing data. | |
* @param {Boolean} initialLoad flag that determines whether the data has been loaded during the initialization. | |
*/ | |
'afterLoadData', | |
/** | |
* Fired after a scroll event, which is identified as a momentum scroll (e.g. on an iPad). | |
* | |
* @event Hooks#afterMomentumScroll | |
*/ | |
'afterMomentumScroll', | |
/** | |
* Fired after a `mousedown` event is triggered on the cell corner (the drag handle). | |
* | |
* @event Hooks#afterOnCellCornerMouseDown | |
* @param {Event} event `mousedown` event object. | |
*/ | |
'afterOnCellCornerMouseDown', | |
/** | |
* Fired after a `dblclick` event is triggered on the cell corner (the drag handle). | |
* | |
* @event Hooks#afterOnCellCornerDblClick | |
* @param {Event} event `dblclick` event object. | |
*/ | |
'afterOnCellCornerDblClick', | |
/** | |
* Fired after clicking on a cell or row/column header. In case the row/column header was clicked, the coordinate | |
* indexes are negative. | |
* | |
* For example clicking on the row header of cell (0, 0) results with `afterOnCellMouseDown` called | |
* with coordinates `{row: 0, col: -1}`. | |
* | |
* @event Hooks#afterOnCellMouseDown | |
* @param {Event} event `mousedown` event object. | |
* @param {CellCoords} coords Coordinates object containing the visual row and visual column indexes of the clicked cell. | |
* @param {HTMLTableCellElement} TD Cell's TD (or TH) element. | |
*/ | |
'afterOnCellMouseDown', | |
/** | |
* Fired after clicking on a cell or row/column header. In case the row/column header was clicked, the coordinate | |
* indexes are negative. | |
* | |
* For example clicking on the row header of cell (0, 0) results with `afterOnCellMouseUp` called | |
* with coordinates `{row: 0, col: -1}`. | |
* | |
* @event Hooks#afterOnCellMouseUp | |
* @param {Event} event `mouseup` event object. | |
* @param {CellCoords} coords Coordinates object containing the visual row and visual column indexes of the clicked cell. | |
* @param {HTMLTableCellElement} TD Cell's TD (or TH) element. | |
*/ | |
'afterOnCellMouseUp', | |
/** | |
* Fired after clicking right mouse button on a cell or row/column header. | |
* | |
* For example clicking on the row header of cell (0, 0) results with `afterOnCellContextMenu` called | |
* with coordinates `{row: 0, col: -1}`. | |
* | |
* @event Hooks#afterOnCellContextMenu | |
* @since 4.1.0 | |
* @param {Event} event `contextmenu` event object. | |
* @param {CellCoords} coords Coordinates object containing the visual row and visual column indexes of the clicked cell. | |
* @param {HTMLTableCellElement} TD Cell's TD (or TH) element. | |
*/ | |
'afterOnCellContextMenu', | |
/** | |
* Fired after hovering a cell or row/column header with the mouse cursor. In case the row/column header was | |
* hovered, the index is negative. | |
* | |
* For example, hovering over the row header of cell (0, 0) results with `afterOnCellMouseOver` called | |
* with coords `{row: 0, col: -1}`. | |
* | |
* @event Hooks#afterOnCellMouseOver | |
* @param {Event} event `mouseover` event object. | |
* @param {CellCoords} coords Hovered cell's visual coordinate object. | |
* @param {HTMLTableCellElement} TD Cell's TD (or TH) element. | |
*/ | |
'afterOnCellMouseOver', | |
/** | |
* Fired after leaving a cell or row/column header with the mouse cursor. | |
* | |
* @event Hooks#afterOnCellMouseOut | |
* @param {Event} event `mouseout` event object. | |
* @param {CellCoords} coords Leaved cell's visual coordinate object. | |
* @param {HTMLTableCellElement} TD Cell's TD (or TH) element. | |
*/ | |
'afterOnCellMouseOut', | |
/** | |
* Fired after one or more columns are removed. | |
* | |
* @event Hooks#afterRemoveCol | |
* @param {Number} index Visual index of starter column. | |
* @param {Number} amount An amount of removed columns. | |
* @param {Number[]} physicalColumns An array of physical columns removed from the data source. | |
* @param {String} [source] String that identifies source of hook call ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterRemoveCol', | |
/** | |
* Fired after one or more rows are removed. | |
* | |
* @event Hooks#afterRemoveRow | |
* @param {Number} index Visual index of starter row. | |
* @param {Number} amount An amount of removed rows. | |
* @param {Number[]} physicalRows An array of physical rows removed from the data source. | |
* @param {String} [source] String that identifies source of hook call ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterRemoveRow', | |
/** | |
* Fired after the Handsontable table is rendered. | |
* | |
* @event Hooks#afterRender | |
* @param {Boolean} isForced Is `true` if rendering was triggered by a change of settings or data; or `false` if | |
* rendering was triggered by scrolling or moving selection. | |
*/ | |
'afterRender', | |
/** | |
* Fired before starting rendering the cell. | |
* | |
* @event Hooks#beforeRenderer | |
* @param {HTMLTableCellElement} TD Currently rendered cell's TD element. | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays. | |
* @param {*} value Value of the rendered cell. | |
* @param {Object} cellProperties Object containing the cell's properties. | |
*/ | |
'beforeRenderer', | |
/** | |
* Fired after finishing rendering the cell (after the renderer finishes). | |
* | |
* @event Hooks#afterRenderer | |
* @param {HTMLTableCellElement} TD Currently rendered cell's TD element. | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {String|Number} prop Column property name or a column index, if datasource is an array of arrays. | |
* @param {*} value Value of the rendered cell. | |
* @param {Object} cellProperties Object containing the cell's properties. | |
*/ | |
'afterRenderer', | |
/** | |
* Fired after the horizontal scroll event. | |
* | |
* @event Hooks#afterScrollHorizontally | |
*/ | |
'afterScrollHorizontally', | |
/** | |
* Fired after the vertical scroll event. | |
* | |
* @event Hooks#afterScrollVertically | |
*/ | |
'afterScrollVertically', | |
/** | |
* Fired after one or more cells are selected (e.g. during mouse move). | |
* | |
* @event Hooks#afterSelection | |
* @param {Number} row Selection start visual row index. | |
* @param {Number} column Selection start visual column index. | |
* @param {Number} row2 Selection end visual row index. | |
* @param {Number} column2 Selection end visual column index. | |
* @param {Object} preventScrolling Object with `value` property where its value change will be observed. | |
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified. | |
* @example | |
* ```js | |
* new Handsontable(element, { | |
* afterSelection: (row, column, row2, column2, preventScrolling, selectionLayerLevel) => { | |
* // setting if prevent scrolling after selection | |
* preventScrolling.value = true; | |
* } | |
* }) | |
* ``` | |
*/ | |
'afterSelection', | |
/** | |
* Fired after one or more cells are selected. | |
* | |
* The `prop` and `prop2` arguments represent the source object property name instead of the column number. | |
* | |
* @event Hooks#afterSelectionByProp | |
* @param {Number} row Selection start visual row index. | |
* @param {String} prop Selection start data source object property name. | |
* @param {Number} row2 Selection end visual row index. | |
* @param {String} prop2 Selection end data source object property name. | |
* @param {Object} preventScrolling Object with `value` property where its value change will be observed. | |
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified. | |
* @example | |
* ```js | |
* new Handsontable(element, { | |
* afterSelectionByProp: (row, column, row2, column2, preventScrolling, selectionLayerLevel) => { | |
* // setting if prevent scrolling after selection | |
* preventScrolling.value = true; | |
* } | |
* }) | |
* ``` | |
*/ | |
'afterSelectionByProp', | |
/** | |
* Fired after one or more cells are selected (e.g. on mouse up). | |
* | |
* @event Hooks#afterSelectionEnd | |
* @param {Number} row Selection start visual row index. | |
* @param {Number} column Selection start visual column index. | |
* @param {Number} row2 Selection end visual row index. | |
* @param {Number} column2 Selection end visual column index. | |
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified. | |
*/ | |
'afterSelectionEnd', | |
/** | |
* Fired after one or more cells are selected (e.g. on mouse up). | |
* | |
* The `prop` and `prop2` arguments represent the source object property name instead of the column number. | |
* | |
* @event Hooks#afterSelectionEndByProp | |
* @param {Number} row Selection start visual row index. | |
* @param {String} prop Selection start data source object property index. | |
* @param {Number} row2 Selection end visual row index. | |
* @param {String} prop2 Selection end data source object property index. | |
* @param {Number} selectionLayerLevel The number which indicates what selection layer is currently modified. | |
*/ | |
'afterSelectionEndByProp', | |
/** | |
* Fired after cell meta is changed. | |
* | |
* @event Hooks#afterSetCellMeta | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {String} key The updated meta key. | |
* @param {*} value The updated meta value. | |
*/ | |
'afterSetCellMeta', | |
/** | |
* Fired after cell meta is removed. | |
* | |
* @event Hooks#afterRemoveCellMeta | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {String} key The removed meta key. | |
* @param {*} value Value which was under removed key of cell meta. | |
*/ | |
'afterRemoveCellMeta', | |
/** | |
* Fired after cell data was changed. | |
* | |
* @event Hooks#afterSetDataAtCell | |
* @param {Array} changes An array of changes in format `[[row, column, oldValue, value], ...]`. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterSetDataAtCell', | |
/** | |
* Fired after cell data was changed. | |
* | |
* @event Hooks#afterSetDataAtRowProp | |
* @param {Array} changes An array of changes in format `[[row, prop, oldValue, value], ...]`. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterSetDataAtRowProp', | |
/** | |
* Fired after calling the `updateSettings` method. | |
* | |
* @event Hooks#afterUpdateSettings | |
* @param {Object} newSettings New settings object. | |
*/ | |
'afterUpdateSettings', | |
/** | |
* @description | |
* A plugin hook executed after validator function, only if validator function is defined. | |
* Validation result is the first parameter. This can be used to determinate if validation passed successfully or not. | |
* | |
* __Returning false from the callback will mark the cell as invalid.__ | |
* | |
* @event Hooks#afterValidate | |
* @param {Boolean} isValid `true` if valid, `false` if not. | |
* @param {*} value The value in question. | |
* @param {Number} row Visual row index. | |
* @param {String|Number} prop Property name / visual column index. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'afterValidate', | |
/** | |
* Fired before successful change of language (when proper language code was set) | |
* | |
* @event Hooks#beforeLanguageChange | |
* @since 0.35.0 | |
* @param {String} languageCode New language code. | |
*/ | |
'beforeLanguageChange', | |
/** | |
* Fired after successful change of language (when proper language code was set). | |
* | |
* @event Hooks#afterLanguageChange | |
* @since 0.35.0 | |
* @param {String} languageCode New language code. | |
*/ | |
'afterLanguageChange', | |
/** | |
* Fired by {@link Autofill} plugin before populating the data in the autofill feature. This hook is fired when | |
* {@link Options#fillHandle} option is enabled. | |
* | |
* @event Hooks#beforeAutofill | |
* @param {CellCoords} start Object containing information about first filled cell: `{row: 2, col: 0}`. | |
* @param {CellCoords} end Object containing information about last filled cell: `{row: 4, col: 1}`. | |
* @param {Array[]} data 2D array containing information about fill pattern: `[["1", "Ted"], ["1", "John"]]`. | |
*/ | |
'beforeAutofill', | |
/** | |
* Fired before aligning the cell contents. | |
* | |
* @event Hooks#beforeCellAlignment | |
* @param {Object} stateBefore An object with class names defining the cell alignment. | |
* @param {CellRange[]} range An array of CellRange coordinates where the alignment will be applied. | |
* @param {String} type Type of the alignment - either `horizontal` or `vertical`. | |
* @param {String} alignmentClass String defining the alignment class added to the cell. | |
* Possible values: | |
* * `htLeft` | |
* * `htCenter` | |
* * `htRight` | |
* * `htJustify` | |
* * `htTop` | |
* * `htMiddle` | |
* * `htBottom` | |
*/ | |
'beforeCellAlignment', | |
/** | |
* Fired before one or more cells is changed. Its main purpose is to alter changes silently after input and before | |
* table rendering. | |
* | |
* @event Hooks#beforeChange | |
* @param {Array[]} changes 2D array containing information about each of the edited cells. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
* @example | |
* ```js | |
* // To disregard a single change, set changes[i] to null or remove it from array using changes.splice(i, 1). | |
* new Handsontable(element, { | |
* beforeChange: (changes, source) => { | |
* // [[row, prop, oldVal, newVal], ...] | |
* changes[0] = null; | |
* } | |
* }); | |
* // To alter a single change, overwrite the desired value to changes[i][3]. | |
* new Handsontable(element, { | |
* beforeChange: (changes, source) => { | |
* // [[row, prop, oldVal, newVal], ...] | |
* changes[0][3] = 10; | |
* } | |
* }); | |
* // To cancel all edit, return false from the callback or set array length to 0 (changes.length = 0). | |
* new Handsontable(element, { | |
* beforeChange: (changes, source) => { | |
* // [[row, prop, oldVal, newVal], ...] | |
* return false; | |
* } | |
* }); | |
* ``` | |
*/ | |
'beforeChange', | |
/** | |
* Fired right before rendering the changes. | |
* | |
* @event Hooks#beforeChangeRender | |
* @param {Array[]} changes Array in form of `[row, prop, oldValue, newValue]`. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'beforeChangeRender', | |
/** | |
* Fired before drawing the borders. | |
* | |
* @event Hooks#beforeDrawBorders | |
* @param {Array} corners Array specifying the current selection borders. | |
* @param {String} borderClassName Specifies the border class name. | |
*/ | |
'beforeDrawBorders', | |
/** | |
* Fired before getting cell settings. | |
* | |
* @event Hooks#beforeGetCellMeta | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {Object} cellProperties Object containing the cell's properties. | |
*/ | |
'beforeGetCellMeta', | |
/** | |
* Fired before cell meta is removed. | |
* | |
* @event Hooks#beforeRemoveCellMeta | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {String} key The removed meta key. | |
* @param {*} value Value which is under removed key of cell meta. | |
*/ | |
'beforeRemoveCellMeta', | |
/** | |
* Fired before the Handsontable instance is initiated. | |
* | |
* @event Hooks#beforeInit | |
*/ | |
'beforeInit', | |
/** | |
* Fired before the Walkontable instance is initiated. | |
* | |
* @event Hooks#beforeInitWalkontable | |
* @param {Object} walkontableConfig Walkontable configuration object. | |
*/ | |
'beforeInitWalkontable', | |
/** | |
* Fired before new data is loaded (by `loadData` or `updateSettings` method) into the data source array. | |
* | |
* @event Hooks#beforeLoadData | |
* @param {Array} sourceData Array of arrays or array of objects containing data. | |
* @param {Boolean} initialLoad flag that determines whether the data has been loaded during the initialization. | |
*/ | |
'beforeLoadData', | |
/** | |
* Fired before keydown event is handled. It can be used to overwrite default key bindings. | |
* | |
* __Note__: To prevent default behavior you need to call `event.stopImmediatePropagation()` in your `beforeKeyDown` | |
* handler. | |
* | |
* @event Hooks#beforeKeyDown | |
* @param {Event} event Original DOM event. | |
*/ | |
'beforeKeyDown', | |
/** | |
* Fired after the user clicked a cell, but before all the calculations related with it. | |
* | |
* @event Hooks#beforeOnCellMouseDown | |
* @param {Event} event The `mousedown` event object. | |
* @param {CellCoords} coords Cell coords object containing the visual coordinates of the clicked cell. | |
* @param {HTMLTableCellElement} TD TD element. | |
* @param {Object} controller An object with keys `row`, `column` and `cells` which contains boolean values. This | |
* object allows or disallows changing the selection for the particular axies. | |
*/ | |
'beforeOnCellMouseDown', | |
/** | |
* Fired after the user clicked a cell. | |
* | |
* @event Hooks#beforeOnCellMouseUp | |
* @param {Event} event The `mouseup` event object. | |
* @param {CellCoords} coords Cell coords object containing the visual coordinates of the clicked cell. | |
* @param {HTMLTableCellElement} TD TD element. | |
* @param {Object} controller An object with keys `row`, `column` and `cells` which contains boolean values. This | |
* object allows or disallows changing the selection for the particular axies. | |
*/ | |
'beforeOnCellMouseUp', | |
/** | |
* Fired after the user clicked a cell, but before all the calculations related with it. | |
* | |
* @event Hooks#beforeOnCellContextMenu | |
* @since 4.1.0 | |
* @param {Event} event The `contextmenu` event object. | |
* @param {CellCoords} coords Cell coords object containing the visual coordinates of the clicked cell. | |
* @param {HTMLTableCellElement} TD TD element. | |
*/ | |
'beforeOnCellContextMenu', | |
/** | |
* Fired after the user moved cursor over a cell, but before all the calculations related with it. | |
* | |
* @event Hooks#beforeOnCellMouseOver | |
* @param {Event} event The `mouseover` event object. | |
* @param {CellCoords} coords CellCoords object containing the visual coordinates of the clicked cell. | |
* @param {HTMLTableCellElement} TD TD element. | |
* @param {Object} controller An object with keys `row`, `column` and `cells` which contains boolean values. This | |
* object allows or disallows changing the selection for the particular axies. | |
*/ | |
'beforeOnCellMouseOver', | |
/** | |
* Fired after the user moved cursor out from a cell, but before all the calculations related with it. | |
* | |
* @event Hooks#beforeOnCellMouseOut | |
* @param {Event} event The `mouseout` event object. | |
* @param {CellCoords} coords CellCoords object containing the visual coordinates of the leaved cell. | |
* @param {HTMLTableCellElement} TD TD element. | |
*/ | |
'beforeOnCellMouseOut', | |
/** | |
* Fired before one or more columns are about to be removed. | |
* | |
* @event Hooks#beforeRemoveCol | |
* @param {Number} index Visual index of starter column. | |
* @param {Number} amount Amount of columns to be removed. | |
* @param {Number[]} physicalColumns An array of physical columns removed from the data source. | |
* @param {String} [source] String that identifies source of hook call ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'beforeRemoveCol', | |
/** | |
* Fired when one or more rows are about to be removed. | |
* | |
* @event Hooks#beforeRemoveRow | |
* @param {Number} index Visual index of starter row. | |
* @param {Number} amount Amount of rows to be removed. | |
* @param {Number[]} physicalRows An array of physical rows removed from the data source. | |
* @param {String} [source] String that identifies source of hook call ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'beforeRemoveRow', | |
/** | |
* Fired before the Handsontable table is rendered. | |
* | |
* @event Hooks#beforeRender | |
* @param {Boolean} isForced If `true` rendering was triggered by a change of settings or data; or `false` if | |
* rendering was triggered by scrolling or moving selection. | |
*/ | |
'beforeRender', | |
/** | |
* Fired before setting range is started but not finished yet. | |
* | |
* @event Hooks#beforeSetRangeStartOnly | |
* @param {CellCoords} coords CellCoords instance. | |
*/ | |
'beforeSetRangeStartOnly', | |
/** | |
* Fired before setting range is started. | |
* | |
* @event Hooks#beforeSetRangeStart | |
* @param {CellCoords} coords CellCoords instance. | |
*/ | |
'beforeSetRangeStart', | |
/** | |
* Fired before setting range is ended. | |
* | |
* @event Hooks#beforeSetRangeEnd | |
* @param {CellCoords} coords CellCoords instance. | |
*/ | |
'beforeSetRangeEnd', | |
/** | |
* Fired before the logic of handling a touch scroll, when user started scrolling on a touch-enabled device. | |
* | |
* @event Hooks#beforeTouchScroll | |
*/ | |
'beforeTouchScroll', | |
/** | |
* Fired before cell validation, only if validator function is defined. This can be used to manipulate the value | |
* of changed cell before it is applied to the validator function. | |
* | |
* __Note:__ this will not affect values of changes. This will change value *ONLY* for validation | |
* | |
* @event Hooks#beforeValidate | |
* @param {*} value Value of the cell. | |
* @param {Number} row Visual row index. | |
* @param {String|Number} prop Property name / column index. | |
* @param {String} [source] String that identifies source of hook call | |
* ([list of all available sources]{@link https://handsontable.com/docs/tutorial-using-callbacks.html#page-source-definition}). | |
*/ | |
'beforeValidate', | |
/** | |
* Fired before cell value is rendered into the DOM (through renderer function). This can be used to manipulate the | |
* value which is passed to the renderer without modifying the renderer itself. | |
* | |
* @event Hooks#beforeValueRender | |
* @param {*} value Cell value to render. | |
* @param {Object} cellProperties An object containing the cell properties. | |
*/ | |
'beforeValueRender', | |
/** | |
* Fired after Handsontable instance is constructed (using `new` operator). | |
* | |
* @event Hooks#construct | |
*/ | |
'construct', | |
/** | |
* Fired after Handsontable instance is initiated but before table is rendered. | |
* | |
* @event Hooks#init | |
*/ | |
'init', | |
/** | |
* Fired when a column header index is about to be modified by a callback function. | |
* | |
* @event Hooks#modifyColHeader | |
* @param {Number} column Visual column header index. | |
*/ | |
'modifyColHeader', | |
/** | |
* Fired when a column width is about to be modified by a callback function. | |
* | |
* @event Hooks#modifyColWidth | |
* @param {Number} width Current column width. | |
* @param {Number} column Visual column index. | |
*/ | |
'modifyColWidth', | |
/** | |
* Fired when a row header index is about to be modified by a callback function. | |
* | |
* @event Hooks#modifyRowHeader | |
* @param {Number} row Visual row header index. | |
*/ | |
'modifyRowHeader', | |
/** | |
* Fired when a row height is about to be modified by a callback function. | |
* | |
* @event Hooks#modifyRowHeight | |
* @param {Number} height Row height. | |
* @param {Number} row Visual row index. | |
*/ | |
'modifyRowHeight', | |
/** | |
* Fired when a data was retrieved or modified. | |
* | |
* @event Hooks#modifyData | |
* @param {Number} row Row height. | |
* @param {Number} column Column index. | |
* @param {Object} valueHolder Object which contains original value which can be modified by overwriting `.value` property. | |
* @param {String} ioMode String which indicates for what operation hook is fired (`get` or `set`). | |
*/ | |
'modifyData', | |
/** | |
* Fired when a data was retrieved or modified. | |
* | |
* @event Hooks#modifyRowData | |
* @param {Number} row Physical row index. | |
*/ | |
'modifyRowData', | |
/** | |
* Used to modify the cell coordinates when using the `getCell` method. | |
* | |
* @event Hooks#modifyGetCellCoords | |
* @since 0.36.0 | |
* @param {Number} row Visual row index. | |
* @param {Number} column Visual column index. | |
* @param {Boolean} topmost If set to `true`, it returns the TD element from the topmost overlay. For example, | |
* if the wanted cell is in the range of fixed rows, it will return a TD element | |
* from the `top` overlay. | |
*/ | |
'modifyGetCellCoords', | |
/** | |
* Fired by {@link PersistentState} plugin, after loading value, saved under given key, from browser local storage. This hook is fired when | |
* {@link Options#persistentState} option is enabled. | |
* | |
* @event Hooks#persistentStateLoad | |
* @param {String} key Key. | |
* @param {Object} valuePlaceholder Object containing the loaded value under `valuePlaceholder.value` (if no value have been saved, `value` key will be undefined). | |
*/ | |
'persistentStateLoad', | |
/** | |
* Fired by {@link PersistentState} plugin after resetting data from local storage. If no key is given, all values associated with table will be cleared. | |
* This hook is fired when {@link Options#persistentState} option is enabled. | |
* | |
* @event Hooks#persistentStateReset | |
* @param {String} [key] Key. | |
*/ | |
'persistentStateReset', | |
/** | |
* Fired by {@link PersistentState} plugin, after saving value under given key in browser local storage. This hook is fired when | |
* {@link Options#persistentState} option is enabled. | |
* | |
* @event Hooks#persistentStateSave | |
* @param {String} key Key. | |
* @param {Mixed} value Value to save. | |
*/ | |
'persistentStateSave', | |
/** | |
* Fired by {@link ColumnSorting} and {@link MultiColumnSorting} plugins before sorting the column. If you return `false` value inside callback for hook, then sorting | |
* will be not applied by the Handsontable (useful for server-side sorting). | |
* | |
* This hook is fired when {@link Options#columnSorting} or {@link Options#multiColumnSorting} option is enabled. | |
* | |
* @event Hooks#beforeColumnSort | |
* @param {Array} currentSortConfig Current sort configuration (for all sorted columns). | |
* @param {Array} destinationSortConfigs Destination sort configuration (for all sorted columns). | |
*/ | |
'beforeColumnSort', | |
/** | |
* Fired by {@link ColumnSorting} and {@link MultiColumnSorting} plugins after sorting the column. This hook is fired when {@link Options#columnSorting} | |
* or {@link Options#multiColumnSorting} option is enabled. | |
* | |
* @event Hooks#afterColumnSort | |
* @param {Array} currentSortConfig Current sort configuration (for all sorted columns). | |
* @param {Array} destinationSortConfigs Destination sort configuration (for all sorted columns). | |
*/ | |
'afterColumnSort', | |
/** | |
* Fired by {@link Autofill} plugin after setting range of autofill. This hook is fired when {@link Options#fillHandle} | |
* option is enabled. | |
* | |
* @event Hooks#modifyAutofillRange | |
* @param {Array} startArea Array of visual coordinates of the starting point for the drag-down operation (`[startRow, startColumn, endRow, endColumn]`). | |
* @param {Array} entireArea Array of visual coordinates of the entire area of the drag-down operation (`[startRow, startColumn, endRow, endColumn]`). | |
*/ | |
'modifyAutofillRange', | |
/** | |
* Fired to allow modifying the copyable range with a callback function. | |
* | |
* @event Hooks#modifyCopyableRange | |
* @param {Array[]} copyableRanges Array of objects defining copyable cells. | |
*/ | |
'modifyCopyableRange', | |
/** | |
* Fired by {@link CopyPaste} plugin before copying the values into clipboard and before clearing values of | |
* the selected cells. This hook is fired when {@link Options#copyPaste} option is enabled. | |
* | |
* @event Hooks#beforeCut | |
* @param {Array[]} data An array of arrays which contains data to cut. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* which will be cut out. | |
* @returns {*} If returns `false` then operation of the cutting out is canceled. | |
* @example | |
* ```js | |
* // To disregard a single row, remove it from the array using data.splice(i, 1). | |
* new Handsontable(element, { | |
* beforeCut: function(data, coords) { | |
* // data -> [[1, 2, 3], [4, 5, 6]] | |
* data.splice(0, 1); | |
* // data -> [[4, 5, 6]] | |
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}] | |
* } | |
* }); | |
* // To cancel a cutting action, just return `false`. | |
* new Handsontable(element, { | |
* beforeCut: function(data, coords) { | |
* return false; | |
* } | |
* }); | |
* ``` | |
*/ | |
'beforeCut', | |
/** | |
* Fired by {@link CopyPaste} plugin after data was cut out from the table. This hook is fired when | |
* {@link Options#copyPaste} option is enabled. | |
* | |
* @event Hooks#afterCut | |
* @param {Array[]} data An array of arrays which contains the cutted out data. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* which was cut out. | |
*/ | |
'afterCut', | |
/** | |
* Fired before values are copied into clipboard. | |
* | |
* @event Hooks#beforeCopy | |
* @param {Array[]} data An array of arrays which contains data to copied. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* which will copied. | |
* @returns {*} If returns `false` then copying is canceled. | |
* | |
* @example | |
* ```js | |
* // To disregard a single row, remove it from array using data.splice(i, 1). | |
* ... | |
* new Handsontable(document.getElementById('example'), { | |
* beforeCopy: (data, coords) => { | |
* // data -> [[1, 2, 3], [4, 5, 6]] | |
* data.splice(0, 1); | |
* // data -> [[4, 5, 6]] | |
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}] | |
* } | |
* }); | |
* ... | |
* | |
* // To cancel copying, return false from the callback. | |
* ... | |
* new Handsontable(document.getElementById('example'), { | |
* beforeCopy: (data, coords) => { | |
* return false; | |
* } | |
* }); | |
* ... | |
* ``` | |
*/ | |
'beforeCopy', | |
/** | |
* Fired by {@link CopyPaste} plugin after data are pasted into table. This hook is fired when {@link Options#copyPaste} | |
* option is enabled. | |
* | |
* @event Hooks#afterCopy | |
* @param {Array[]} data An array of arrays which contains the copied data. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* which was copied. | |
*/ | |
'afterCopy', | |
/** | |
* Fired by {@link CopyPaste} plugin before values are pasted into table. This hook is fired when | |
* {@link Options#copyPaste} option is enabled. | |
* | |
* @event Hooks#beforePaste | |
* @param {Array[]} data An array of arrays which contains data to paste. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* that correspond to the previously selected area. | |
* @returns {*} If returns `false` then pasting is canceled. | |
* @example | |
* ```js | |
* // To disregard a single row, remove it from array using data.splice(i, 1). | |
* new Handsontable(example, { | |
* beforePaste: (data, coords) => { | |
* // data -> [[1, 2, 3], [4, 5, 6]] | |
* data.splice(0, 1); | |
* // data -> [[4, 5, 6]] | |
* // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}] | |
* } | |
* }); | |
* // To cancel pasting, return false from the callback. | |
* new Handsontable(example, { | |
* beforePaste: (data, coords) => { | |
* return false; | |
* } | |
* }); | |
* ``` | |
*/ | |
'beforePaste', | |
/** | |
* Fired by {@link CopyPaste} plugin after values are pasted into table. This hook is fired when | |
* {@link Options#copyPaste} option is enabled. | |
* | |
* @event Hooks#afterPaste | |
* @param {Array[]} data An array of arrays which contains the pasted data. | |
* @param {Object[]} coords An array of objects with ranges of the visual indexes (`startRow`, `startCol`, `endRow`, `endCol`) | |
* that correspond to the previously selected area. | |
*/ | |
'afterPaste', | |
/** | |
* Fired by {@link ManualColumnMove} plugin before change order of the visual indexes. This hook is fired when | |
* {@link Options#manualColumnMove} option is enabled. | |
* | |
* @event Hooks#beforeColumnMove | |
* @param {Number[]} columns Array of visual column indexes to be moved. | |
* @param {Number} target Visual column index being a target for moved columns. | |
*/ | |
'beforeColumnMove', | |
/** | |
* Fired by {@link ManualColumnMove} plugin after changing order of the visual indexes. This hook is fired when | |
* {@link Options#manualColumnMove} option is enabled. | |
* | |
* @event Hooks#afterColumnMove | |
* @param {Number[]} columns Array of visual column indexes that were moved. | |
* @param {Number} target Visual column index being a target for moved columns. | |
*/ | |
'afterColumnMove', | |
/** | |
* Fired by {@link ManualRowMove} plugin before changing the order of the visual indexes. This hook is fired when | |
* {@link Options#manualRowMove} option is enabled. | |
* | |
* @event Hooks#beforeRowMove | |
* @param {Array} movedRows Array of visual row indexes to be moved. | |
* @param {Number} finalIndex Visual row index, being a start index for the moved rows. Points to where the elements will be placed after the moving action. To check visualization of final index please take a look at [documentation](/demo-moving.html#manualRowMove). | |
* @param {Number|undefined} dropIndex Visual row index, being a drop index for the moved rows. Points to where we are going to drop the moved elements. To check visualization of drop index please take a look at [documentation](/demo-moving.html#manualRowMove). It's `undefined` when `dragRows` function wasn't called. | |
* @param {Boolean} movePossible Indicates if it's possible to move rows to the desired position. | |
*/ | |
'beforeRowMove', | |
/** | |
* Fired by {@link ManualRowMove} plugin after changing the order of the visual indexes. This hook is fired when | |
* {@link Options#manualRowMove} option is enabled. | |
* | |
* @event Hooks#afterRowMove | |
* @param {Array} movedRows Array of visual row indexes to be moved. | |
* @param {Number} finalIndex Visual row index, being a start index for the moved rows. Points to where the elements will be placed after the moving action. To check visualization of final index please take a look at [documentation](/demo-moving.html#manualRowMove). | |
* @param {Number|undefined} dropIndex Visual row index, being a drop index for the moved rows. Points to where we are going to drop the moved elements. To check visualization of drop index please take a look at [documentation](/demo-moving.html#manualRowMove). It's `undefined` when `dragRows` function wasn't called. | |
* @param {Boolean} movePossible Indicates if it was possible to move rows to the desired position. | |
* @param {Boolean} orderChanged Indicates if order of rows was changed by move. | |
*/ | |
'afterRowMove', | |
/** | |
* Fired by {@link ManualColumnResize} plugin before rendering the table with modified column sizes. This hook is | |
* fired when {@link Options#manualColumnResize} option is enabled. | |
* | |
* @event Hooks#beforeColumnResize | |
* @param {Number} newSize Calculated new column width. | |
* @param {Number} column Visual index of the resized column. | |
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click. | |
* @returns {Number} Returns a new column size or `undefined`, if column size should be calculated automatically. | |
*/ | |
'beforeColumnResize', | |
/** | |
* Fired by {@link ManualColumnResize} plugin after rendering the table with modified column sizes. This hook is | |
* fired when {@link Options#manualColumnResize} option is enabled. | |
* | |
* @event Hooks#afterColumnResize | |
* @param {Number} newSize Calculated new column width. | |
* @param {Number} column Visual index of the resized column. | |
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click. | |
*/ | |
'afterColumnResize', | |
/** | |
* Fired by {@link ManualRowResize} plugin before rendering the table with modified row sizes. This hook is | |
* fired when {@link Options#manualRowResize} option is enabled. | |
* | |
* @event Hooks#beforeRowResize | |
* @param {Number} newSize Calculated new row height. | |
* @param {Number} row Visual index of the resized row. | |
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click. | |
* @returns {Number} Returns the new row size or `undefined` if row size should be calculated automatically. | |
*/ | |
'beforeRowResize', | |
/** | |
* Fired by {@link ManualRowResize} plugin after rendering the table with modified row sizes. This hook is | |
* fired when {@link Options#manualRowResize} option is enabled. | |
* | |
* @event Hooks#afterRowResize | |
* @param {Number} newSize Calculated new row height. | |
* @param {Number} row Visual index of the resized row. | |
* @param {Boolean} isDoubleClick Flag that determines whether there was a double-click. | |
*/ | |
'afterRowResize', | |
/** | |
* Fired after getting the column header renderers. | |
* | |
* @event Hooks#afterGetColumnHeaderRenderers | |
* @param {Function[]} renderers An array of the column header renderers. | |
*/ | |
'afterGetColumnHeaderRenderers', | |
/** | |
* Fired after getting the row header renderers. | |
* | |
* @event Hooks#afterGetRowHeaderRenderers | |
* @param {Function[]} renderers An array of the row header renderers. | |
*/ | |
'afterGetRowHeaderRenderers', | |
/** | |
* Fired before applying stretched column width to column. | |
* | |
* @event Hooks#beforeStretchingColumnWidth | |
* @param {Number} stretchedWidth Calculated width. | |
* @param {Number} column Visual column index. | |
* @returns {Number} Returns new width which will be applied to the column element. | |
*/ | |
'beforeStretchingColumnWidth', | |
/** | |
* Fired by {@link Filters} plugin before applying [filtering]{@link https://handsontable.com/docs/demo-filtering.html}. This hook is fired when | |
* {@link Options#filters} option is enabled. | |
* | |
* @event Hooks#beforeFilter | |
* @param {Object[]} conditionsStack An array of objects with added formulas. | |
* ```js | |
* // Example format of the conditionsStack argument: | |
* [ | |
* { | |
* column: 2, | |
* conditions: [ | |
* {name: 'begins_with', args: [['S']]} | |
* ], | |
* operation: 'conjunction' | |
* }, | |
* { | |
* column: 4, | |
* conditions: [ | |
* {name: 'not_empty', args: []} | |
* ], | |
* operation: 'conjunction' | |
* }, | |
* ] | |
* ``` | |
* @returns {Boolean} If hook returns `false` value then filtering won't be applied on the UI side (server-side filtering). | |
*/ | |
'beforeFilter', | |
/** | |
* Fired by {@link Filters} plugin after applying [filtering]{@link https://handsontable.com/docs/demo-filtering.html}. This hook is fired when | |
* {@link Options#filters} option is enabled. | |
* | |
* @event Hooks#afterFilter | |
* @param {Object[]} conditionsStack An array of objects with added conditions. | |
* ```js | |
* // Example format of the conditionsStack argument: | |
* [ | |
* { | |
* column: 2, | |
* conditions: [ | |
* {name: 'begins_with', args: [['S']]} | |
* ], | |
* operation: 'conjunction' | |
* }, | |
* { | |
* column: 4, | |
* conditions: [ | |
* {name: 'not_empty', args: []} | |
* ], | |
* operation: 'conjunction' | |
* }, | |
* ] | |
* ``` | |
*/ | |
'afterFilter', | |
/** | |
* Fired while retrieving the column header height. | |
* | |
* @event Hooks#modifyColumnHeaderHeight | |
*/ | |
'modifyColumnHeaderHeight', | |
/** | |
* Fired by {@link UndoRedo} plugin before the undo action. Contains information about the action that is being undone. | |
* This hook is fired when {@link Options#undo} option is enabled. | |
* | |
* @event Hooks#beforeUndo | |
* @param {Object} action The action object. Contains information about the action being undone. The `actionType` | |
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`). | |
*/ | |
'beforeUndo', | |
/** | |
* Fired by {@link UndoRedo} plugin after the undo action. Contains information about the action that is being undone. | |
* This hook is fired when {@link Options#undo} option is enabled. | |
* | |
* @event Hooks#afterUndo | |
* @param {Object} action The action object. Contains information about the action being undone. The `actionType` | |
* property of the object specifies the type of the action in a String format. (e.g. `'remove_row'`). | |
*/ | |
'afterUndo', | |
/** | |
* Fired by {@link UndoRedo} plugin before the redo action. Contains information about the action that is being redone. | |
* This hook is fired when {@link Options#undo} option is enabled. | |
* | |
* @event Hooks#beforeRedo | |
* @param {Object} action The action object. Contains information about the action being redone. The `actionType` | |
* property of the object specifies the type of the action in a String format (e.g. `'remove_row'`). | |
*/ | |
'beforeRedo', | |
/** | |
* Fired by {@link UndoRedo} plugin after the redo action. Contains information about the action that is being redone. | |
* This hook is fired when {@link Options#undo} option is enabled. | |
* | |
* @event Hooks#afterRedo | |
* @param {Object} action The action object. Contains information about the action being redone. The `actionType` | |
* property of the object specifies the type of the action in a String format (e.g. `'remove_row'`). | |
*/ | |
'afterRedo', | |
/** | |
* Fired while retrieving the row header width. | |
* | |
* @event Hooks#modifyRowHeaderWidth | |
* @param {Number} rowHeaderWidth Row header width. | |
*/ | |
'modifyRowHeaderWidth', | |
/** | |
* Fired from the `populateFromArray` method during the `autofill` process. Fired for each "autofilled" cell individually. | |
* | |
* @event Hooks#beforeAutofillInsidePopulate | |
* @param {Object} index Object containing `row` and `col` properties, defining the number of rows/columns from the initial cell of the autofill. | |
* @param {String} direction Declares the direction of the autofill. Possible values: `up`, `down`, `left`, `right`. | |
* @param {Array[]} input Contains an array of rows with data being used in the autofill. | |
* @param {Array} deltas The deltas array passed to the `populateFromArray` method. | |
*/ | |
'beforeAutofillInsidePopulate', | |
/** | |
* Fired when the start of the selection is being modified (e.g. moving the selection with the arrow keys). | |
* | |
* @event Hooks#modifyTransformStart | |
* @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one. | |
*/ | |
'modifyTransformStart', | |
/** | |
* Fired when the end of the selection is being modified (e.g. moving the selection with the arrow keys). | |
* | |
* @event Hooks#modifyTransformEnd | |
* @param {CellCoords} delta Cell coords object declaring the delta of the new selection relative to the previous one. | |
*/ | |
'modifyTransformEnd', | |
/** | |
* Fired after the start of the selection is being modified (e.g. moving the selection with the arrow keys). | |
* | |
* @event Hooks#afterModifyTransformStart | |
* @param {CellCoords} coords Coords of the freshly selected cell. | |
* @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise. | |
* @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise. | |
*/ | |
'afterModifyTransformStart', | |
/** | |
* Fired after the end of the selection is being modified (e.g. moving the selection with the arrow keys). | |
* | |
* @event Hooks#afterModifyTransformEnd | |
* @param {CellCoords} coords Visual coords of the freshly selected cell. | |
* @param {Number} rowTransformDir `-1` if trying to select a cell with a negative row index. `0` otherwise. | |
* @param {Number} colTransformDir `-1` if trying to select a cell with a negative column index. `0` otherwise. | |
*/ | |
'afterModifyTransformEnd', | |
/** | |
* Fired inside the `viewportRowCalculatorOverride` method. Allows modifying the row calculator parameters. | |
* | |
* @event Hooks#afterViewportRowCalculatorOverride | |
* @param {Object} calc The row calculator. | |
*/ | |
'afterViewportRowCalculatorOverride', | |
/** | |
* Fired inside the `viewportColumnCalculatorOverride` method. Allows modifying the row calculator parameters. | |
* | |
* @event Hooks#afterViewportColumnCalculatorOverride | |
* @param {Object} calc The row calculator. | |
*/ | |
'afterViewportColumnCalculatorOverride', | |
/** | |
* Fired after initializing all the plugins. | |
* | |
* @event Hooks#afterPluginsInitialized | |
*/ | |
'afterPluginsInitialized', | |
/** | |
* Fired by {@link HiddenRows} plugin before marking the rows as hidden. Fired only if the {@link Options#hiddenRows} option is enabled. | |
* Returning `false` in the callback will prevent the hiding action from completing. | |
* | |
* @event Hooks#beforeHideRows | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical row indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical row indexes. | |
* @param {Boolean} actionPossible `true`, if provided row indexes are valid, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the hiding action will not be completed. | |
*/ | |
'beforeHideRows', | |
/** | |
* Fired by {@link HiddenRows} plugin after marking the rows as hidden. Fired only if the {@link Options#hiddenRows} option is enabled. | |
* | |
* @event Hooks#afterHideRows | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical row indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical row indexes. | |
* @param {Boolean} actionPossible `true`, if provided row indexes are valid, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any non-hidden rows, `false` otherwise. | |
*/ | |
'afterHideRows', | |
/** | |
* Fired by {@link HiddenRows} plugin before marking the rows as not hidden. Fired only if the {@link Options#hiddenRows} option is enabled. | |
* Returning `false` in the callback will prevent the row revealing action from completing. | |
* | |
* @event Hooks#beforeUnhideRows | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical row indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical row indexes. | |
* @param {Boolean} actionPossible `true`, if provided row indexes are valid, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the revealing action will not be completed. | |
*/ | |
'beforeUnhideRows', | |
/** | |
* Fired by {@link HiddenRows} plugin after marking the rows as not hidden. Fired only if the {@link Options#hiddenRows} option is enabled. | |
* | |
* @event Hooks#afterUnhideRows | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical row indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical row indexes. | |
* @param {Boolean} actionPossible `true`, if provided row indexes are valid, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any hidden rows, `false` otherwise. | |
*/ | |
'afterUnhideRows', | |
/** | |
* Fired by {@link HiddenColumns} plugin before marking the columns as hidden. Fired only if the {@link Options#hiddenColumns} option is enabled. | |
* Returning `false` in the callback will prevent the hiding action from completing. | |
* | |
* @event Hooks#beforeHideColumns | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical column indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical column indexes. | |
* @param {Boolean} actionPossible `true`, if the provided column indexes are valid, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the hiding action will not be completed. | |
*/ | |
'beforeHideColumns', | |
/** | |
* Fired by {@link HiddenColumns} plugin after marking the columns as hidden. Fired only if the {@link Options#hiddenColumns} option is enabled. | |
* | |
* @event Hooks#afterHideColumns | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical column indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical column indexes. | |
* @param {Boolean} actionPossible `true`, if the provided column indexes are valid, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any non-hidden columns, `false` otherwise. | |
*/ | |
'afterHideColumns', | |
/** | |
* Fired by {@link HiddenColumns} plugin before marking the columns as not hidden. Fired only if the {@link Options#hiddenColumns} option is enabled. | |
* Returning `false` in the callback will prevent the column revealing action from completing. | |
* | |
* @event Hooks#beforeUnhideColumns | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical column indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical column indexes. | |
* @param {Boolean} actionPossible `true`, if the provided column indexes are valid, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the hiding action will not be completed. | |
*/ | |
'beforeUnhideColumns', | |
/** | |
* Fired by {@link HiddenColumns} plugin after marking the columns as not hidden. Fired only if the {@link Options#hiddenColumns} option is enabled. | |
* | |
* @event Hooks#afterUnhideColumns | |
* @param {Array} currentHideConfig Current hide configuration - a list of hidden physical column indexes. | |
* @param {Array} destinationHideConfig Destination hide configuration - a list of hidden physical column indexes. | |
* @param {Boolean} actionPossible `true`, if the provided column indexes are valid, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any hidden columns, `false` otherwise. | |
*/ | |
'afterUnhideColumns', | |
/** | |
* Fired by {@link TrimRows} plugin before trimming rows. This hook is fired when {@link Options#trimRows} option is enabled. | |
* | |
* @event Hooks#beforeTrimRow | |
* @param {Array} currentTrimConfig Current trim configuration - a list of trimmed physical row indexes. | |
* @param {Array} destinationTrimConfig Destination trim configuration - a list of trimmed physical row indexes. | |
* @param {Boolean} actionPossible `true`, if all of the row indexes are withing the bounds of the table, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the trimming action will not be completed. | |
*/ | |
'beforeTrimRow', | |
/** | |
* Fired by {@link TrimRows} plugin after trimming rows. This hook is fired when {@link Options#trimRows} option is enabled. | |
* | |
* @event Hooks#afterTrimRow | |
* @param {Array} currentTrimConfig Current trim configuration - a list of trimmed physical row indexes. | |
* @param {Array} destinationTrimConfig Destination trim configuration - a list of trimmed physical row indexes. | |
* @param {Boolean} actionPossible `true`, if all of the row indexes are withing the bounds of the table, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any non-trimmed rows, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the trimming action will not be completed. | |
*/ | |
'afterTrimRow', | |
/** | |
* Fired by {@link TrimRows} plugin before untrimming rows. This hook is fired when {@link Options#trimRows} option is enabled. | |
* | |
* @event Hooks#beforeUntrimRow | |
* @param {Array} currentTrimConfig Current trim configuration - a list of trimmed physical row indexes. | |
* @param {Array} destinationTrimConfig Destination trim configuration - a list of trimmed physical row indexes. | |
* @param {Boolean} actionPossible `true`, if all of the row indexes are withing the bounds of the table, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the untrimming action will not be completed. | |
*/ | |
'beforeUntrimRow', | |
/** | |
* Fired by {@link TrimRows} plugin after untrimming rows. This hook is fired when {@link Options#trimRows} option is enabled. | |
* | |
* @event Hooks#afterUntrimRow | |
* @param {Array} currentTrimConfig Current trim configuration - a list of trimmed physical row indexes. | |
* @param {Array} destinationTrimConfig Destination trim configuration - a list of trimmed physical row indexes. | |
* @param {Boolean} actionPossible `true`, if all of the row indexes are withing the bounds of the table, `false` otherwise. | |
* @param {Boolean} stateChanged `true`, if the action affected any trimmed rows, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the untrimming action will not be completed. | |
*/ | |
'afterUntrimRow', | |
/** | |
* Fired by {@link DropdownMenu} plugin before opening the dropdown menu. This hook is fired when {@link Options#dropdownMenu} | |
* option is enabled. | |
* | |
* @event Hooks#beforeDropdownMenuShow | |
* @param {DropdownMenu} dropdownMenu The DropdownMenu instance. | |
*/ | |
'beforeDropdownMenuShow', | |
/** | |
* Fired by {@link DropdownMenu} plugin after opening the Dropdown Menu. This hook is fired when {@link Options#dropdownMenu} | |
* option is enabled. | |
* | |
* @event Hooks#afterDropdownMenuShow | |
* @param {DropdownMenu} dropdownMenu The DropdownMenu instance. | |
*/ | |
'afterDropdownMenuShow', | |
/** | |
* Fired by {@link DropdownMenu} plugin after hiding the Dropdown Menu. This hook is fired when {@link Options#dropdownMenu} | |
* option is enabled. | |
* | |
* @event Hooks#afterDropdownMenuHide | |
* @param {DropdownMenu} instance The DropdownMenu instance. | |
*/ | |
'afterDropdownMenuHide', | |
/** | |
* Fired by {@link HiddenRows} plugin to check whether the provided row index is hidden. This hook is fired when | |
* {@link Options#hiddenRows} option is enabled. | |
* | |
* @event Hooks#hiddenRow | |
* @param {Number} row The visual row index in question. | |
*/ | |
'hiddenRow', | |
/** | |
* Fired by {@link HiddenColumns} plugin to check whether the provided column index is hidden. This hook is fired when | |
* {@link Options#hiddenColumns} option is enabled. | |
* | |
* @event Hooks#hiddenColumn | |
* @param {Number} column The visual column index in question. | |
*/ | |
'hiddenColumn', | |
/** | |
* Fired by {@link NestedRows} plugin before adding a children to the NestedRows structure. This hook is fired when | |
* {@link Options#nestedRows} option is enabled. | |
* | |
* @event Hooks#beforeAddChild | |
* @param {Object} parent The parent object. | |
* @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added. | |
* @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child. | |
*/ | |
'beforeAddChild', | |
/** | |
* Fired by {@link NestedRows} plugin after adding a children to the NestedRows structure. This hook is fired when | |
* {@link Options#nestedRows} option is enabled. | |
* | |
* @event Hooks#afterAddChild | |
* @param {Object} parent The parent object. | |
* @param {Object|undefined} element The element added as a child. If `undefined`, a blank child was added. | |
* @param {Number|undefined} index The index within the parent where the new child was added. If `undefined`, the element was added as the last child. | |
*/ | |
'afterAddChild', | |
/** | |
* Fired by {@link NestedRows} plugin before detaching a child from its parent. This hook is fired when | |
* {@link Options#nestedRows} option is enabled. | |
* | |
* @event Hooks#beforeDetachChild | |
* @param {Object} parent An object representing the parent from which the element is to be detached. | |
* @param {Object} element The detached element. | |
*/ | |
'beforeDetachChild', | |
/** | |
* Fired by {@link NestedRows} plugin after detaching a child from its parent. This hook is fired when | |
* {@link Options#nestedRows} option is enabled. | |
* | |
* @event Hooks#afterDetachChild | |
* @param {Object} parent An object representing the parent from which the element was detached. | |
* @param {Object} element The detached element. | |
*/ | |
'afterDetachChild', | |
/** | |
* Fired after the editor is opened and rendered. | |
* | |
* @event Hooks#afterBeginEditing | |
* @param {Number} row Visual row index of the edited cell. | |
* @param {Number} column Visual column index of the edited cell. | |
*/ | |
'afterBeginEditing', | |
/** | |
* Fired by {@link MergeCells} plugin before cell merging. This hook is fired when {@link Options#mergeCells} | |
* option is enabled. | |
* | |
* @event Hooks#beforeMergeCells | |
* @param {CellRange} cellRange Selection cell range. | |
* @param {Boolean} [auto=false] `true` if called automatically by the plugin. | |
*/ | |
'beforeMergeCells', | |
/** | |
* Fired by {@link MergeCells} plugin after cell merging. This hook is fired when {@link Options#mergeCells} | |
* option is enabled. | |
* | |
* @event Hooks#afterMergeCells | |
* @param {CellRange} cellRange Selection cell range. | |
* @param {Object} mergeParent The parent collection of the provided cell range. | |
* @param {Boolean} [auto=false] `true` if called automatically by the plugin. | |
*/ | |
'afterMergeCells', | |
/** | |
* Fired by {@link MergeCells} plugin before unmerging the cells. This hook is fired when {@link Options#mergeCells} | |
* option is enabled. | |
* | |
* @event Hooks#beforeUnmergeCells | |
* @param {CellRange} cellRange Selection cell range. | |
* @param {Boolean} [auto=false] `true` if called automatically by the plugin. | |
*/ | |
'beforeUnmergeCells', | |
/** | |
* Fired by {@link MergeCells} plugin after unmerging the cells. This hook is fired when {@link Options#mergeCells} | |
* option is enabled. | |
* | |
* @event Hooks#afterUnmergeCells | |
* @param {CellRange} cellRange Selection cell range. | |
* @param {Boolean} [auto=false] `true` if called automatically by the plugin. | |
*/ | |
'afterUnmergeCells', | |
/** | |
* Fired after the table was switched into listening mode. This allows Handsontable to capture keyboard events and | |
* respond in the right way. | |
* | |
* @event Hooks#afterListen | |
*/ | |
'afterListen', | |
/** | |
* Fired after the table was switched off from the listening mode. This makes the Handsontable inert for any | |
* keyboard events. | |
* | |
* @event Hooks#afterUnlisten | |
*/ | |
'afterUnlisten', | |
/** | |
* Fired after the window was resized. | |
* | |
* @event Hooks#afterRefreshDimensions | |
* @param {Object} previousDimensions Previous dimensions of the container. | |
* @param {Object} currentDimensions Current dimensions of the container. | |
* @param {Boolean} stateChanged `true`, if the container was re-render, `false` otherwise. | |
*/ | |
'afterRefreshDimensions', | |
/** | |
* Cancellable hook, called after resizing a window, but before redrawing a table. | |
* | |
* @event Hooks#beforeRefreshDimensions | |
* @param {Object} previousDimensions Previous dimensions of the container. | |
* @param {Object} currentDimensions Current dimensions of the container. | |
* @param {Boolean} actionPossible `true`, if current and previous dimensions are different, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the refresh action will not be completed. | |
*/ | |
'beforeRefreshDimensions', | |
/** | |
* Fired by {@link CollapsibleColumns} plugin before columns collapse. This hook is fired when {@link Options#collapsibleColumns} option is enabled. | |
* | |
* @event Hooks#beforeColumnCollapse | |
* @param {Array} currentCollapsedColumns Current collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Array} destinationCollapsedColumns Destination collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Boolean} collapsePossible `true`, if all of the column indexes are withing the bounds of the collapsed sections, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the collapsing action will not be completed. | |
*/ | |
'beforeColumnCollapse', | |
/** | |
* Fired by {@link CollapsibleColumns} plugin before columns collapse. This hook is fired when {@link Options#collapsibleColumns} option is enabled. | |
* | |
* @event Hooks#afterColumnCollapse | |
* @param {Array} currentCollapsedColumns Current collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Array} destinationCollapsedColumns Destination collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Boolean} collapsePossible `true`, if all of the column indexes are withing the bounds of the collapsed sections, `false` otherwise. | |
* @param {Boolean} successfullyCollapsed `true`, if the action affected any non-collapsible column, `false` otherwise. | |
*/ | |
'afterColumnCollapse', | |
/** | |
* Fired by {@link CollapsibleColumns} plugin before columns expand. This hook is fired when {@link Options#collapsibleColumns} option is enabled. | |
* | |
* @event Hooks#beforeColumnExpand | |
* @param {Array} currentCollapsedColumns Current collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Array} destinationCollapsedColumns Destination collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Boolean} expandPossible `true`, if all of the column indexes are withing the bounds of the collapsed sections, `false` otherwise. | |
* @returns {undefined|Boolean} If the callback returns `false`, the expanding action will not be completed. | |
*/ | |
'beforeColumnExpand', | |
/** | |
* Fired by {@link CollapsibleColumns} plugin before columns expand. This hook is fired when {@link Options#collapsibleColumns} option is enabled. | |
* | |
* @event Hooks#afterColumnExpand | |
* @param {Array} currentCollapsedColumns Current collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Array} destinationCollapsedColumns Destination collapsible configuration - a list of collapsible physical column indexes. | |
* @param {Boolean} expandPossible `true`, if all of the column indexes are withing the bounds of the collapsed sections, `false` otherwise. | |
* @param {Boolean} successfullyExpanded `true`, if the action affected any non-collapsible column, `false` otherwise. | |
*/ | |
'afterColumnExpand']; | |
var Hooks = | |
/*#__PURE__*/ | |
function () { | |
(0, _createClass2.default)(Hooks, null, [{ | |
key: "getSingleton", | |
value: function getSingleton() { | |
return getGlobalSingleton(); | |
} | |
/** | |
* | |
*/ | |
}]); | |
function Hooks() { | |
(0, _classCallCheck2.default)(this, Hooks); | |
this.globalBucket = this.createEmptyBucket(); | |
} | |
/** | |
* Returns a new object with empty handlers related to every registered hook name. | |
* | |
* @returns {Object} The empty bucket object. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.createEmptyBucket(); | |
* // Results: | |
* { | |
* ... | |
* afterCreateCol: [], | |
* afterCreateRow: [], | |
* beforeInit: [], | |
* ... | |
* } | |
* ``` | |
*/ | |
(0, _createClass2.default)(Hooks, [{ | |
key: "createEmptyBucket", | |
value: function createEmptyBucket() { | |
var bucket = Object.create(null); // eslint-disable-next-line no-return-assign | |
(0, _array.arrayEach)(REGISTERED_HOOKS, function (hook) { | |
return bucket[hook] = []; | |
}); | |
return bucket; | |
} | |
/** | |
* Get hook bucket based on the context of the object or if argument is `undefined`, get the global hook bucket. | |
* | |
* @param {Object} [context=null] A Handsontable instance. | |
* @returns {Object} Returns a global or Handsontable instance bucket. | |
*/ | |
}, { | |
key: "getBucket", | |
value: function getBucket() { | |
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | |
if (context) { | |
if (!context.pluginHookBucket) { | |
context.pluginHookBucket = this.createEmptyBucket(); | |
} | |
return context.pluginHookBucket; | |
} | |
return this.globalBucket; | |
} | |
/** | |
* Adds a listener (globally or locally) to a specified hook name. | |
* If the `context` parameter is provided, the hook will be added only to the instance it references. | |
* Otherwise, the callback will be used everytime the hook fires on any Handsontable instance. | |
* You can provide an array of callback functions as the `callback` argument, this way they will all be fired | |
* once the hook is triggered. | |
* | |
* @see Core#addHook | |
* @param {String} key Hook name. | |
* @param {Function|Array} callback Callback function or an array of functions. | |
* @param {Object} [context=null] The context for the hook callback to be added - a Handsontable instance or leave empty. | |
* @returns {Hooks} Instance of Hooks. | |
* | |
* @example | |
* ```js | |
* // single callback, added locally | |
* Handsontable.hooks.add('beforeInit', myCallback, hotInstance); | |
* | |
* // single callback, added globally | |
* Handsontable.hooks.add('beforeInit', myCallback); | |
* | |
* // multiple callbacks, added locally | |
* Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback], hotInstance); | |
* | |
* // multiple callbacks, added globally | |
* Handsontable.hooks.add('beforeInit', [myCallback, anotherCallback]); | |
* ``` | |
*/ | |
}, { | |
key: "add", | |
value: function add(key, callback) { | |
var _this = this; | |
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | |
if (Array.isArray(callback)) { | |
(0, _array.arrayEach)(callback, function (c) { | |
return _this.add(key, c, context); | |
}); | |
} else { | |
var bucket = this.getBucket(context); | |
if (typeof bucket[key] === 'undefined') { | |
this.register(key); | |
bucket[key] = []; | |
} | |
callback.skip = false; | |
if (bucket[key].indexOf(callback) === -1) { | |
// only add a hook if it has not already been added (adding the same hook twice is now silently ignored) | |
var foundInitialHook = false; | |
if (callback.initialHook) { | |
(0, _array.arrayEach)(bucket[key], function (cb, i) { | |
if (cb.initialHook) { | |
bucket[key][i] = callback; | |
foundInitialHook = true; | |
return false; | |
} | |
}); | |
} | |
if (!foundInitialHook) { | |
bucket[key].push(callback); | |
} | |
} | |
} | |
return this; | |
} | |
/** | |
* Adds a listener to a specified hook. After the hook runs this listener will be automatically removed from the bucket. | |
* | |
* @see Core#addHookOnce | |
* @param {String} key Hook/Event name. | |
* @param {Function|Array} callback Callback function. | |
* @param {Object} [context=null] A Handsontable instance. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.once('beforeInit', myCallback, hotInstance); | |
* ``` | |
*/ | |
}, { | |
key: "once", | |
value: function once(key, callback) { | |
var _this2 = this; | |
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | |
if (Array.isArray(callback)) { | |
(0, _array.arrayEach)(callback, function (c) { | |
return _this2.once(key, c, context); | |
}); | |
} else { | |
callback.runOnce = true; | |
this.add(key, callback, context); | |
} | |
} | |
/** | |
* Removes a listener from a hook with a given name. If the `context` argument is provided, it removes a listener from a local hook assigned to the given Handsontable instance. | |
* | |
* @see Core#removeHook | |
* @param {String} key Hook/Event name. | |
* @param {Function} callback Callback function (needs the be the function that was previously added to the hook). | |
* @param {Object} [context=null] Handsontable instance. | |
* @return {Boolean} Returns `true` if hook was removed, `false` otherwise. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.remove('beforeInit', myCallback); | |
* ``` | |
*/ | |
}, { | |
key: "remove", | |
value: function remove(key, callback) { | |
var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | |
var bucket = this.getBucket(context); | |
if (typeof bucket[key] !== 'undefined') { | |
if (bucket[key].indexOf(callback) >= 0) { | |
callback.skip = true; | |
return true; | |
} | |
} | |
return false; | |
} | |
/** | |
* Checks whether there are any registered listeners for the provided hook name. | |
* If the `context` parameter is provided, it only checks for listeners assigned to the given Handsontable instance. | |
* | |
* @param {String} key Hook name. | |
* @param {Object} [context=null] A Handsontable instance. | |
* @returns {Boolean} `true` for success, `false` otherwise. | |
*/ | |
}, { | |
key: "has", | |
value: function has(key) { | |
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; | |
var bucket = this.getBucket(context); | |
return !!(bucket[key] !== void 0 && bucket[key].length); | |
} | |
/** | |
* Runs all local and global callbacks assigned to the hook identified by the `key` parameter. | |
* It returns either a return value from the last called callback or the first parameter (`p1`) passed to the `run` function. | |
* | |
* @see Core#runHooks | |
* @param {Object} context Handsontable instance. | |
* @param {String} key Hook/Event name. | |
* @param {*} [p1] Parameter to be passed as an argument to the callback function. | |
* @param {*} [p2] Parameter to be passed as an argument to the callback function. | |
* @param {*} [p3] Parameter to be passed as an argument to the callback function. | |
* @param {*} [p4] Parameter to be passed as an argument to the callback function. | |
* @param {*} [p5] Parameter to be passed as an argument to the callback function. | |
* @param {*} [p6] Parameter to be passed as an argument to the callback function. | |
* @returns {*} Either a return value from the last called callback or `p1`. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.run(hot, 'beforeInit'); | |
* ``` | |
*/ | |
}, { | |
key: "run", | |
value: function run(context, key, p1, p2, p3, p4, p5, p6) { | |
{ | |
var globalHandlers = this.globalBucket[key]; | |
var length = globalHandlers ? globalHandlers.length : 0; | |
var index = 0; | |
if (length) { | |
// Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC. | |
while (index < length) { | |
if (!globalHandlers[index] || globalHandlers[index].skip) { | |
index += 1; | |
/* eslint-disable no-continue */ | |
continue; | |
} // performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture | |
var res = globalHandlers[index].call(context, p1, p2, p3, p4, p5, p6); | |
if (res !== void 0) { | |
// eslint-disable-next-line no-param-reassign | |
p1 = res; | |
} | |
if (globalHandlers[index] && globalHandlers[index].runOnce) { | |
this.remove(key, globalHandlers[index]); | |
} | |
index += 1; | |
} | |
} | |
} | |
{ | |
var localHandlers = this.getBucket(context)[key]; | |
var _length = localHandlers ? localHandlers.length : 0; | |
var _index = 0; | |
if (_length) { | |
// Do not optimise this loop with arrayEach or arrow function! If you do You'll decrease perf because of GC. | |
while (_index < _length) { | |
if (!localHandlers[_index] || localHandlers[_index].skip) { | |
_index += 1; | |
/* eslint-disable no-continue */ | |
continue; | |
} // performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture | |
var _res = localHandlers[_index].call(context, p1, p2, p3, p4, p5, p6); | |
if (_res !== void 0) { | |
// eslint-disable-next-line no-param-reassign | |
p1 = _res; | |
} | |
if (localHandlers[_index] && localHandlers[_index].runOnce) { | |
this.remove(key, localHandlers[_index], context); | |
} | |
_index += 1; | |
} | |
} | |
} | |
return p1; | |
} | |
/** | |
* Destroy all listeners connected to the context. If no context is provided, the global listeners will be destroyed. | |
* | |
* @param {Object} [context=null] A Handsontable instance. | |
* @example | |
* ```js | |
* // destroy the global listeners | |
* Handsontable.hooks.destroy(); | |
* | |
* // destroy the local listeners | |
* Handsontable.hooks.destroy(hotInstance); | |
* ``` | |
*/ | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | |
// eslint-disable-next-line no-return-assign | |
(0, _object.objectEach)(this.getBucket(context), function (value, key, bucket) { | |
return bucket[key].length = 0; | |
}); | |
} | |
/** | |
* Registers a hook name (adds it to the list of the known hook names). Used by plugins. | |
* It is not necessary to call register, but if you use it, your plugin hook will be used returned by | |
* the `getRegistered` method. (which itself is used in the demo https://handsontable.com/docs/tutorial-using-callbacks.html). | |
* | |
* @param key {String} The hook name. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.register('myHook'); | |
* ``` | |
*/ | |
}, { | |
key: "register", | |
value: function register(key) { | |
if (!this.isRegistered(key)) { | |
REGISTERED_HOOKS.push(key); | |
} | |
} | |
/** | |
* Deregisters a hook name (removes it from the list of known hook names). | |
* | |
* @param key {String} Hook name. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.deregister('myHook'); | |
* ``` | |
*/ | |
}, { | |
key: "deregister", | |
value: function deregister(key) { | |
if (this.isRegistered(key)) { | |
REGISTERED_HOOKS.splice(REGISTERED_HOOKS.indexOf(key), 1); | |
} | |
} | |
/** | |
* Returns a boolean depending on if a hook by such name has been registered. | |
* | |
* @param key {String} Hook name. | |
* @returns {Boolean} `true` for success, `false` otherwise. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.isRegistered('beforeInit'); | |
* | |
* // Results: | |
* true | |
* ``` | |
*/ | |
}, { | |
key: "isRegistered", | |
value: function isRegistered(key) { | |
return REGISTERED_HOOKS.indexOf(key) >= 0; | |
} | |
/** | |
* Returns an array of registered hooks. | |
* | |
* @returns {Array} An array of registered hooks. | |
* | |
* @example | |
* ```js | |
* Handsontable.hooks.getRegistered(); | |
* | |
* // Results: | |
* [ | |
* ... | |
* 'beforeInit', | |
* 'beforeRender', | |
* 'beforeSetRangeEnd', | |
* 'beforeDrawBorders', | |
* 'beforeChange', | |
* ... | |
* ] | |
* ``` | |
*/ | |
}, { | |
key: "getRegistered", | |
value: function getRegistered() { | |
return REGISTERED_HOOKS; | |
} | |
}]); | |
return Hooks; | |
}(); | |
var globalSingleton = new Hooks(); | |
function getGlobalSingleton() { | |
return globalSingleton; | |
} | |
var _default = Hooks; | |
exports.default = _default; | |
/***/ }), | |
/* 46 */ | |
/***/ (function(module, exports) { | |
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } | |
function _typeof(obj) { | |
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { | |
module.exports = _typeof = function _typeof(obj) { | |
return _typeof2(obj); | |
}; | |
} else { | |
module.exports = _typeof = function _typeof(obj) { | |
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj); | |
}; | |
} | |
return _typeof(obj); | |
} | |
module.exports = _typeof; | |
/***/ }), | |
/* 47 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var isObject = __webpack_require__(44); | |
module.exports = function (it) { | |
if (!isObject(it)) { | |
throw TypeError(String(it) + ' is not an object'); | |
} return it; | |
}; | |
/***/ }), | |
/* 48 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var $ = __webpack_require__(21); | |
var from = __webpack_require__(420); | |
var checkCorrectnessOfIteration = __webpack_require__(207); | |
var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { | |
Array.from(iterable); | |
}); | |
// `Array.from` method | |
// https://tc39.github.io/ecma262/#sec-array.from | |
$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { | |
from: from | |
}); | |
/***/ }), | |
/* 49 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var IndexedObject = __webpack_require__(124); | |
var toIndexedObject = __webpack_require__(67); | |
var sloppyArrayMethod = __webpack_require__(107); | |
var nativeJoin = [].join; | |
var ES3_STRINGS = IndexedObject != Object; | |
var SLOPPY_METHOD = sloppyArrayMethod('join', ','); | |
// `Array.prototype.join` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.join | |
$({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD }, { | |
join: function join(separator) { | |
return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); | |
} | |
}); | |
/***/ }), | |
/* 50 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _array = __webpack_require__(3); | |
var _object = __webpack_require__(4); | |
var MIXIN_NAME = 'localHooks'; | |
/** | |
* Mixin object to extend objects functionality for local hooks. | |
* | |
* @type {Object} | |
*/ | |
var localHooks = { | |
/** | |
* Internal hooks storage. | |
*/ | |
_localHooks: Object.create(null), | |
/** | |
* Add hook to the collection. | |
* | |
* @param {String} key Hook name. | |
* @param {Function} callback Hook callback | |
* @returns {Object} | |
*/ | |
addLocalHook: function addLocalHook(key, callback) { | |
if (!this._localHooks[key]) { | |
this._localHooks[key] = []; | |
} | |
this._localHooks[key].push(callback); | |
return this; | |
}, | |
/** | |
* Run hooks. | |
* | |
* @param {String} key Hook name. | |
* @param {*} params | |
*/ | |
runLocalHooks: function runLocalHooks(key) { | |
var _this = this; | |
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
params[_key - 1] = arguments[_key]; | |
} | |
if (this._localHooks[key]) { | |
(0, _array.arrayEach)(this._localHooks[key], function (callback) { | |
return callback.apply(_this, params); | |
}); | |
} | |
}, | |
/** | |
* Clear all added hooks. | |
* | |
* @returns {Object} | |
*/ | |
clearLocalHooks: function clearLocalHooks() { | |
this._localHooks = {}; | |
return this; | |
} | |
}; | |
(0, _object.defineGetter)(localHooks, 'MIXIN_NAME', MIXIN_NAME, { | |
writable: false, | |
enumerable: false | |
}); | |
var _default = localHooks; | |
exports.default = _default; | |
/***/ }), | |
/* 51 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var fails = __webpack_require__(28); | |
// Thank's IE8 for his funny defineProperty | |
module.exports = !fails(function () { | |
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; | |
}); | |
/***/ }), | |
/* 52 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var toInteger = __webpack_require__(79); | |
var min = Math.min; | |
// `ToLength` abstract operation | |
// https://tc39.github.io/ecma262/#sec-tolength | |
module.exports = function (argument) { | |
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 | |
}; | |
/***/ }), | |
/* 53 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var fixRegExpWellKnownSymbolLogic = __webpack_require__(135); | |
var isRegExp = __webpack_require__(163); | |
var anObject = __webpack_require__(47); | |
var requireObjectCoercible = __webpack_require__(54); | |
var speciesConstructor = __webpack_require__(421); | |
var advanceStringIndex = __webpack_require__(164); | |
var toLength = __webpack_require__(52); | |
var callRegExpExec = __webpack_require__(136); | |
var regexpExec = __webpack_require__(162); | |
var fails = __webpack_require__(28); | |
var arrayPush = [].push; | |
var min = Math.min; | |
var MAX_UINT32 = 0xFFFFFFFF; | |
// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError | |
var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); }); | |
// @@split logic | |
fixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { | |
var internalSplit; | |
if ( | |
'abbc'.split(/(b)*/)[1] == 'c' || | |
'test'.split(/(?:)/, -1).length != 4 || | |
'ab'.split(/(?:ab)*/).length != 2 || | |
'.'.split(/(.?)(.?)/).length != 4 || | |
'.'.split(/()()/).length > 1 || | |
''.split(/.?/).length | |
) { | |
// based on es5-shim implementation, need to rework it | |
internalSplit = function (separator, limit) { | |
var string = String(requireObjectCoercible(this)); | |
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; | |
if (lim === 0) return []; | |
if (separator === undefined) return [string]; | |
// If `separator` is not a regex, use native split | |
if (!isRegExp(separator)) { | |
return nativeSplit.call(string, separator, lim); | |
} | |
var output = []; | |
var flags = (separator.ignoreCase ? 'i' : '') + | |
(separator.multiline ? 'm' : '') + | |
(separator.unicode ? 'u' : '') + | |
(separator.sticky ? 'y' : ''); | |
var lastLastIndex = 0; | |
// Make `global` and avoid `lastIndex` issues by working with a copy | |
var separatorCopy = new RegExp(separator.source, flags + 'g'); | |
var match, lastIndex, lastLength; | |
while (match = regexpExec.call(separatorCopy, string)) { | |
lastIndex = separatorCopy.lastIndex; | |
if (lastIndex > lastLastIndex) { | |
output.push(string.slice(lastLastIndex, match.index)); | |
if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); | |
lastLength = match[0].length; | |
lastLastIndex = lastIndex; | |
if (output.length >= lim) break; | |
} | |
if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop | |
} | |
if (lastLastIndex === string.length) { | |
if (lastLength || !separatorCopy.test('')) output.push(''); | |
} else output.push(string.slice(lastLastIndex)); | |
return output.length > lim ? output.slice(0, lim) : output; | |
}; | |
// Chakra, V8 | |
} else if ('0'.split(undefined, 0).length) { | |
internalSplit = function (separator, limit) { | |
return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); | |
}; | |
} else internalSplit = nativeSplit; | |
return [ | |
// `String.prototype.split` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype.split | |
function split(separator, limit) { | |
var O = requireObjectCoercible(this); | |
var splitter = separator == undefined ? undefined : separator[SPLIT]; | |
return splitter !== undefined | |
? splitter.call(separator, O, limit) | |
: internalSplit.call(String(O), separator, limit); | |
}, | |
// `RegExp.prototype[@@split]` method | |
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split | |
// | |
// NOTE: This cannot be properly polyfilled in engines that don't support | |
// the 'y' flag. | |
function (regexp, limit) { | |
var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); | |
if (res.done) return res.value; | |
var rx = anObject(regexp); | |
var S = String(this); | |
var C = speciesConstructor(rx, RegExp); | |
var unicodeMatching = rx.unicode; | |
var flags = (rx.ignoreCase ? 'i' : '') + | |
(rx.multiline ? 'm' : '') + | |
(rx.unicode ? 'u' : '') + | |
(SUPPORTS_Y ? 'y' : 'g'); | |
// ^(? + rx + ) is needed, in combination with some S slicing, to | |
// simulate the 'y' flag. | |
var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); | |
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; | |
if (lim === 0) return []; | |
if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : []; | |
var p = 0; | |
var q = 0; | |
var A = []; | |
while (q < S.length) { | |
splitter.lastIndex = SUPPORTS_Y ? q : 0; | |
var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q)); | |
var e; | |
if ( | |
z === null || | |
(e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p | |
) { | |
q = advanceStringIndex(S, q, unicodeMatching); | |
} else { | |
A.push(S.slice(p, q)); | |
if (A.length === lim) return A; | |
for (var i = 1; i <= z.length - 1; i++) { | |
A.push(z[i]); | |
if (A.length === lim) return A; | |
} | |
q = p = e; | |
} | |
} | |
A.push(S.slice(p)); | |
return A; | |
} | |
]; | |
}, !SUPPORTS_Y); | |
/***/ }), | |
/* 54 */ | |
/***/ (function(module, exports) { | |
// `RequireObjectCoercible` abstract operation | |
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible | |
module.exports = function (it) { | |
if (it == undefined) throw TypeError("Can't call method on " + it); | |
return it; | |
}; | |
/***/ }), | |
/* 55 */ | |
/***/ (function(module, exports) { | |
var hasOwnProperty = {}.hasOwnProperty; | |
module.exports = function (it, key) { | |
return hasOwnProperty.call(it, key); | |
}; | |
/***/ }), | |
/* 56 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var DESCRIPTORS = __webpack_require__(51); | |
var IE8_DOM_DEFINE = __webpack_require__(190); | |
var anObject = __webpack_require__(47); | |
var toPrimitive = __webpack_require__(98); | |
var nativeDefineProperty = Object.defineProperty; | |
// `Object.defineProperty` method | |
// https://tc39.github.io/ecma262/#sec-object.defineproperty | |
exports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) { | |
anObject(O); | |
P = toPrimitive(P, true); | |
anObject(Attributes); | |
if (IE8_DOM_DEFINE) try { | |
return nativeDefineProperty(O, P, Attributes); | |
} catch (error) { /* empty */ } | |
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); | |
if ('value' in Attributes) O[P] = Attributes.value; | |
return O; | |
}; | |
/***/ }), | |
/* 57 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.log = log; | |
exports.warn = warn; | |
exports.info = info; | |
exports.error = error; | |
var _mixed = __webpack_require__(24); | |
/* eslint-disable no-console */ | |
/* eslint-disable no-restricted-globals */ | |
/** | |
* "In Internet Explorer 9 (and 8), the console object is only exposed when the developer tools are opened | |
* for a particular tab." | |
* | |
* Source: https://stackoverflow.com/a/5473193 | |
*/ | |
/** | |
* Logs message to the console if the `console` object is exposed. | |
* | |
* @param {...*} args Values which will be logged. | |
*/ | |
function log() { | |
if ((0, _mixed.isDefined)(console)) { | |
var _console; | |
(_console = console).log.apply(_console, arguments); | |
} | |
} | |
/** | |
* Logs warn to the console if the `console` object is exposed. | |
* | |
* @param {...*} args Values which will be logged. | |
*/ | |
function warn() { | |
if ((0, _mixed.isDefined)(console)) { | |
var _console2; | |
(_console2 = console).warn.apply(_console2, arguments); | |
} | |
} | |
/** | |
* Logs info to the console if the `console` object is exposed. | |
* | |
* @param {...*} args Values which will be logged. | |
*/ | |
function info() { | |
if ((0, _mixed.isDefined)(console)) { | |
var _console3; | |
(_console3 = console).info.apply(_console3, arguments); | |
} | |
} | |
/** | |
* Logs error to the console if the `console` object is exposed. | |
* | |
* @param {...*} args Values which will be logged. | |
*/ | |
function error() { | |
if ((0, _mixed.isDefined)(console)) { | |
var _console4; | |
(_console4 = console).error.apply(_console4, arguments); | |
} | |
} | |
/***/ }), | |
/* 58 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(27); | |
__webpack_require__(15); | |
__webpack_require__(35); | |
__webpack_require__(53); | |
exports.__esModule = true; | |
exports.isPrintableChar = isPrintableChar; | |
exports.isMetaKey = isMetaKey; | |
exports.isCtrlKey = isCtrlKey; | |
exports.isCtrlMetaKey = isCtrlMetaKey; | |
exports.isKey = isKey; | |
exports.KEY_CODES = void 0; | |
var _array = __webpack_require__(3); | |
var KEY_CODES = { | |
MOUSE_LEFT: 1, | |
MOUSE_RIGHT: 3, | |
MOUSE_MIDDLE: 2, | |
BACKSPACE: 8, | |
COMMA: 188, | |
INSERT: 45, | |
DELETE: 46, | |
END: 35, | |
ENTER: 13, | |
ESCAPE: 27, | |
CONTROL: 17, | |
COMMAND_LEFT: 91, | |
COMMAND_RIGHT: 93, | |
COMMAND_FIREFOX: 224, | |
ALT: 18, | |
HOME: 36, | |
PAGE_DOWN: 34, | |
PAGE_UP: 33, | |
PERIOD: 190, | |
SPACE: 32, | |
SHIFT: 16, | |
CAPS_LOCK: 20, | |
TAB: 9, | |
ARROW_RIGHT: 39, | |
ARROW_LEFT: 37, | |
ARROW_UP: 38, | |
ARROW_DOWN: 40, | |
F1: 112, | |
F2: 113, | |
F3: 114, | |
F4: 115, | |
F5: 116, | |
F6: 117, | |
F7: 118, | |
F8: 119, | |
F9: 120, | |
F10: 121, | |
F11: 122, | |
F12: 123, | |
A: 65, | |
C: 67, | |
D: 68, | |
F: 70, | |
L: 76, | |
O: 79, | |
P: 80, | |
S: 83, | |
V: 86, | |
X: 88 | |
}; | |
/** | |
* Returns true if keyCode represents a printable character. | |
* | |
* @param {Number} keyCode | |
* @returns {Boolean} | |
*/ | |
exports.KEY_CODES = KEY_CODES; | |
function isPrintableChar(keyCode) { | |
return keyCode === 32 || // space | |
keyCode >= 48 && keyCode <= 57 || // 0-9 | |
keyCode >= 96 && keyCode <= 111 || // numpad | |
keyCode >= 186 && keyCode <= 192 || // ;=,-./` | |
keyCode >= 219 && keyCode <= 222 || // []{}\|"' | |
keyCode >= 226 || // special chars (229 for Asian chars) | |
keyCode >= 65 && keyCode <= 90; // a-z | |
} | |
/** | |
* @param {Number} keyCode | |
* @returns {Boolean} | |
*/ | |
function isMetaKey(keyCode) { | |
var metaKeys = [KEY_CODES.ARROW_DOWN, KEY_CODES.ARROW_UP, KEY_CODES.ARROW_LEFT, KEY_CODES.ARROW_RIGHT, KEY_CODES.HOME, KEY_CODES.END, KEY_CODES.DELETE, KEY_CODES.BACKSPACE, KEY_CODES.F1, KEY_CODES.F2, KEY_CODES.F3, KEY_CODES.F4, KEY_CODES.F5, KEY_CODES.F6, KEY_CODES.F7, KEY_CODES.F8, KEY_CODES.F9, KEY_CODES.F10, KEY_CODES.F11, KEY_CODES.F12, KEY_CODES.TAB, KEY_CODES.PAGE_DOWN, KEY_CODES.PAGE_UP, KEY_CODES.ENTER, KEY_CODES.ESCAPE, KEY_CODES.SHIFT, KEY_CODES.CAPS_LOCK, KEY_CODES.ALT]; | |
return metaKeys.indexOf(keyCode) !== -1; | |
} | |
/** | |
* Checks if passed key code is ctrl or cmd key. Depends on what OS the code runs it check key code based on | |
* different meta key codes. | |
* | |
* @param {Number} keyCode Key code to check. | |
* @returns {Boolean} | |
*/ | |
function isCtrlKey(keyCode) { | |
var keys = []; | |
if (navigator.platform.includes('Mac')) { | |
keys.push(KEY_CODES.COMMAND_LEFT, KEY_CODES.COMMAND_RIGHT, KEY_CODES.COMMAND_FIREFOX); | |
} else { | |
keys.push(KEY_CODES.CONTROL); | |
} | |
return keys.includes(keyCode); | |
} | |
/** | |
* Checks if passed key code is ctrl or cmd key. This helper checks if the key code matches to meta keys | |
* regardless of the OS on which it is running. | |
* | |
* @param {Number} keyCode Key code to check. | |
* @returns {Boolean} | |
*/ | |
function isCtrlMetaKey(keyCode) { | |
return [KEY_CODES.CONTROL, KEY_CODES.COMMAND_LEFT, KEY_CODES.COMMAND_RIGHT, KEY_CODES.COMMAND_FIREFOX].includes(keyCode); | |
} | |
/** | |
* @param {Number} keyCode | |
* @param {String} baseCode | |
* @returns {Boolean} | |
*/ | |
function isKey(keyCode, baseCode) { | |
var keys = baseCode.split('|'); | |
var result = false; | |
(0, _array.arrayEach)(keys, function (key) { | |
if (keyCode === KEY_CODES[key]) { | |
result = true; | |
return false; | |
} | |
}); | |
return result; | |
} | |
/***/ }), | |
/* 59 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var DESCRIPTORS = __webpack_require__(51); | |
var defineProperty = __webpack_require__(56).f; | |
var FunctionPrototype = Function.prototype; | |
var FunctionPrototypeToString = FunctionPrototype.toString; | |
var nameRE = /^\s*function ([^ (]*)/; | |
var NAME = 'name'; | |
// Function instances `.name` property | |
// https://tc39.github.io/ecma262/#sec-function-instances-name | |
if (DESCRIPTORS && !(NAME in FunctionPrototype)) { | |
defineProperty(FunctionPrototype, NAME, { | |
configurable: true, | |
get: function () { | |
try { | |
return FunctionPrototypeToString.call(this).match(nameRE)[1]; | |
} catch (error) { | |
return ''; | |
} | |
} | |
}); | |
} | |
/***/ }), | |
/* 60 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(12); | |
__webpack_require__(9); | |
__webpack_require__(11); | |
__webpack_require__(23); | |
__webpack_require__(13); | |
exports.__esModule = true; | |
exports.RegisteredEditor = RegisteredEditor; | |
exports.getEditorInstance = exports._getEditorInstance = _getEditorInstance; | |
exports.registerEditor = _register; | |
exports.getEditor = _getItem; | |
exports.getRegisteredEditors = exports.getRegisteredEditorNames = exports.hasEditor = void 0; | |
var _staticRegister2 = _interopRequireDefault(__webpack_require__(80)); | |
var _pluginHooks = _interopRequireDefault(__webpack_require__(45)); | |
var _baseEditor = _interopRequireDefault(__webpack_require__(110)); | |
var _autocompleteEditor = _interopRequireDefault(__webpack_require__(359)); | |
var _checkboxEditor = _interopRequireDefault(__webpack_require__(468)); | |
var _dateEditor = _interopRequireDefault(__webpack_require__(469)); | |
var _dropdownEditor = _interopRequireDefault(__webpack_require__(472)); | |
var _handsontableEditor = _interopRequireDefault(__webpack_require__(361)); | |
var _numericEditor = _interopRequireDefault(__webpack_require__(473)); | |
var _passwordEditor = _interopRequireDefault(__webpack_require__(474)); | |
var _selectEditor = _interopRequireDefault(__webpack_require__(475)); | |
var _textEditor = _interopRequireDefault(__webpack_require__(116)); | |
/** | |
* Utility to register editors and common namespace for keeping reference to all editor classes | |
*/ | |
var registeredEditorClasses = new WeakMap(); | |
var _staticRegister = (0, _staticRegister2.default)('editors'), | |
register = _staticRegister.register, | |
getItem = _staticRegister.getItem, | |
hasItem = _staticRegister.hasItem, | |
getNames = _staticRegister.getNames, | |
getValues = _staticRegister.getValues; | |
exports.getRegisteredEditors = getValues; | |
exports.getRegisteredEditorNames = getNames; | |
exports.hasEditor = hasItem; | |
_register('base', _baseEditor.default); | |
_register('autocomplete', _autocompleteEditor.default); | |
_register('checkbox', _checkboxEditor.default); | |
_register('date', _dateEditor.default); | |
_register('dropdown', _dropdownEditor.default); | |
_register('handsontable', _handsontableEditor.default); | |
_register('numeric', _numericEditor.default); | |
_register('password', _passwordEditor.default); | |
_register('select', _selectEditor.default); | |
_register('text', _textEditor.default); | |
function RegisteredEditor(editorClass) { | |
var instances = {}; | |
var Clazz = editorClass; | |
this.getConstructor = function () { | |
return editorClass; | |
}; | |
this.getInstance = function (hotInstance) { | |
if (!(hotInstance.guid in instances)) { | |
instances[hotInstance.guid] = new Clazz(hotInstance); | |
} | |
return instances[hotInstance.guid]; | |
}; | |
_pluginHooks.default.getSingleton().add('afterDestroy', function () { | |
instances[this.guid] = null; | |
}); | |
} | |
/** | |
* Returns instance (singleton) of editor class. | |
* | |
* @param {String} name Name of an editor under which it has been stored. | |
* @param {Object} hotInstance Instance of Handsontable. | |
* @returns {Function} Returns instance of editor. | |
*/ | |
function _getEditorInstance(name, hotInstance) { | |
var editor; | |
if (typeof name === 'function') { | |
if (!registeredEditorClasses.get(name)) { | |
_register(null, name); | |
} | |
editor = registeredEditorClasses.get(name); | |
} else if (typeof name === 'string') { | |
editor = getItem(name); | |
} else { | |
throw Error('Only strings and functions can be passed as "editor" parameter'); | |
} | |
if (!editor) { | |
throw Error("No editor registered under name \"".concat(name, "\"")); | |
} | |
return editor.getInstance(hotInstance); | |
} | |
/** | |
* Retrieve editor class. | |
* | |
* @param {String} name Editor identification. | |
* @returns {Function} Returns editor class. | |
*/ | |
function _getItem(name) { | |
if (!hasItem(name)) { | |
throw Error("No registered editor found under \"".concat(name, "\" name")); | |
} | |
return getItem(name).getConstructor(); | |
} | |
/** | |
* Register editor class under specified name. | |
* | |
* @param {String} name Editor identification. | |
* @param {Function} editorClass Editor class. | |
*/ | |
function _register(name, editorClass) { | |
var editorWrapper = new RegisteredEditor(editorClass); | |
if (typeof name === 'string') { | |
register(name, editorWrapper); | |
} | |
registeredEditorClasses.set(editorClass, editorWrapper); | |
} | |
/***/ }), | |
/* 61 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var global = __webpack_require__(38); | |
var DOMIterables = __webpack_require__(209); | |
var forEach = __webpack_require__(439); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
for (var COLLECTION_NAME in DOMIterables) { | |
var Collection = global[COLLECTION_NAME]; | |
var CollectionPrototype = Collection && Collection.prototype; | |
// some Chrome versions have non-configurable methods on DOMTokenList | |
if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try { | |
createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach); | |
} catch (error) { | |
CollectionPrototype.forEach = forEach; | |
} | |
} | |
/***/ }), | |
/* 62 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var requireObjectCoercible = __webpack_require__(54); | |
// `ToObject` abstract operation | |
// https://tc39.github.io/ecma262/#sec-toobject | |
module.exports = function (argument) { | |
return Object(requireObjectCoercible(argument)); | |
}; | |
/***/ }), | |
/* 63 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(17); | |
__webpack_require__(113); | |
__webpack_require__(31); | |
__webpack_require__(36); | |
exports.__esModule = true; | |
exports.isFunction = isFunction; | |
exports.throttle = throttle; | |
exports.throttleAfterHits = throttleAfterHits; | |
exports.debounce = debounce; | |
exports.pipe = pipe; | |
exports.partial = partial; | |
exports.curry = curry; | |
exports.curryRight = curryRight; | |
var _array = __webpack_require__(3); | |
/** | |
* Checks if given variable is function. | |
* | |
* @param {*} func Variable to check. | |
* @returns {Boolean} | |
*/ | |
function isFunction(func) { | |
return typeof func === 'function'; | |
} | |
/** | |
* Creates throttle function that enforces a maximum number of times a function (`func`) can be called over time (`wait`). | |
* | |
* @param {Function} func Function to invoke. | |
* @param {Number} wait Delay in miliseconds. | |
* @returns {Function} | |
*/ | |
function throttle(func) { | |
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; | |
var lastCalled = 0; | |
var result = { | |
lastCallThrottled: true | |
}; | |
var lastTimer = null; | |
function _throttle() { | |
var _this = this; | |
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
var stamp = Date.now(); | |
var needCall = false; | |
result.lastCallThrottled = true; | |
if (!lastCalled) { | |
lastCalled = stamp; | |
needCall = true; | |
} | |
var remaining = wait - (stamp - lastCalled); | |
if (needCall) { | |
result.lastCallThrottled = false; | |
func.apply(this, args); | |
} else { | |
if (lastTimer) { | |
clearTimeout(lastTimer); | |
} | |
lastTimer = setTimeout(function () { | |
result.lastCallThrottled = false; | |
func.apply(_this, args); | |
lastCalled = 0; | |
lastTimer = void 0; | |
}, remaining); | |
} | |
return result; | |
} | |
return _throttle; | |
} | |
/** | |
* Creates throttle function that enforces a maximum number of times a function (`func`) can be called over | |
* time (`wait`) after specified hits. | |
* | |
* @param {Function} func Function to invoke. | |
* @param {Number} wait Delay in miliseconds. | |
* @param {Number} hits Number of hits after throttling will be applied. | |
* @returns {Function} | |
*/ | |
function throttleAfterHits(func) { | |
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; | |
var hits = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10; | |
var funcThrottle = throttle(func, wait); | |
var remainHits = hits; | |
function _clearHits() { | |
remainHits = hits; | |
} | |
function _throttleAfterHits() { | |
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | |
args[_key2] = arguments[_key2]; | |
} | |
if (remainHits) { | |
remainHits -= 1; | |
return func.apply(this, args); | |
} | |
return funcThrottle.apply(this, args); | |
} | |
_throttleAfterHits.clearHits = _clearHits; | |
return _throttleAfterHits; | |
} | |
/** | |
* Creates debounce function that enforces a function (`func`) not be called again until a certain amount of time (`wait`) | |
* has passed without it being called. | |
* | |
* @param {Function} func Function to invoke. | |
* @param {Number} wait Delay in milliseconds. | |
* @returns {Function} | |
*/ | |
function debounce(func) { | |
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200; | |
var lastTimer = null; | |
var result; | |
function _debounce() { | |
var _this2 = this; | |
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | |
args[_key3] = arguments[_key3]; | |
} | |
if (lastTimer) { | |
clearTimeout(lastTimer); | |
} | |
lastTimer = setTimeout(function () { | |
result = func.apply(_this2, args); | |
}, wait); | |
return result; | |
} | |
return _debounce; | |
} | |
/** | |
* Creates the function that returns the result of calling the given functions. Result of the first function is passed to | |
* the second as an argument and so on. Only first function in the chain can handle multiple arguments. | |
* | |
* @param {Function} functions Functions to compose. | |
* @returns {Function} | |
*/ | |
function pipe() { | |
for (var _len4 = arguments.length, functions = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | |
functions[_key4] = arguments[_key4]; | |
} | |
var firstFunc = functions[0], | |
restFunc = functions.slice(1); | |
return function _pipe() { | |
for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { | |
args[_key5] = arguments[_key5]; | |
} | |
return (0, _array.arrayReduce)(restFunc, function (acc, fn) { | |
return fn(acc); | |
}, firstFunc.apply(this, args)); | |
}; | |
} | |
/** | |
* Creates the function that returns the function with cached arguments. | |
* | |
* @param {Function} func Function to partialization. | |
* @param {Array} params Function arguments to cache. | |
* @returns {Function} | |
*/ | |
function partial(func) { | |
for (var _len6 = arguments.length, params = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { | |
params[_key6 - 1] = arguments[_key6]; | |
} | |
return function _partial() { | |
for (var _len7 = arguments.length, restParams = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { | |
restParams[_key7] = arguments[_key7]; | |
} | |
return func.apply(this, params.concat(restParams)); | |
}; | |
} | |
/** | |
* Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched | |
* to the arguments defined in `func` then function will be invoked. | |
* Arguments are added to the stack in direction from the left to the right. | |
* | |
* @example | |
* ``` | |
* var replace = curry(function(find, replace, string) { | |
* return string.replace(find, replace); | |
* }); | |
* | |
* // returns function with bounded first argument | |
* var replace = replace('foo') | |
* | |
* // returns replaced string - all arguments was passed so function was invoked | |
* replace('bar', 'Some test with foo...'); | |
* | |
* ``` | |
* | |
* @param {Function} func Function to currying. | |
* @returns {Function} | |
*/ | |
function curry(func) { | |
var argsLength = func.length; | |
function given(argsSoFar) { | |
return function _curry() { | |
for (var _len8 = arguments.length, params = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { | |
params[_key8] = arguments[_key8]; | |
} | |
var passedArgsSoFar = argsSoFar.concat(params); | |
var result; | |
if (passedArgsSoFar.length >= argsLength) { | |
result = func.apply(this, passedArgsSoFar); | |
} else { | |
result = given(passedArgsSoFar); | |
} | |
return result; | |
}; | |
} | |
return given([]); | |
} | |
/** | |
* Creates the functions that returns the function with cached arguments. If count if passed arguments will be matched | |
* to the arguments defined in `func` then function will be invoked. | |
* Arguments are added to the stack in direction from the right to the left. | |
* | |
* @example | |
* ``` | |
* var replace = curry(function(find, replace, string) { | |
* return string.replace(find, replace); | |
* }); | |
* | |
* // returns function with bounded first argument | |
* var replace = replace('Some test with foo...') | |
* | |
* // returns replaced string - all arguments was passed so function was invoked | |
* replace('bar', 'foo'); | |
* | |
* ``` | |
* | |
* @param {Function} func Function to currying. | |
* @returns {Function} | |
*/ | |
function curryRight(func) { | |
var argsLength = func.length; | |
function given(argsSoFar) { | |
return function _curry() { | |
for (var _len9 = arguments.length, params = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { | |
params[_key9] = arguments[_key9]; | |
} | |
var passedArgsSoFar = argsSoFar.concat(params.reverse()); | |
var result; | |
if (passedArgsSoFar.length >= argsLength) { | |
result = func.apply(this, passedArgsSoFar); | |
} else { | |
result = given(passedArgsSoFar); | |
} | |
return result; | |
}; | |
} | |
return given([]); | |
} | |
/***/ }), | |
/* 64 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
/* WEBPACK VAR INJECTION */(function(module) {var require;//! moment.js | |
//! version : 2.20.1 | |
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors | |
//! license : MIT | |
//! momentjs.com | |
;(function (global, factory) { | |
true ? module.exports = factory() : | |
undefined | |
}(this, (function () { 'use strict'; | |
var hookCallback; | |
function hooks () { | |
return hookCallback.apply(null, arguments); | |
} | |
// This is done to register the method called with moment() | |
// without creating circular dependencies. | |
function setHookCallback (callback) { | |
hookCallback = callback; | |
} | |
function isArray(input) { | |
return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; | |
} | |
function isObject(input) { | |
// IE8 will treat undefined and null as object if it wasn't for | |
// input != null | |
return input != null && Object.prototype.toString.call(input) === '[object Object]'; | |
} | |
function isObjectEmpty(obj) { | |
if (Object.getOwnPropertyNames) { | |
return (Object.getOwnPropertyNames(obj).length === 0); | |
} else { | |
var k; | |
for (k in obj) { | |
if (obj.hasOwnProperty(k)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} | |
function isUndefined(input) { | |
return input === void 0; | |
} | |
function isNumber(input) { | |
return typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]'; | |
} | |
function isDate(input) { | |
return input instanceof Date || Object.prototype.toString.call(input) === '[object Date]'; | |
} | |
function map(arr, fn) { | |
var res = [], i; | |
for (i = 0; i < arr.length; ++i) { | |
res.push(fn(arr[i], i)); | |
} | |
return res; | |
} | |
function hasOwnProp(a, b) { | |
return Object.prototype.hasOwnProperty.call(a, b); | |
} | |
function extend(a, b) { | |
for (var i in b) { | |
if (hasOwnProp(b, i)) { | |
a[i] = b[i]; | |
} | |
} | |
if (hasOwnProp(b, 'toString')) { | |
a.toString = b.toString; | |
} | |
if (hasOwnProp(b, 'valueOf')) { | |
a.valueOf = b.valueOf; | |
} | |
return a; | |
} | |
function createUTC (input, format, locale, strict) { | |
return createLocalOrUTC(input, format, locale, strict, true).utc(); | |
} | |
function defaultParsingFlags() { | |
// We need to deep clone this object. | |
return { | |
empty : false, | |
unusedTokens : [], | |
unusedInput : [], | |
overflow : -2, | |
charsLeftOver : 0, | |
nullInput : false, | |
invalidMonth : null, | |
invalidFormat : false, | |
userInvalidated : false, | |
iso : false, | |
parsedDateParts : [], | |
meridiem : null, | |
rfc2822 : false, | |
weekdayMismatch : false | |
}; | |
} | |
function getParsingFlags(m) { | |
if (m._pf == null) { | |
m._pf = defaultParsingFlags(); | |
} | |
return m._pf; | |
} | |
var some; | |
if (Array.prototype.some) { | |
some = Array.prototype.some; | |
} else { | |
some = function (fun) { | |
var t = Object(this); | |
var len = t.length >>> 0; | |
for (var i = 0; i < len; i++) { | |
if (i in t && fun.call(this, t[i], i, t)) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
} | |
function isValid(m) { | |
if (m._isValid == null) { | |
var flags = getParsingFlags(m); | |
var parsedParts = some.call(flags.parsedDateParts, function (i) { | |
return i != null; | |
}); | |
var isNowValid = !isNaN(m._d.getTime()) && | |
flags.overflow < 0 && | |
!flags.empty && | |
!flags.invalidMonth && | |
!flags.invalidWeekday && | |
!flags.weekdayMismatch && | |
!flags.nullInput && | |
!flags.invalidFormat && | |
!flags.userInvalidated && | |
(!flags.meridiem || (flags.meridiem && parsedParts)); | |
if (m._strict) { | |
isNowValid = isNowValid && | |
flags.charsLeftOver === 0 && | |
flags.unusedTokens.length === 0 && | |
flags.bigHour === undefined; | |
} | |
if (Object.isFrozen == null || !Object.isFrozen(m)) { | |
m._isValid = isNowValid; | |
} | |
else { | |
return isNowValid; | |
} | |
} | |
return m._isValid; | |
} | |
function createInvalid (flags) { | |
var m = createUTC(NaN); | |
if (flags != null) { | |
extend(getParsingFlags(m), flags); | |
} | |
else { | |
getParsingFlags(m).userInvalidated = true; | |
} | |
return m; | |
} | |
// Plugins that add properties should also add the key here (null value), | |
// so we can properly clone ourselves. | |
var momentProperties = hooks.momentProperties = []; | |
function copyConfig(to, from) { | |
var i, prop, val; | |
if (!isUndefined(from._isAMomentObject)) { | |
to._isAMomentObject = from._isAMomentObject; | |
} | |
if (!isUndefined(from._i)) { | |
to._i = from._i; | |
} | |
if (!isUndefined(from._f)) { | |
to._f = from._f; | |
} | |
if (!isUndefined(from._l)) { | |
to._l = from._l; | |
} | |
if (!isUndefined(from._strict)) { | |
to._strict = from._strict; | |
} | |
if (!isUndefined(from._tzm)) { | |
to._tzm = from._tzm; | |
} | |
if (!isUndefined(from._isUTC)) { | |
to._isUTC = from._isUTC; | |
} | |
if (!isUndefined(from._offset)) { | |
to._offset = from._offset; | |
} | |
if (!isUndefined(from._pf)) { | |
to._pf = getParsingFlags(from); | |
} | |
if (!isUndefined(from._locale)) { | |
to._locale = from._locale; | |
} | |
if (momentProperties.length > 0) { | |
for (i = 0; i < momentProperties.length; i++) { | |
prop = momentProperties[i]; | |
val = from[prop]; | |
if (!isUndefined(val)) { | |
to[prop] = val; | |
} | |
} | |
} | |
return to; | |
} | |
var updateInProgress = false; | |
// Moment prototype object | |
function Moment(config) { | |
copyConfig(this, config); | |
this._d = new Date(config._d != null ? config._d.getTime() : NaN); | |
if (!this.isValid()) { | |
this._d = new Date(NaN); | |
} | |
// Prevent infinite loop in case updateOffset creates new moment | |
// objects. | |
if (updateInProgress === false) { | |
updateInProgress = true; | |
hooks.updateOffset(this); | |
updateInProgress = false; | |
} | |
} | |
function isMoment (obj) { | |
return obj instanceof Moment || (obj != null && obj._isAMomentObject != null); | |
} | |
function absFloor (number) { | |
if (number < 0) { | |
// -0 -> 0 | |
return Math.ceil(number) || 0; | |
} else { | |
return Math.floor(number); | |
} | |
} | |
function toInt(argumentForCoercion) { | |
var coercedNumber = +argumentForCoercion, | |
value = 0; | |
if (coercedNumber !== 0 && isFinite(coercedNumber)) { | |
value = absFloor(coercedNumber); | |
} | |
return value; | |
} | |
// compare two arrays, return the number of differences | |
function compareArrays(array1, array2, dontConvert) { | |
var len = Math.min(array1.length, array2.length), | |
lengthDiff = Math.abs(array1.length - array2.length), | |
diffs = 0, | |
i; | |
for (i = 0; i < len; i++) { | |
if ((dontConvert && array1[i] !== array2[i]) || | |
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { | |
diffs++; | |
} | |
} | |
return diffs + lengthDiff; | |
} | |
function warn(msg) { | |
if (hooks.suppressDeprecationWarnings === false && | |
(typeof console !== 'undefined') && console.warn) { | |
console.warn('Deprecation warning: ' + msg); | |
} | |
} | |
function deprecate(msg, fn) { | |
var firstTime = true; | |
return extend(function () { | |
if (hooks.deprecationHandler != null) { | |
hooks.deprecationHandler(null, msg); | |
} | |
if (firstTime) { | |
var args = []; | |
var arg; | |
for (var i = 0; i < arguments.length; i++) { | |
arg = ''; | |
if (typeof arguments[i] === 'object') { | |
arg += '\n[' + i + '] '; | |
for (var key in arguments[0]) { | |
arg += key + ': ' + arguments[0][key] + ', '; | |
} | |
arg = arg.slice(0, -2); // Remove trailing comma and space | |
} else { | |
arg = arguments[i]; | |
} | |
args.push(arg); | |
} | |
warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + (new Error()).stack); | |
firstTime = false; | |
} | |
return fn.apply(this, arguments); | |
}, fn); | |
} | |
var deprecations = {}; | |
function deprecateSimple(name, msg) { | |
if (hooks.deprecationHandler != null) { | |
hooks.deprecationHandler(name, msg); | |
} | |
if (!deprecations[name]) { | |
warn(msg); | |
deprecations[name] = true; | |
} | |
} | |
hooks.suppressDeprecationWarnings = false; | |
hooks.deprecationHandler = null; | |
function isFunction(input) { | |
return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; | |
} | |
function set (config) { | |
var prop, i; | |
for (i in config) { | |
prop = config[i]; | |
if (isFunction(prop)) { | |
this[i] = prop; | |
} else { | |
this['_' + i] = prop; | |
} | |
} | |
this._config = config; | |
// Lenient ordinal parsing accepts just a number in addition to | |
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse. | |
// TODO: Remove "ordinalParse" fallback in next major release. | |
this._dayOfMonthOrdinalParseLenient = new RegExp( | |
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + | |
'|' + (/\d{1,2}/).source); | |
} | |
function mergeConfigs(parentConfig, childConfig) { | |
var res = extend({}, parentConfig), prop; | |
for (prop in childConfig) { | |
if (hasOwnProp(childConfig, prop)) { | |
if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { | |
res[prop] = {}; | |
extend(res[prop], parentConfig[prop]); | |
extend(res[prop], childConfig[prop]); | |
} else if (childConfig[prop] != null) { | |
res[prop] = childConfig[prop]; | |
} else { | |
delete res[prop]; | |
} | |
} | |
} | |
for (prop in parentConfig) { | |
if (hasOwnProp(parentConfig, prop) && | |
!hasOwnProp(childConfig, prop) && | |
isObject(parentConfig[prop])) { | |
// make sure changes to properties don't modify parent config | |
res[prop] = extend({}, res[prop]); | |
} | |
} | |
return res; | |
} | |
function Locale(config) { | |
if (config != null) { | |
this.set(config); | |
} | |
} | |
var keys; | |
if (Object.keys) { | |
keys = Object.keys; | |
} else { | |
keys = function (obj) { | |
var i, res = []; | |
for (i in obj) { | |
if (hasOwnProp(obj, i)) { | |
res.push(i); | |
} | |
} | |
return res; | |
}; | |
} | |
var defaultCalendar = { | |
sameDay : '[Today at] LT', | |
nextDay : '[Tomorrow at] LT', | |
nextWeek : 'dddd [at] LT', | |
lastDay : '[Yesterday at] LT', | |
lastWeek : '[Last] dddd [at] LT', | |
sameElse : 'L' | |
}; | |
function calendar (key, mom, now) { | |
var output = this._calendar[key] || this._calendar['sameElse']; | |
return isFunction(output) ? output.call(mom, now) : output; | |
} | |
var defaultLongDateFormat = { | |
LTS : 'h:mm:ss A', | |
LT : 'h:mm A', | |
L : 'MM/DD/YYYY', | |
LL : 'MMMM D, YYYY', | |
LLL : 'MMMM D, YYYY h:mm A', | |
LLLL : 'dddd, MMMM D, YYYY h:mm A' | |
}; | |
function longDateFormat (key) { | |
var format = this._longDateFormat[key], | |
formatUpper = this._longDateFormat[key.toUpperCase()]; | |
if (format || !formatUpper) { | |
return format; | |
} | |
this._longDateFormat[key] = formatUpper.replace(/MMMM|MM|DD|dddd/g, function (val) { | |
return val.slice(1); | |
}); | |
return this._longDateFormat[key]; | |
} | |
var defaultInvalidDate = 'Invalid date'; | |
function invalidDate () { | |
return this._invalidDate; | |
} | |
var defaultOrdinal = '%d'; | |
var defaultDayOfMonthOrdinalParse = /\d{1,2}/; | |
function ordinal (number) { | |
return this._ordinal.replace('%d', number); | |
} | |
var defaultRelativeTime = { | |
future : 'in %s', | |
past : '%s ago', | |
s : 'a few seconds', | |
ss : '%d seconds', | |
m : 'a minute', | |
mm : '%d minutes', | |
h : 'an hour', | |
hh : '%d hours', | |
d : 'a day', | |
dd : '%d days', | |
M : 'a month', | |
MM : '%d months', | |
y : 'a year', | |
yy : '%d years' | |
}; | |
function relativeTime (number, withoutSuffix, string, isFuture) { | |
var output = this._relativeTime[string]; | |
return (isFunction(output)) ? | |
output(number, withoutSuffix, string, isFuture) : | |
output.replace(/%d/i, number); | |
} | |
function pastFuture (diff, output) { | |
var format = this._relativeTime[diff > 0 ? 'future' : 'past']; | |
return isFunction(format) ? format(output) : format.replace(/%s/i, output); | |
} | |
var aliases = {}; | |
function addUnitAlias (unit, shorthand) { | |
var lowerCase = unit.toLowerCase(); | |
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; | |
} | |
function normalizeUnits(units) { | |
return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; | |
} | |
function normalizeObjectUnits(inputObject) { | |
var normalizedInput = {}, | |
normalizedProp, | |
prop; | |
for (prop in inputObject) { | |
if (hasOwnProp(inputObject, prop)) { | |
normalizedProp = normalizeUnits(prop); | |
if (normalizedProp) { | |
normalizedInput[normalizedProp] = inputObject[prop]; | |
} | |
} | |
} | |
return normalizedInput; | |
} | |
var priorities = {}; | |
function addUnitPriority(unit, priority) { | |
priorities[unit] = priority; | |
} | |
function getPrioritizedUnits(unitsObj) { | |
var units = []; | |
for (var u in unitsObj) { | |
units.push({unit: u, priority: priorities[u]}); | |
} | |
units.sort(function (a, b) { | |
return a.priority - b.priority; | |
}); | |
return units; | |
} | |
function zeroFill(number, targetLength, forceSign) { | |
var absNumber = '' + Math.abs(number), | |
zerosToFill = targetLength - absNumber.length, | |
sign = number >= 0; | |
return (sign ? (forceSign ? '+' : '') : '-') + | |
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; | |
} | |
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g; | |
var localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g; | |
var formatFunctions = {}; | |
var formatTokenFunctions = {}; | |
// token: 'M' | |
// padded: ['MM', 2] | |
// ordinal: 'Mo' | |
// callback: function () { this.month() + 1 } | |
function addFormatToken (token, padded, ordinal, callback) { | |
var func = callback; | |
if (typeof callback === 'string') { | |
func = function () { | |
return this[callback](); | |
}; | |
} | |
if (token) { | |
formatTokenFunctions[token] = func; | |
} | |
if (padded) { | |
formatTokenFunctions[padded[0]] = function () { | |
return zeroFill(func.apply(this, arguments), padded[1], padded[2]); | |
}; | |
} | |
if (ordinal) { | |
formatTokenFunctions[ordinal] = function () { | |
return this.localeData().ordinal(func.apply(this, arguments), token); | |
}; | |
} | |
} | |
function removeFormattingTokens(input) { | |
if (input.match(/\[[\s\S]/)) { | |
return input.replace(/^\[|\]$/g, ''); | |
} | |
return input.replace(/\\/g, ''); | |
} | |
function makeFormatFunction(format) { | |
var array = format.match(formattingTokens), i, length; | |
for (i = 0, length = array.length; i < length; i++) { | |
if (formatTokenFunctions[array[i]]) { | |
array[i] = formatTokenFunctions[array[i]]; | |
} else { | |
array[i] = removeFormattingTokens(array[i]); | |
} | |
} | |
return function (mom) { | |
var output = '', i; | |
for (i = 0; i < length; i++) { | |
output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; | |
} | |
return output; | |
}; | |
} | |
// format date using native date object | |
function formatMoment(m, format) { | |
if (!m.isValid()) { | |
return m.localeData().invalidDate(); | |
} | |
format = expandFormat(format, m.localeData()); | |
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); | |
return formatFunctions[format](m); | |
} | |
function expandFormat(format, locale) { | |
var i = 5; | |
function replaceLongDateFormatTokens(input) { | |
return locale.longDateFormat(input) || input; | |
} | |
localFormattingTokens.lastIndex = 0; | |
while (i >= 0 && localFormattingTokens.test(format)) { | |
format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); | |
localFormattingTokens.lastIndex = 0; | |
i -= 1; | |
} | |
return format; | |
} | |
var match1 = /\d/; // 0 - 9 | |
var match2 = /\d\d/; // 00 - 99 | |
var match3 = /\d{3}/; // 000 - 999 | |
var match4 = /\d{4}/; // 0000 - 9999 | |
var match6 = /[+-]?\d{6}/; // -999999 - 999999 | |
var match1to2 = /\d\d?/; // 0 - 99 | |
var match3to4 = /\d\d\d\d?/; // 999 - 9999 | |
var match5to6 = /\d\d\d\d\d\d?/; // 99999 - 999999 | |
var match1to3 = /\d{1,3}/; // 0 - 999 | |
var match1to4 = /\d{1,4}/; // 0 - 9999 | |
var match1to6 = /[+-]?\d{1,6}/; // -999999 - 999999 | |
var matchUnsigned = /\d+/; // 0 - inf | |
var matchSigned = /[+-]?\d+/; // -inf - inf | |
var matchOffset = /Z|[+-]\d\d:?\d\d/gi; // +00:00 -00:00 +0000 -0000 or Z | |
var matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi; // +00 -00 +00:00 -00:00 +0000 -0000 or Z | |
var matchTimestamp = /[+-]?\d+(\.\d{1,3})?/; // 123456789 123456789.123 | |
// any word (or two) characters or numbers including two/three word month in arabic. | |
// includes scottish gaelic two word and hyphenated months | |
var matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i; | |
var regexes = {}; | |
function addRegexToken (token, regex, strictRegex) { | |
regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { | |
return (isStrict && strictRegex) ? strictRegex : regex; | |
}; | |
} | |
function getParseRegexForToken (token, config) { | |
if (!hasOwnProp(regexes, token)) { | |
return new RegExp(unescapeFormat(token)); | |
} | |
return regexes[token](config._strict, config._locale); | |
} | |
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript | |
function unescapeFormat(s) { | |
return regexEscape(s.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { | |
return p1 || p2 || p3 || p4; | |
})); | |
} | |
function regexEscape(s) { | |
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); | |
} | |
var tokens = {}; | |
function addParseToken (token, callback) { | |
var i, func = callback; | |
if (typeof token === 'string') { | |
token = [token]; | |
} | |
if (isNumber(callback)) { | |
func = function (input, array) { | |
array[callback] = toInt(input); | |
}; | |
} | |
for (i = 0; i < token.length; i++) { | |
tokens[token[i]] = func; | |
} | |
} | |
function addWeekParseToken (token, callback) { | |
addParseToken(token, function (input, array, config, token) { | |
config._w = config._w || {}; | |
callback(input, config._w, config, token); | |
}); | |
} | |
function addTimeToArrayFromToken(token, input, config) { | |
if (input != null && hasOwnProp(tokens, token)) { | |
tokens[token](input, config._a, config, token); | |
} | |
} | |
var YEAR = 0; | |
var MONTH = 1; | |
var DATE = 2; | |
var HOUR = 3; | |
var MINUTE = 4; | |
var SECOND = 5; | |
var MILLISECOND = 6; | |
var WEEK = 7; | |
var WEEKDAY = 8; | |
// FORMATTING | |
addFormatToken('Y', 0, 0, function () { | |
var y = this.year(); | |
return y <= 9999 ? '' + y : '+' + y; | |
}); | |
addFormatToken(0, ['YY', 2], 0, function () { | |
return this.year() % 100; | |
}); | |
addFormatToken(0, ['YYYY', 4], 0, 'year'); | |
addFormatToken(0, ['YYYYY', 5], 0, 'year'); | |
addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); | |
// ALIASES | |
addUnitAlias('year', 'y'); | |
// PRIORITIES | |
addUnitPriority('year', 1); | |
// PARSING | |
addRegexToken('Y', matchSigned); | |
addRegexToken('YY', match1to2, match2); | |
addRegexToken('YYYY', match1to4, match4); | |
addRegexToken('YYYYY', match1to6, match6); | |
addRegexToken('YYYYYY', match1to6, match6); | |
addParseToken(['YYYYY', 'YYYYYY'], YEAR); | |
addParseToken('YYYY', function (input, array) { | |
array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); | |
}); | |
addParseToken('YY', function (input, array) { | |
array[YEAR] = hooks.parseTwoDigitYear(input); | |
}); | |
addParseToken('Y', function (input, array) { | |
array[YEAR] = parseInt(input, 10); | |
}); | |
// HELPERS | |
function daysInYear(year) { | |
return isLeapYear(year) ? 366 : 365; | |
} | |
function isLeapYear(year) { | |
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; | |
} | |
// HOOKS | |
hooks.parseTwoDigitYear = function (input) { | |
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); | |
}; | |
// MOMENTS | |
var getSetYear = makeGetSet('FullYear', true); | |
function getIsLeapYear () { | |
return isLeapYear(this.year()); | |
} | |
function makeGetSet (unit, keepTime) { | |
return function (value) { | |
if (value != null) { | |
set$1(this, unit, value); | |
hooks.updateOffset(this, keepTime); | |
return this; | |
} else { | |
return get(this, unit); | |
} | |
}; | |
} | |
function get (mom, unit) { | |
return mom.isValid() ? | |
mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; | |
} | |
function set$1 (mom, unit, value) { | |
if (mom.isValid() && !isNaN(value)) { | |
if (unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { | |
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month())); | |
} | |
else { | |
mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); | |
} | |
} | |
} | |
// MOMENTS | |
function stringGet (units) { | |
units = normalizeUnits(units); | |
if (isFunction(this[units])) { | |
return this[units](); | |
} | |
return this; | |
} | |
function stringSet (units, value) { | |
if (typeof units === 'object') { | |
units = normalizeObjectUnits(units); | |
var prioritized = getPrioritizedUnits(units); | |
for (var i = 0; i < prioritized.length; i++) { | |
this[prioritized[i].unit](units[prioritized[i].unit]); | |
} | |
} else { | |
units = normalizeUnits(units); | |
if (isFunction(this[units])) { | |
return this[units](value); | |
} | |
} | |
return this; | |
} | |
function mod(n, x) { | |
return ((n % x) + x) % x; | |
} | |
var indexOf; | |
if (Array.prototype.indexOf) { | |
indexOf = Array.prototype.indexOf; | |
} else { | |
indexOf = function (o) { | |
// I know | |
var i; | |
for (i = 0; i < this.length; ++i) { | |
if (this[i] === o) { | |
return i; | |
} | |
} | |
return -1; | |
}; | |
} | |
function daysInMonth(year, month) { | |
if (isNaN(year) || isNaN(month)) { | |
return NaN; | |
} | |
var modMonth = mod(month, 12); | |
year += (month - modMonth) / 12; | |
return modMonth === 1 ? (isLeapYear(year) ? 29 : 28) : (31 - modMonth % 7 % 2); | |
} | |
// FORMATTING | |
addFormatToken('M', ['MM', 2], 'Mo', function () { | |
return this.month() + 1; | |
}); | |
addFormatToken('MMM', 0, 0, function (format) { | |
return this.localeData().monthsShort(this, format); | |
}); | |
addFormatToken('MMMM', 0, 0, function (format) { | |
return this.localeData().months(this, format); | |
}); | |
// ALIASES | |
addUnitAlias('month', 'M'); | |
// PRIORITY | |
addUnitPriority('month', 8); | |
// PARSING | |
addRegexToken('M', match1to2); | |
addRegexToken('MM', match1to2, match2); | |
addRegexToken('MMM', function (isStrict, locale) { | |
return locale.monthsShortRegex(isStrict); | |
}); | |
addRegexToken('MMMM', function (isStrict, locale) { | |
return locale.monthsRegex(isStrict); | |
}); | |
addParseToken(['M', 'MM'], function (input, array) { | |
array[MONTH] = toInt(input) - 1; | |
}); | |
addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { | |
var month = config._locale.monthsParse(input, token, config._strict); | |
// if we didn't find a month name, mark the date as invalid. | |
if (month != null) { | |
array[MONTH] = month; | |
} else { | |
getParsingFlags(config).invalidMonth = input; | |
} | |
}); | |
// LOCALES | |
var MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/; | |
var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'); | |
function localeMonths (m, format) { | |
if (!m) { | |
return isArray(this._months) ? this._months : | |
this._months['standalone']; | |
} | |
return isArray(this._months) ? this._months[m.month()] : | |
this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()]; | |
} | |
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'); | |
function localeMonthsShort (m, format) { | |
if (!m) { | |
return isArray(this._monthsShort) ? this._monthsShort : | |
this._monthsShort['standalone']; | |
} | |
return isArray(this._monthsShort) ? this._monthsShort[m.month()] : | |
this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()]; | |
} | |
function handleStrictParse(monthName, format, strict) { | |
var i, ii, mom, llc = monthName.toLocaleLowerCase(); | |
if (!this._monthsParse) { | |
// this is not used | |
this._monthsParse = []; | |
this._longMonthsParse = []; | |
this._shortMonthsParse = []; | |
for (i = 0; i < 12; ++i) { | |
mom = createUTC([2000, i]); | |
this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(); | |
this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); | |
} | |
} | |
if (strict) { | |
if (format === 'MMM') { | |
ii = indexOf.call(this._shortMonthsParse, llc); | |
return ii !== -1 ? ii : null; | |
} else { | |
ii = indexOf.call(this._longMonthsParse, llc); | |
return ii !== -1 ? ii : null; | |
} | |
} else { | |
if (format === 'MMM') { | |
ii = indexOf.call(this._shortMonthsParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._longMonthsParse, llc); | |
return ii !== -1 ? ii : null; | |
} else { | |
ii = indexOf.call(this._longMonthsParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._shortMonthsParse, llc); | |
return ii !== -1 ? ii : null; | |
} | |
} | |
} | |
function localeMonthsParse (monthName, format, strict) { | |
var i, mom, regex; | |
if (this._monthsParseExact) { | |
return handleStrictParse.call(this, monthName, format, strict); | |
} | |
if (!this._monthsParse) { | |
this._monthsParse = []; | |
this._longMonthsParse = []; | |
this._shortMonthsParse = []; | |
} | |
// TODO: add sorting | |
// Sorting makes sure if one month (or abbr) is a prefix of another | |
// see sorting in computeMonthsParse | |
for (i = 0; i < 12; i++) { | |
// make the regex if we don't have it already | |
mom = createUTC([2000, i]); | |
if (strict && !this._longMonthsParse[i]) { | |
this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); | |
this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); | |
} | |
if (!strict && !this._monthsParse[i]) { | |
regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); | |
this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); | |
} | |
// test the regex | |
if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { | |
return i; | |
} else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { | |
return i; | |
} else if (!strict && this._monthsParse[i].test(monthName)) { | |
return i; | |
} | |
} | |
} | |
// MOMENTS | |
function setMonth (mom, value) { | |
var dayOfMonth; | |
if (!mom.isValid()) { | |
// No op | |
return mom; | |
} | |
if (typeof value === 'string') { | |
if (/^\d+$/.test(value)) { | |
value = toInt(value); | |
} else { | |
value = mom.localeData().monthsParse(value); | |
// TODO: Another silent failure? | |
if (!isNumber(value)) { | |
return mom; | |
} | |
} | |
} | |
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); | |
mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); | |
return mom; | |
} | |
function getSetMonth (value) { | |
if (value != null) { | |
setMonth(this, value); | |
hooks.updateOffset(this, true); | |
return this; | |
} else { | |
return get(this, 'Month'); | |
} | |
} | |
function getDaysInMonth () { | |
return daysInMonth(this.year(), this.month()); | |
} | |
var defaultMonthsShortRegex = matchWord; | |
function monthsShortRegex (isStrict) { | |
if (this._monthsParseExact) { | |
if (!hasOwnProp(this, '_monthsRegex')) { | |
computeMonthsParse.call(this); | |
} | |
if (isStrict) { | |
return this._monthsShortStrictRegex; | |
} else { | |
return this._monthsShortRegex; | |
} | |
} else { | |
if (!hasOwnProp(this, '_monthsShortRegex')) { | |
this._monthsShortRegex = defaultMonthsShortRegex; | |
} | |
return this._monthsShortStrictRegex && isStrict ? | |
this._monthsShortStrictRegex : this._monthsShortRegex; | |
} | |
} | |
var defaultMonthsRegex = matchWord; | |
function monthsRegex (isStrict) { | |
if (this._monthsParseExact) { | |
if (!hasOwnProp(this, '_monthsRegex')) { | |
computeMonthsParse.call(this); | |
} | |
if (isStrict) { | |
return this._monthsStrictRegex; | |
} else { | |
return this._monthsRegex; | |
} | |
} else { | |
if (!hasOwnProp(this, '_monthsRegex')) { | |
this._monthsRegex = defaultMonthsRegex; | |
} | |
return this._monthsStrictRegex && isStrict ? | |
this._monthsStrictRegex : this._monthsRegex; | |
} | |
} | |
function computeMonthsParse () { | |
function cmpLenRev(a, b) { | |
return b.length - a.length; | |
} | |
var shortPieces = [], longPieces = [], mixedPieces = [], | |
i, mom; | |
for (i = 0; i < 12; i++) { | |
// make the regex if we don't have it already | |
mom = createUTC([2000, i]); | |
shortPieces.push(this.monthsShort(mom, '')); | |
longPieces.push(this.months(mom, '')); | |
mixedPieces.push(this.months(mom, '')); | |
mixedPieces.push(this.monthsShort(mom, '')); | |
} | |
// Sorting makes sure if one month (or abbr) is a prefix of another it | |
// will match the longer piece. | |
shortPieces.sort(cmpLenRev); | |
longPieces.sort(cmpLenRev); | |
mixedPieces.sort(cmpLenRev); | |
for (i = 0; i < 12; i++) { | |
shortPieces[i] = regexEscape(shortPieces[i]); | |
longPieces[i] = regexEscape(longPieces[i]); | |
} | |
for (i = 0; i < 24; i++) { | |
mixedPieces[i] = regexEscape(mixedPieces[i]); | |
} | |
this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); | |
this._monthsShortRegex = this._monthsRegex; | |
this._monthsStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); | |
this._monthsShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); | |
} | |
function createDate (y, m, d, h, M, s, ms) { | |
// can't just apply() to create a date: | |
// https://stackoverflow.com/q/181348 | |
var date = new Date(y, m, d, h, M, s, ms); | |
// the date constructor remaps years 0-99 to 1900-1999 | |
if (y < 100 && y >= 0 && isFinite(date.getFullYear())) { | |
date.setFullYear(y); | |
} | |
return date; | |
} | |
function createUTCDate (y) { | |
var date = new Date(Date.UTC.apply(null, arguments)); | |
// the Date.UTC function remaps years 0-99 to 1900-1999 | |
if (y < 100 && y >= 0 && isFinite(date.getUTCFullYear())) { | |
date.setUTCFullYear(y); | |
} | |
return date; | |
} | |
// start-of-first-week - start-of-year | |
function firstWeekOffset(year, dow, doy) { | |
var // first-week day -- which january is always in the first week (4 for iso, 1 for other) | |
fwd = 7 + dow - doy, | |
// first-week day local weekday -- which local weekday is fwd | |
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; | |
return -fwdlw + fwd - 1; | |
} | |
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday | |
function dayOfYearFromWeeks(year, week, weekday, dow, doy) { | |
var localWeekday = (7 + weekday - dow) % 7, | |
weekOffset = firstWeekOffset(year, dow, doy), | |
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, | |
resYear, resDayOfYear; | |
if (dayOfYear <= 0) { | |
resYear = year - 1; | |
resDayOfYear = daysInYear(resYear) + dayOfYear; | |
} else if (dayOfYear > daysInYear(year)) { | |
resYear = year + 1; | |
resDayOfYear = dayOfYear - daysInYear(year); | |
} else { | |
resYear = year; | |
resDayOfYear = dayOfYear; | |
} | |
return { | |
year: resYear, | |
dayOfYear: resDayOfYear | |
}; | |
} | |
function weekOfYear(mom, dow, doy) { | |
var weekOffset = firstWeekOffset(mom.year(), dow, doy), | |
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, | |
resWeek, resYear; | |
if (week < 1) { | |
resYear = mom.year() - 1; | |
resWeek = week + weeksInYear(resYear, dow, doy); | |
} else if (week > weeksInYear(mom.year(), dow, doy)) { | |
resWeek = week - weeksInYear(mom.year(), dow, doy); | |
resYear = mom.year() + 1; | |
} else { | |
resYear = mom.year(); | |
resWeek = week; | |
} | |
return { | |
week: resWeek, | |
year: resYear | |
}; | |
} | |
function weeksInYear(year, dow, doy) { | |
var weekOffset = firstWeekOffset(year, dow, doy), | |
weekOffsetNext = firstWeekOffset(year + 1, dow, doy); | |
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; | |
} | |
// FORMATTING | |
addFormatToken('w', ['ww', 2], 'wo', 'week'); | |
addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); | |
// ALIASES | |
addUnitAlias('week', 'w'); | |
addUnitAlias('isoWeek', 'W'); | |
// PRIORITIES | |
addUnitPriority('week', 5); | |
addUnitPriority('isoWeek', 5); | |
// PARSING | |
addRegexToken('w', match1to2); | |
addRegexToken('ww', match1to2, match2); | |
addRegexToken('W', match1to2); | |
addRegexToken('WW', match1to2, match2); | |
addWeekParseToken(['w', 'ww', 'W', 'WW'], function (input, week, config, token) { | |
week[token.substr(0, 1)] = toInt(input); | |
}); | |
// HELPERS | |
// LOCALES | |
function localeWeek (mom) { | |
return weekOfYear(mom, this._week.dow, this._week.doy).week; | |
} | |
var defaultLocaleWeek = { | |
dow : 0, // Sunday is the first day of the week. | |
doy : 6 // The week that contains Jan 1st is the first week of the year. | |
}; | |
function localeFirstDayOfWeek () { | |
return this._week.dow; | |
} | |
function localeFirstDayOfYear () { | |
return this._week.doy; | |
} | |
// MOMENTS | |
function getSetWeek (input) { | |
var week = this.localeData().week(this); | |
return input == null ? week : this.add((input - week) * 7, 'd'); | |
} | |
function getSetISOWeek (input) { | |
var week = weekOfYear(this, 1, 4).week; | |
return input == null ? week : this.add((input - week) * 7, 'd'); | |
} | |
// FORMATTING | |
addFormatToken('d', 0, 'do', 'day'); | |
addFormatToken('dd', 0, 0, function (format) { | |
return this.localeData().weekdaysMin(this, format); | |
}); | |
addFormatToken('ddd', 0, 0, function (format) { | |
return this.localeData().weekdaysShort(this, format); | |
}); | |
addFormatToken('dddd', 0, 0, function (format) { | |
return this.localeData().weekdays(this, format); | |
}); | |
addFormatToken('e', 0, 0, 'weekday'); | |
addFormatToken('E', 0, 0, 'isoWeekday'); | |
// ALIASES | |
addUnitAlias('day', 'd'); | |
addUnitAlias('weekday', 'e'); | |
addUnitAlias('isoWeekday', 'E'); | |
// PRIORITY | |
addUnitPriority('day', 11); | |
addUnitPriority('weekday', 11); | |
addUnitPriority('isoWeekday', 11); | |
// PARSING | |
addRegexToken('d', match1to2); | |
addRegexToken('e', match1to2); | |
addRegexToken('E', match1to2); | |
addRegexToken('dd', function (isStrict, locale) { | |
return locale.weekdaysMinRegex(isStrict); | |
}); | |
addRegexToken('ddd', function (isStrict, locale) { | |
return locale.weekdaysShortRegex(isStrict); | |
}); | |
addRegexToken('dddd', function (isStrict, locale) { | |
return locale.weekdaysRegex(isStrict); | |
}); | |
addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { | |
var weekday = config._locale.weekdaysParse(input, token, config._strict); | |
// if we didn't get a weekday name, mark the date as invalid | |
if (weekday != null) { | |
week.d = weekday; | |
} else { | |
getParsingFlags(config).invalidWeekday = input; | |
} | |
}); | |
addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { | |
week[token] = toInt(input); | |
}); | |
// HELPERS | |
function parseWeekday(input, locale) { | |
if (typeof input !== 'string') { | |
return input; | |
} | |
if (!isNaN(input)) { | |
return parseInt(input, 10); | |
} | |
input = locale.weekdaysParse(input); | |
if (typeof input === 'number') { | |
return input; | |
} | |
return null; | |
} | |
function parseIsoWeekday(input, locale) { | |
if (typeof input === 'string') { | |
return locale.weekdaysParse(input) % 7 || 7; | |
} | |
return isNaN(input) ? null : input; | |
} | |
// LOCALES | |
var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); | |
function localeWeekdays (m, format) { | |
if (!m) { | |
return isArray(this._weekdays) ? this._weekdays : | |
this._weekdays['standalone']; | |
} | |
return isArray(this._weekdays) ? this._weekdays[m.day()] : | |
this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; | |
} | |
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); | |
function localeWeekdaysShort (m) { | |
return (m) ? this._weekdaysShort[m.day()] : this._weekdaysShort; | |
} | |
var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); | |
function localeWeekdaysMin (m) { | |
return (m) ? this._weekdaysMin[m.day()] : this._weekdaysMin; | |
} | |
function handleStrictParse$1(weekdayName, format, strict) { | |
var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); | |
if (!this._weekdaysParse) { | |
this._weekdaysParse = []; | |
this._shortWeekdaysParse = []; | |
this._minWeekdaysParse = []; | |
for (i = 0; i < 7; ++i) { | |
mom = createUTC([2000, 1]).day(i); | |
this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); | |
this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); | |
this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); | |
} | |
} | |
if (strict) { | |
if (format === 'dddd') { | |
ii = indexOf.call(this._weekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} else if (format === 'ddd') { | |
ii = indexOf.call(this._shortWeekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} else { | |
ii = indexOf.call(this._minWeekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} | |
} else { | |
if (format === 'dddd') { | |
ii = indexOf.call(this._weekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._shortWeekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._minWeekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} else if (format === 'ddd') { | |
ii = indexOf.call(this._shortWeekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._weekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._minWeekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} else { | |
ii = indexOf.call(this._minWeekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._weekdaysParse, llc); | |
if (ii !== -1) { | |
return ii; | |
} | |
ii = indexOf.call(this._shortWeekdaysParse, llc); | |
return ii !== -1 ? ii : null; | |
} | |
} | |
} | |
function localeWeekdaysParse (weekdayName, format, strict) { | |
var i, mom, regex; | |
if (this._weekdaysParseExact) { | |
return handleStrictParse$1.call(this, weekdayName, format, strict); | |
} | |
if (!this._weekdaysParse) { | |
this._weekdaysParse = []; | |
this._minWeekdaysParse = []; | |
this._shortWeekdaysParse = []; | |
this._fullWeekdaysParse = []; | |
} | |
for (i = 0; i < 7; i++) { | |
// make the regex if we don't have it already | |
mom = createUTC([2000, 1]).day(i); | |
if (strict && !this._fullWeekdaysParse[i]) { | |
this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); | |
this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); | |
this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); | |
} | |
if (!this._weekdaysParse[i]) { | |
regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); | |
this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); | |
} | |
// test the regex | |
if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { | |
return i; | |
} else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { | |
return i; | |
} else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { | |
return i; | |
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) { | |
return i; | |
} | |
} | |
} | |
// MOMENTS | |
function getSetDayOfWeek (input) { | |
if (!this.isValid()) { | |
return input != null ? this : NaN; | |
} | |
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); | |
if (input != null) { | |
input = parseWeekday(input, this.localeData()); | |
return this.add(input - day, 'd'); | |
} else { | |
return day; | |
} | |
} | |
function getSetLocaleDayOfWeek (input) { | |
if (!this.isValid()) { | |
return input != null ? this : NaN; | |
} | |
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; | |
return input == null ? weekday : this.add(input - weekday, 'd'); | |
} | |
function getSetISODayOfWeek (input) { | |
if (!this.isValid()) { | |
return input != null ? this : NaN; | |
} | |
// behaves the same as moment#day except | |
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) | |
// as a setter, sunday should belong to the previous week. | |
if (input != null) { | |
var weekday = parseIsoWeekday(input, this.localeData()); | |
return this.day(this.day() % 7 ? weekday : weekday - 7); | |
} else { | |
return this.day() || 7; | |
} | |
} | |
var defaultWeekdaysRegex = matchWord; | |
function weekdaysRegex (isStrict) { | |
if (this._weekdaysParseExact) { | |
if (!hasOwnProp(this, '_weekdaysRegex')) { | |
computeWeekdaysParse.call(this); | |
} | |
if (isStrict) { | |
return this._weekdaysStrictRegex; | |
} else { | |
return this._weekdaysRegex; | |
} | |
} else { | |
if (!hasOwnProp(this, '_weekdaysRegex')) { | |
this._weekdaysRegex = defaultWeekdaysRegex; | |
} | |
return this._weekdaysStrictRegex && isStrict ? | |
this._weekdaysStrictRegex : this._weekdaysRegex; | |
} | |
} | |
var defaultWeekdaysShortRegex = matchWord; | |
function weekdaysShortRegex (isStrict) { | |
if (this._weekdaysParseExact) { | |
if (!hasOwnProp(this, '_weekdaysRegex')) { | |
computeWeekdaysParse.call(this); | |
} | |
if (isStrict) { | |
return this._weekdaysShortStrictRegex; | |
} else { | |
return this._weekdaysShortRegex; | |
} | |
} else { | |
if (!hasOwnProp(this, '_weekdaysShortRegex')) { | |
this._weekdaysShortRegex = defaultWeekdaysShortRegex; | |
} | |
return this._weekdaysShortStrictRegex && isStrict ? | |
this._weekdaysShortStrictRegex : this._weekdaysShortRegex; | |
} | |
} | |
var defaultWeekdaysMinRegex = matchWord; | |
function weekdaysMinRegex (isStrict) { | |
if (this._weekdaysParseExact) { | |
if (!hasOwnProp(this, '_weekdaysRegex')) { | |
computeWeekdaysParse.call(this); | |
} | |
if (isStrict) { | |
return this._weekdaysMinStrictRegex; | |
} else { | |
return this._weekdaysMinRegex; | |
} | |
} else { | |
if (!hasOwnProp(this, '_weekdaysMinRegex')) { | |
this._weekdaysMinRegex = defaultWeekdaysMinRegex; | |
} | |
return this._weekdaysMinStrictRegex && isStrict ? | |
this._weekdaysMinStrictRegex : this._weekdaysMinRegex; | |
} | |
} | |
function computeWeekdaysParse () { | |
function cmpLenRev(a, b) { | |
return b.length - a.length; | |
} | |
var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], | |
i, mom, minp, shortp, longp; | |
for (i = 0; i < 7; i++) { | |
// make the regex if we don't have it already | |
mom = createUTC([2000, 1]).day(i); | |
minp = this.weekdaysMin(mom, ''); | |
shortp = this.weekdaysShort(mom, ''); | |
longp = this.weekdays(mom, ''); | |
minPieces.push(minp); | |
shortPieces.push(shortp); | |
longPieces.push(longp); | |
mixedPieces.push(minp); | |
mixedPieces.push(shortp); | |
mixedPieces.push(longp); | |
} | |
// Sorting makes sure if one weekday (or abbr) is a prefix of another it | |
// will match the longer piece. | |
minPieces.sort(cmpLenRev); | |
shortPieces.sort(cmpLenRev); | |
longPieces.sort(cmpLenRev); | |
mixedPieces.sort(cmpLenRev); | |
for (i = 0; i < 7; i++) { | |
shortPieces[i] = regexEscape(shortPieces[i]); | |
longPieces[i] = regexEscape(longPieces[i]); | |
mixedPieces[i] = regexEscape(mixedPieces[i]); | |
} | |
this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); | |
this._weekdaysShortRegex = this._weekdaysRegex; | |
this._weekdaysMinRegex = this._weekdaysRegex; | |
this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); | |
this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); | |
this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); | |
} | |
// FORMATTING | |
function hFormat() { | |
return this.hours() % 12 || 12; | |
} | |
function kFormat() { | |
return this.hours() || 24; | |
} | |
addFormatToken('H', ['HH', 2], 0, 'hour'); | |
addFormatToken('h', ['hh', 2], 0, hFormat); | |
addFormatToken('k', ['kk', 2], 0, kFormat); | |
addFormatToken('hmm', 0, 0, function () { | |
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); | |
}); | |
addFormatToken('hmmss', 0, 0, function () { | |
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + | |
zeroFill(this.seconds(), 2); | |
}); | |
addFormatToken('Hmm', 0, 0, function () { | |
return '' + this.hours() + zeroFill(this.minutes(), 2); | |
}); | |
addFormatToken('Hmmss', 0, 0, function () { | |
return '' + this.hours() + zeroFill(this.minutes(), 2) + | |
zeroFill(this.seconds(), 2); | |
}); | |
function meridiem (token, lowercase) { | |
addFormatToken(token, 0, 0, function () { | |
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase); | |
}); | |
} | |
meridiem('a', true); | |
meridiem('A', false); | |
// ALIASES | |
addUnitAlias('hour', 'h'); | |
// PRIORITY | |
addUnitPriority('hour', 13); | |
// PARSING | |
function matchMeridiem (isStrict, locale) { | |
return locale._meridiemParse; | |
} | |
addRegexToken('a', matchMeridiem); | |
addRegexToken('A', matchMeridiem); | |
addRegexToken('H', match1to2); | |
addRegexToken('h', match1to2); | |
addRegexToken('k', match1to2); | |
addRegexToken('HH', match1to2, match2); | |
addRegexToken('hh', match1to2, match2); | |
addRegexToken('kk', match1to2, match2); | |
addRegexToken('hmm', match3to4); | |
addRegexToken('hmmss', match5to6); | |
addRegexToken('Hmm', match3to4); | |
addRegexToken('Hmmss', match5to6); | |
addParseToken(['H', 'HH'], HOUR); | |
addParseToken(['k', 'kk'], function (input, array, config) { | |
var kInput = toInt(input); | |
array[HOUR] = kInput === 24 ? 0 : kInput; | |
}); | |
addParseToken(['a', 'A'], function (input, array, config) { | |
config._isPm = config._locale.isPM(input); | |
config._meridiem = input; | |
}); | |
addParseToken(['h', 'hh'], function (input, array, config) { | |
array[HOUR] = toInt(input); | |
getParsingFlags(config).bigHour = true; | |
}); | |
addParseToken('hmm', function (input, array, config) { | |
var pos = input.length - 2; | |
array[HOUR] = toInt(input.substr(0, pos)); | |
array[MINUTE] = toInt(input.substr(pos)); | |
getParsingFlags(config).bigHour = true; | |
}); | |
addParseToken('hmmss', function (input, array, config) { | |
var pos1 = input.length - 4; | |
var pos2 = input.length - 2; | |
array[HOUR] = toInt(input.substr(0, pos1)); | |
array[MINUTE] = toInt(input.substr(pos1, 2)); | |
array[SECOND] = toInt(input.substr(pos2)); | |
getParsingFlags(config).bigHour = true; | |
}); | |
addParseToken('Hmm', function (input, array, config) { | |
var pos = input.length - 2; | |
array[HOUR] = toInt(input.substr(0, pos)); | |
array[MINUTE] = toInt(input.substr(pos)); | |
}); | |
addParseToken('Hmmss', function (input, array, config) { | |
var pos1 = input.length - 4; | |
var pos2 = input.length - 2; | |
array[HOUR] = toInt(input.substr(0, pos1)); | |
array[MINUTE] = toInt(input.substr(pos1, 2)); | |
array[SECOND] = toInt(input.substr(pos2)); | |
}); | |
// LOCALES | |
function localeIsPM (input) { | |
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays | |
// Using charAt should be more compatible. | |
return ((input + '').toLowerCase().charAt(0) === 'p'); | |
} | |
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i; | |
function localeMeridiem (hours, minutes, isLower) { | |
if (hours > 11) { | |
return isLower ? 'pm' : 'PM'; | |
} else { | |
return isLower ? 'am' : 'AM'; | |
} | |
} | |
// MOMENTS | |
// Setting the hour should keep the time, because the user explicitly | |
// specified which hour he wants. So trying to maintain the same hour (in | |
// a new timezone) makes sense. Adding/subtracting hours does not follow | |
// this rule. | |
var getSetHour = makeGetSet('Hours', true); | |
// months | |
// week | |
// weekdays | |
// meridiem | |
var baseConfig = { | |
calendar: defaultCalendar, | |
longDateFormat: defaultLongDateFormat, | |
invalidDate: defaultInvalidDate, | |
ordinal: defaultOrdinal, | |
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, | |
relativeTime: defaultRelativeTime, | |
months: defaultLocaleMonths, | |
monthsShort: defaultLocaleMonthsShort, | |
week: defaultLocaleWeek, | |
weekdays: defaultLocaleWeekdays, | |
weekdaysMin: defaultLocaleWeekdaysMin, | |
weekdaysShort: defaultLocaleWeekdaysShort, | |
meridiemParse: defaultLocaleMeridiemParse | |
}; | |
// internal storage for locale config files | |
var locales = {}; | |
var localeFamilies = {}; | |
var globalLocale; | |
function normalizeLocale(key) { | |
return key ? key.toLowerCase().replace('_', '-') : key; | |
} | |
// pick the locale from the array | |
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each | |
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root | |
function chooseLocale(names) { | |
var i = 0, j, next, locale, split; | |
while (i < names.length) { | |
split = normalizeLocale(names[i]).split('-'); | |
j = split.length; | |
next = normalizeLocale(names[i + 1]); | |
next = next ? next.split('-') : null; | |
while (j > 0) { | |
locale = loadLocale(split.slice(0, j).join('-')); | |
if (locale) { | |
return locale; | |
} | |
if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { | |
//the next array item is better than a shallower substring of this one | |
break; | |
} | |
j--; | |
} | |
i++; | |
} | |
return null; | |
} | |
function loadLocale(name) { | |
var oldLocale = null; | |
// TODO: Find a better way to register and load all the locales in Node | |
if (!locales[name] && (typeof module !== 'undefined') && | |
module && module.exports) { | |
try { | |
oldLocale = globalLocale._abbr; | |
var aliasedRequire = require; | |
__webpack_require__(436)("./" + name); | |
getSetGlobalLocale(oldLocale); | |
} catch (e) {} | |
} | |
return locales[name]; | |
} | |
// This function will load locale and then set the global locale. If | |
// no arguments are passed in, it will simply return the current global | |
// locale key. | |
function getSetGlobalLocale (key, values) { | |
var data; | |
if (key) { | |
if (isUndefined(values)) { | |
data = getLocale(key); | |
} | |
else { | |
data = defineLocale(key, values); | |
} | |
if (data) { | |
// moment.duration._locale = moment._locale = data; | |
globalLocale = data; | |
} | |
} | |
return globalLocale._abbr; | |
} | |
function defineLocale (name, config) { | |
if (config !== null) { | |
var parentConfig = baseConfig; | |
config.abbr = name; | |
if (locales[name] != null) { | |
deprecateSimple('defineLocaleOverride', | |
'use moment.updateLocale(localeName, config) to change ' + | |
'an existing locale. moment.defineLocale(localeName, ' + | |
'config) should only be used for creating a new locale ' + | |
'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.'); | |
parentConfig = locales[name]._config; | |
} else if (config.parentLocale != null) { | |
if (locales[config.parentLocale] != null) { | |
parentConfig = locales[config.parentLocale]._config; | |
} else { | |
if (!localeFamilies[config.parentLocale]) { | |
localeFamilies[config.parentLocale] = []; | |
} | |
localeFamilies[config.parentLocale].push({ | |
name: name, | |
config: config | |
}); | |
return null; | |
} | |
} | |
locales[name] = new Locale(mergeConfigs(parentConfig, config)); | |
if (localeFamilies[name]) { | |
localeFamilies[name].forEach(function (x) { | |
defineLocale(x.name, x.config); | |
}); | |
} | |
// backwards compat for now: also set the locale | |
// make sure we set the locale AFTER all child locales have been | |
// created, so we won't end up with the child locale set. | |
getSetGlobalLocale(name); | |
return locales[name]; | |
} else { | |
// useful for testing | |
delete locales[name]; | |
return null; | |
} | |
} | |
function updateLocale(name, config) { | |
if (config != null) { | |
var locale, tmpLocale, parentConfig = baseConfig; | |
// MERGE | |
tmpLocale = loadLocale(name); | |
if (tmpLocale != null) { | |
parentConfig = tmpLocale._config; | |
} | |
config = mergeConfigs(parentConfig, config); | |
locale = new Locale(config); | |
locale.parentLocale = locales[name]; | |
locales[name] = locale; | |
// backwards compat for now: also set the locale | |
getSetGlobalLocale(name); | |
} else { | |
// pass null for config to unupdate, useful for tests | |
if (locales[name] != null) { | |
if (locales[name].parentLocale != null) { | |
locales[name] = locales[name].parentLocale; | |
} else if (locales[name] != null) { | |
delete locales[name]; | |
} | |
} | |
} | |
return locales[name]; | |
} | |
// returns locale data | |
function getLocale (key) { | |
var locale; | |
if (key && key._locale && key._locale._abbr) { | |
key = key._locale._abbr; | |
} | |
if (!key) { | |
return globalLocale; | |
} | |
if (!isArray(key)) { | |
//short-circuit everything else | |
locale = loadLocale(key); | |
if (locale) { | |
return locale; | |
} | |
key = [key]; | |
} | |
return chooseLocale(key); | |
} | |
function listLocales() { | |
return keys(locales); | |
} | |
function checkOverflow (m) { | |
var overflow; | |
var a = m._a; | |
if (a && getParsingFlags(m).overflow === -2) { | |
overflow = | |
a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : | |
a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : | |
a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : | |
a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : | |
a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : | |
a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : | |
-1; | |
if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { | |
overflow = DATE; | |
} | |
if (getParsingFlags(m)._overflowWeeks && overflow === -1) { | |
overflow = WEEK; | |
} | |
if (getParsingFlags(m)._overflowWeekday && overflow === -1) { | |
overflow = WEEKDAY; | |
} | |
getParsingFlags(m).overflow = overflow; | |
} | |
return m; | |
} | |
// Pick the first defined of two or three arguments. | |
function defaults(a, b, c) { | |
if (a != null) { | |
return a; | |
} | |
if (b != null) { | |
return b; | |
} | |
return c; | |
} | |
function currentDateArray(config) { | |
// hooks is actually the exported moment object | |
var nowValue = new Date(hooks.now()); | |
if (config._useUTC) { | |
return [nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate()]; | |
} | |
return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; | |
} | |
// convert an array to a date. | |
// the array should mirror the parameters below | |
// note: all values past the year are optional and will default to the lowest possible value. | |
// [year, month, day , hour, minute, second, millisecond] | |
function configFromArray (config) { | |
var i, date, input = [], currentDate, expectedWeekday, yearToUse; | |
if (config._d) { | |
return; | |
} | |
currentDate = currentDateArray(config); | |
//compute day of the year from weeks and weekdays | |
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { | |
dayOfYearFromWeekInfo(config); | |
} | |
//if the day of the year is set, figure out what it is | |
if (config._dayOfYear != null) { | |
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); | |
if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { | |
getParsingFlags(config)._overflowDayOfYear = true; | |
} | |
date = createUTCDate(yearToUse, 0, config._dayOfYear); | |
config._a[MONTH] = date.getUTCMonth(); | |
config._a[DATE] = date.getUTCDate(); | |
} | |
// Default to current date. | |
// * if no year, month, day of month are given, default to today | |
// * if day of month is given, default month and year | |
// * if month is given, default only year | |
// * if year is given, don't default anything | |
for (i = 0; i < 3 && config._a[i] == null; ++i) { | |
config._a[i] = input[i] = currentDate[i]; | |
} | |
// Zero out whatever was not defaulted, including time | |
for (; i < 7; i++) { | |
config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; | |
} | |
// Check for 24:00:00.000 | |
if (config._a[HOUR] === 24 && | |
config._a[MINUTE] === 0 && | |
config._a[SECOND] === 0 && | |
config._a[MILLISECOND] === 0) { | |
config._nextDay = true; | |
config._a[HOUR] = 0; | |
} | |
config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input); | |
expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); | |
// Apply timezone offset from input. The actual utcOffset can be changed | |
// with parseZone. | |
if (config._tzm != null) { | |
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); | |
} | |
if (config._nextDay) { | |
config._a[HOUR] = 24; | |
} | |
// check for mismatching day of week | |
if (config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday) { | |
getParsingFlags(config).weekdayMismatch = true; | |
} | |
} | |
function dayOfYearFromWeekInfo(config) { | |
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow; | |
w = config._w; | |
if (w.GG != null || w.W != null || w.E != null) { | |
dow = 1; | |
doy = 4; | |
// TODO: We need to take the current isoWeekYear, but that depends on | |
// how we interpret now (local, utc, fixed offset). So create | |
// a now version of current config (take local/utc/offset flags, and | |
// create now). | |
weekYear = defaults(w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year); | |
week = defaults(w.W, 1); | |
weekday = defaults(w.E, 1); | |
if (weekday < 1 || weekday > 7) { | |
weekdayOverflow = true; | |
} | |
} else { | |
dow = config._locale._week.dow; | |
doy = config._locale._week.doy; | |
var curWeek = weekOfYear(createLocal(), dow, doy); | |
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); | |
// Default to current week. | |
week = defaults(w.w, curWeek.week); | |
if (w.d != null) { | |
// weekday -- low day numbers are considered next week | |
weekday = w.d; | |
if (weekday < 0 || weekday > 6) { | |
weekdayOverflow = true; | |
} | |
} else if (w.e != null) { | |
// local weekday -- counting starts from begining of week | |
weekday = w.e + dow; | |
if (w.e < 0 || w.e > 6) { | |
weekdayOverflow = true; | |
} | |
} else { | |
// default to begining of week | |
weekday = dow; | |
} | |
} | |
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { | |
getParsingFlags(config)._overflowWeeks = true; | |
} else if (weekdayOverflow != null) { | |
getParsingFlags(config)._overflowWeekday = true; | |
} else { | |
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); | |
config._a[YEAR] = temp.year; | |
config._dayOfYear = temp.dayOfYear; | |
} | |
} | |
// iso 8601 regex | |
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) | |
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; | |
var basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/; | |
var tzRegex = /Z|[+-]\d\d(?::?\d\d)?/; | |
var isoDates = [ | |
['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], | |
['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], | |
['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], | |
['GGGG-[W]WW', /\d{4}-W\d\d/, false], | |
['YYYY-DDD', /\d{4}-\d{3}/], | |
['YYYY-MM', /\d{4}-\d\d/, false], | |
['YYYYYYMMDD', /[+-]\d{10}/], | |
['YYYYMMDD', /\d{8}/], | |
// YYYYMM is NOT allowed by the standard | |
['GGGG[W]WWE', /\d{4}W\d{3}/], | |
['GGGG[W]WW', /\d{4}W\d{2}/, false], | |
['YYYYDDD', /\d{7}/] | |
]; | |
// iso time formats and regexes | |
var isoTimes = [ | |
['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], | |
['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], | |
['HH:mm:ss', /\d\d:\d\d:\d\d/], | |
['HH:mm', /\d\d:\d\d/], | |
['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], | |
['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], | |
['HHmmss', /\d\d\d\d\d\d/], | |
['HHmm', /\d\d\d\d/], | |
['HH', /\d\d/] | |
]; | |
var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i; | |
// date from iso format | |
function configFromISO(config) { | |
var i, l, | |
string = config._i, | |
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), | |
allowTime, dateFormat, timeFormat, tzFormat; | |
if (match) { | |
getParsingFlags(config).iso = true; | |
for (i = 0, l = isoDates.length; i < l; i++) { | |
if (isoDates[i][1].exec(match[1])) { | |
dateFormat = isoDates[i][0]; | |
allowTime = isoDates[i][2] !== false; | |
break; | |
} | |
} | |
if (dateFormat == null) { | |
config._isValid = false; | |
return; | |
} | |
if (match[3]) { | |
for (i = 0, l = isoTimes.length; i < l; i++) { | |
if (isoTimes[i][1].exec(match[3])) { | |
// match[2] should be 'T' or space | |
timeFormat = (match[2] || ' ') + isoTimes[i][0]; | |
break; | |
} | |
} | |
if (timeFormat == null) { | |
config._isValid = false; | |
return; | |
} | |
} | |
if (!allowTime && timeFormat != null) { | |
config._isValid = false; | |
return; | |
} | |
if (match[4]) { | |
if (tzRegex.exec(match[4])) { | |
tzFormat = 'Z'; | |
} else { | |
config._isValid = false; | |
return; | |
} | |
} | |
config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); | |
configFromStringAndFormat(config); | |
} else { | |
config._isValid = false; | |
} | |
} | |
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 | |
var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; | |
function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { | |
var result = [ | |
untruncateYear(yearStr), | |
defaultLocaleMonthsShort.indexOf(monthStr), | |
parseInt(dayStr, 10), | |
parseInt(hourStr, 10), | |
parseInt(minuteStr, 10) | |
]; | |
if (secondStr) { | |
result.push(parseInt(secondStr, 10)); | |
} | |
return result; | |
} | |
function untruncateYear(yearStr) { | |
var year = parseInt(yearStr, 10); | |
if (year <= 49) { | |
return 2000 + year; | |
} else if (year <= 999) { | |
return 1900 + year; | |
} | |
return year; | |
} | |
function preprocessRFC2822(s) { | |
// Remove comments and folding whitespace and replace multiple-spaces with a single space | |
return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim(); | |
} | |
function checkWeekday(weekdayStr, parsedInput, config) { | |
if (weekdayStr) { | |
// TODO: Replace the vanilla JS Date object with an indepentent day-of-week check. | |
var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), | |
weekdayActual = new Date(parsedInput[0], parsedInput[1], parsedInput[2]).getDay(); | |
if (weekdayProvided !== weekdayActual) { | |
getParsingFlags(config).weekdayMismatch = true; | |
config._isValid = false; | |
return false; | |
} | |
} | |
return true; | |
} | |
var obsOffsets = { | |
UT: 0, | |
GMT: 0, | |
EDT: -4 * 60, | |
EST: -5 * 60, | |
CDT: -5 * 60, | |
CST: -6 * 60, | |
MDT: -6 * 60, | |
MST: -7 * 60, | |
PDT: -7 * 60, | |
PST: -8 * 60 | |
}; | |
function calculateOffset(obsOffset, militaryOffset, numOffset) { | |
if (obsOffset) { | |
return obsOffsets[obsOffset]; | |
} else if (militaryOffset) { | |
// the only allowed military tz is Z | |
return 0; | |
} else { | |
var hm = parseInt(numOffset, 10); | |
var m = hm % 100, h = (hm - m) / 100; | |
return h * 60 + m; | |
} | |
} | |
// date and time from ref 2822 format | |
function configFromRFC2822(config) { | |
var match = rfc2822.exec(preprocessRFC2822(config._i)); | |
if (match) { | |
var parsedArray = extractFromRFC2822Strings(match[4], match[3], match[2], match[5], match[6], match[7]); | |
if (!checkWeekday(match[1], parsedArray, config)) { | |
return; | |
} | |
config._a = parsedArray; | |
config._tzm = calculateOffset(match[8], match[9], match[10]); | |
config._d = createUTCDate.apply(null, config._a); | |
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); | |
getParsingFlags(config).rfc2822 = true; | |
} else { | |
config._isValid = false; | |
} | |
} | |
// date from iso format or fallback | |
function configFromString(config) { | |
var matched = aspNetJsonRegex.exec(config._i); | |
if (matched !== null) { | |
config._d = new Date(+matched[1]); | |
return; | |
} | |
configFromISO(config); | |
if (config._isValid === false) { | |
delete config._isValid; | |
} else { | |
return; | |
} | |
configFromRFC2822(config); | |
if (config._isValid === false) { | |
delete config._isValid; | |
} else { | |
return; | |
} | |
// Final attempt, use Input Fallback | |
hooks.createFromInputFallback(config); | |
} | |
hooks.createFromInputFallback = deprecate( | |
'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + | |
'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + | |
'discouraged and will be removed in an upcoming major release. Please refer to ' + | |
'http://momentjs.com/guides/#/warnings/js-date/ for more info.', | |
function (config) { | |
config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); | |
} | |
); | |
// constant that refers to the ISO standard | |
hooks.ISO_8601 = function () {}; | |
// constant that refers to the RFC 2822 form | |
hooks.RFC_2822 = function () {}; | |
// date from string and format string | |
function configFromStringAndFormat(config) { | |
// TODO: Move this to another part of the creation flow to prevent circular deps | |
if (config._f === hooks.ISO_8601) { | |
configFromISO(config); | |
return; | |
} | |
if (config._f === hooks.RFC_2822) { | |
configFromRFC2822(config); | |
return; | |
} | |
config._a = []; | |
getParsingFlags(config).empty = true; | |
// This array is used to make a Date, either with `new Date` or `Date.UTC` | |
var string = '' + config._i, | |
i, parsedInput, tokens, token, skipped, | |
stringLength = string.length, | |
totalParsedInputLength = 0; | |
tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; | |
for (i = 0; i < tokens.length; i++) { | |
token = tokens[i]; | |
parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; | |
// console.log('token', token, 'parsedInput', parsedInput, | |
// 'regex', getParseRegexForToken(token, config)); | |
if (parsedInput) { | |
skipped = string.substr(0, string.indexOf(parsedInput)); | |
if (skipped.length > 0) { | |
getParsingFlags(config).unusedInput.push(skipped); | |
} | |
string = string.slice(string.indexOf(parsedInput) + parsedInput.length); | |
totalParsedInputLength += parsedInput.length; | |
} | |
// don't parse if it's not a known token | |
if (formatTokenFunctions[token]) { | |
if (parsedInput) { | |
getParsingFlags(config).empty = false; | |
} | |
else { | |
getParsingFlags(config).unusedTokens.push(token); | |
} | |
addTimeToArrayFromToken(token, parsedInput, config); | |
} | |
else if (config._strict && !parsedInput) { | |
getParsingFlags(config).unusedTokens.push(token); | |
} | |
} | |
// add remaining unparsed input length to the string | |
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; | |
if (string.length > 0) { | |
getParsingFlags(config).unusedInput.push(string); | |
} | |
// clear _12h flag if hour is <= 12 | |
if (config._a[HOUR] <= 12 && | |
getParsingFlags(config).bigHour === true && | |
config._a[HOUR] > 0) { | |
getParsingFlags(config).bigHour = undefined; | |
} | |
getParsingFlags(config).parsedDateParts = config._a.slice(0); | |
getParsingFlags(config).meridiem = config._meridiem; | |
// handle meridiem | |
config._a[HOUR] = meridiemFixWrap(config._locale, config._a[HOUR], config._meridiem); | |
configFromArray(config); | |
checkOverflow(config); | |
} | |
function meridiemFixWrap (locale, hour, meridiem) { | |
var isPm; | |
if (meridiem == null) { | |
// nothing to do | |
return hour; | |
} | |
if (locale.meridiemHour != null) { | |
return locale.meridiemHour(hour, meridiem); | |
} else if (locale.isPM != null) { | |
// Fallback | |
isPm = locale.isPM(meridiem); | |
if (isPm && hour < 12) { | |
hour += 12; | |
} | |
if (!isPm && hour === 12) { | |
hour = 0; | |
} | |
return hour; | |
} else { | |
// this is not supposed to happen | |
return hour; | |
} | |
} | |
// date from string and array of format strings | |
function configFromStringAndArray(config) { | |
var tempConfig, | |
bestMoment, | |
scoreToBeat, | |
i, | |
currentScore; | |
if (config._f.length === 0) { | |
getParsingFlags(config).invalidFormat = true; | |
config._d = new Date(NaN); | |
return; | |
} | |
for (i = 0; i < config._f.length; i++) { | |
currentScore = 0; | |
tempConfig = copyConfig({}, config); | |
if (config._useUTC != null) { | |
tempConfig._useUTC = config._useUTC; | |
} | |
tempConfig._f = config._f[i]; | |
configFromStringAndFormat(tempConfig); | |
if (!isValid(tempConfig)) { | |
continue; | |
} | |
// if there is any input that was not parsed add a penalty for that format | |
currentScore += getParsingFlags(tempConfig).charsLeftOver; | |
//or tokens | |
currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; | |
getParsingFlags(tempConfig).score = currentScore; | |
if (scoreToBeat == null || currentScore < scoreToBeat) { | |
scoreToBeat = currentScore; | |
bestMoment = tempConfig; | |
} | |
} | |
extend(config, bestMoment || tempConfig); | |
} | |
function configFromObject(config) { | |
if (config._d) { | |
return; | |
} | |
var i = normalizeObjectUnits(config._i); | |
config._a = map([i.year, i.month, i.day || i.date, i.hour, i.minute, i.second, i.millisecond], function (obj) { | |
return obj && parseInt(obj, 10); | |
}); | |
configFromArray(config); | |
} | |
function createFromConfig (config) { | |
var res = new Moment(checkOverflow(prepareConfig(config))); | |
if (res._nextDay) { | |
// Adding is smart enough around DST | |
res.add(1, 'd'); | |
res._nextDay = undefined; | |
} | |
return res; | |
} | |
function prepareConfig (config) { | |
var input = config._i, | |
format = config._f; | |
config._locale = config._locale || getLocale(config._l); | |
if (input === null || (format === undefined && input === '')) { | |
return createInvalid({nullInput: true}); | |
} | |
if (typeof input === 'string') { | |
config._i = input = config._locale.preparse(input); | |
} | |
if (isMoment(input)) { | |
return new Moment(checkOverflow(input)); | |
} else if (isDate(input)) { | |
config._d = input; | |
} else if (isArray(format)) { | |
configFromStringAndArray(config); | |
} else if (format) { | |
configFromStringAndFormat(config); | |
} else { | |
configFromInput(config); | |
} | |
if (!isValid(config)) { | |
config._d = null; | |
} | |
return config; | |
} | |
function configFromInput(config) { | |
var input = config._i; | |
if (isUndefined(input)) { | |
config._d = new Date(hooks.now()); | |
} else if (isDate(input)) { | |
config._d = new Date(input.valueOf()); | |
} else if (typeof input === 'string') { | |
configFromString(config); | |
} else if (isArray(input)) { | |
config._a = map(input.slice(0), function (obj) { | |
return parseInt(obj, 10); | |
}); | |
configFromArray(config); | |
} else if (isObject(input)) { | |
configFromObject(config); | |
} else if (isNumber(input)) { | |
// from milliseconds | |
config._d = new Date(input); | |
} else { | |
hooks.createFromInputFallback(config); | |
} | |
} | |
function createLocalOrUTC (input, format, locale, strict, isUTC) { | |
var c = {}; | |
if (locale === true || locale === false) { | |
strict = locale; | |
locale = undefined; | |
} | |
if ((isObject(input) && isObjectEmpty(input)) || | |
(isArray(input) && input.length === 0)) { | |
input = undefined; | |
} | |
// object construction must be done this way. | |
// https://github.com/moment/moment/issues/1423 | |
c._isAMomentObject = true; | |
c._useUTC = c._isUTC = isUTC; | |
c._l = locale; | |
c._i = input; | |
c._f = format; | |
c._strict = strict; | |
return createFromConfig(c); | |
} | |
function createLocal (input, format, locale, strict) { | |
return createLocalOrUTC(input, format, locale, strict, false); | |
} | |
var prototypeMin = deprecate( | |
'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', | |
function () { | |
var other = createLocal.apply(null, arguments); | |
if (this.isValid() && other.isValid()) { | |
return other < this ? this : other; | |
} else { | |
return createInvalid(); | |
} | |
} | |
); | |
var prototypeMax = deprecate( | |
'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', | |
function () { | |
var other = createLocal.apply(null, arguments); | |
if (this.isValid() && other.isValid()) { | |
return other > this ? this : other; | |
} else { | |
return createInvalid(); | |
} | |
} | |
); | |
// Pick a moment m from moments so that m[fn](other) is true for all | |
// other. This relies on the function fn to be transitive. | |
// | |
// moments should either be an array of moment objects or an array, whose | |
// first element is an array of moment objects. | |
function pickBy(fn, moments) { | |
var res, i; | |
if (moments.length === 1 && isArray(moments[0])) { | |
moments = moments[0]; | |
} | |
if (!moments.length) { | |
return createLocal(); | |
} | |
res = moments[0]; | |
for (i = 1; i < moments.length; ++i) { | |
if (!moments[i].isValid() || moments[i][fn](res)) { | |
res = moments[i]; | |
} | |
} | |
return res; | |
} | |
// TODO: Use [].sort instead? | |
function min () { | |
var args = [].slice.call(arguments, 0); | |
return pickBy('isBefore', args); | |
} | |
function max () { | |
var args = [].slice.call(arguments, 0); | |
return pickBy('isAfter', args); | |
} | |
var now = function () { | |
return Date.now ? Date.now() : +(new Date()); | |
}; | |
var ordering = ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond']; | |
function isDurationValid(m) { | |
for (var key in m) { | |
if (!(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { | |
return false; | |
} | |
} | |
var unitHasDecimal = false; | |
for (var i = 0; i < ordering.length; ++i) { | |
if (m[ordering[i]]) { | |
if (unitHasDecimal) { | |
return false; // only allow non-integers for smallest unit | |
} | |
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { | |
unitHasDecimal = true; | |
} | |
} | |
} | |
return true; | |
} | |
function isValid$1() { | |
return this._isValid; | |
} | |
function createInvalid$1() { | |
return createDuration(NaN); | |
} | |
function Duration (duration) { | |
var normalizedInput = normalizeObjectUnits(duration), | |
years = normalizedInput.year || 0, | |
quarters = normalizedInput.quarter || 0, | |
months = normalizedInput.month || 0, | |
weeks = normalizedInput.week || 0, | |
days = normalizedInput.day || 0, | |
hours = normalizedInput.hour || 0, | |
minutes = normalizedInput.minute || 0, | |
seconds = normalizedInput.second || 0, | |
milliseconds = normalizedInput.millisecond || 0; | |
this._isValid = isDurationValid(normalizedInput); | |
// representation for dateAddRemove | |
this._milliseconds = +milliseconds + | |
seconds * 1e3 + // 1000 | |
minutes * 6e4 + // 1000 * 60 | |
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 | |
// Because of dateAddRemove treats 24 hours as different from a | |
// day when working around DST, we need to store them separately | |
this._days = +days + | |
weeks * 7; | |
// It is impossible to translate months into days without knowing | |
// which months you are are talking about, so we have to store | |
// it separately. | |
this._months = +months + | |
quarters * 3 + | |
years * 12; | |
this._data = {}; | |
this._locale = getLocale(); | |
this._bubble(); | |
} | |
function isDuration (obj) { | |
return obj instanceof Duration; | |
} | |
function absRound (number) { | |
if (number < 0) { | |
return Math.round(-1 * number) * -1; | |
} else { | |
return Math.round(number); | |
} | |
} | |
// FORMATTING | |
function offset (token, separator) { | |
addFormatToken(token, 0, 0, function () { | |
var offset = this.utcOffset(); | |
var sign = '+'; | |
if (offset < 0) { | |
offset = -offset; | |
sign = '-'; | |
} | |
return sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~(offset) % 60, 2); | |
}); | |
} | |
offset('Z', ':'); | |
offset('ZZ', ''); | |
// PARSING | |
addRegexToken('Z', matchShortOffset); | |
addRegexToken('ZZ', matchShortOffset); | |
addParseToken(['Z', 'ZZ'], function (input, array, config) { | |
config._useUTC = true; | |
config._tzm = offsetFromString(matchShortOffset, input); | |
}); | |
// HELPERS | |
// timezone chunker | |
// '+10:00' > ['10', '00'] | |
// '-1530' > ['-15', '30'] | |
var chunkOffset = /([\+\-]|\d\d)/gi; | |
function offsetFromString(matcher, string) { | |
var matches = (string || '').match(matcher); | |
if (matches === null) { | |
return null; | |
} | |
var chunk = matches[matches.length - 1] || []; | |
var parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; | |
var minutes = +(parts[1] * 60) + toInt(parts[2]); | |
return minutes === 0 ? | |
0 : | |
parts[0] === '+' ? minutes : -minutes; | |
} | |
// Return a moment from input, that is local/utc/zone equivalent to model. | |
function cloneWithOffset(input, model) { | |
var res, diff; | |
if (model._isUTC) { | |
res = model.clone(); | |
diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); | |
// Use low-level api, because this fn is low-level api. | |
res._d.setTime(res._d.valueOf() + diff); | |
hooks.updateOffset(res, false); | |
return res; | |
} else { | |
return createLocal(input).local(); | |
} | |
} | |
function getDateOffset (m) { | |
// On Firefox.24 Date#getTimezoneOffset returns a floating point. | |
// https://github.com/moment/moment/pull/1871 | |
return -Math.round(m._d.getTimezoneOffset() / 15) * 15; | |
} | |
// HOOKS | |
// This function will be called whenever a moment is mutated. | |
// It is intended to keep the offset in sync with the timezone. | |
hooks.updateOffset = function () {}; | |
// MOMENTS | |
// keepLocalTime = true means only change the timezone, without | |
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> | |
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset | |
// +0200, so we adjust the time as needed, to be valid. | |
// | |
// Keeping the time actually adds/subtracts (one hour) | |
// from the actual represented time. That is why we call updateOffset | |
// a second time. In case it wants us to change the offset again | |
// _changeInProgress == true case, then we have to adjust, because | |
// there is no such time in the given timezone. | |
function getSetOffset (input, keepLocalTime, keepMinutes) { | |
var offset = this._offset || 0, | |
localAdjust; | |
if (!this.isValid()) { | |
return input != null ? this : NaN; | |
} | |
if (input != null) { | |
if (typeof input === 'string') { | |
input = offsetFromString(matchShortOffset, input); | |
if (input === null) { | |
return this; | |
} | |
} else if (Math.abs(input) < 16 && !keepMinutes) { | |
input = input * 60; | |
} | |
if (!this._isUTC && keepLocalTime) { | |
localAdjust = getDateOffset(this); | |
} | |
this._offset = input; | |
this._isUTC = true; | |
if (localAdjust != null) { | |
this.add(localAdjust, 'm'); | |
} | |
if (offset !== input) { | |
if (!keepLocalTime || this._changeInProgress) { | |
addSubtract(this, createDuration(input - offset, 'm'), 1, false); | |
} else if (!this._changeInProgress) { | |
this._changeInProgress = true; | |
hooks.updateOffset(this, true); | |
this._changeInProgress = null; | |
} | |
} | |
return this; | |
} else { | |
return this._isUTC ? offset : getDateOffset(this); | |
} | |
} | |
function getSetZone (input, keepLocalTime) { | |
if (input != null) { | |
if (typeof input !== 'string') { | |
input = -input; | |
} | |
this.utcOffset(input, keepLocalTime); | |
return this; | |
} else { | |
return -this.utcOffset(); | |
} | |
} | |
function setOffsetToUTC (keepLocalTime) { | |
return this.utcOffset(0, keepLocalTime); | |
} | |
function setOffsetToLocal (keepLocalTime) { | |
if (this._isUTC) { | |
this.utcOffset(0, keepLocalTime); | |
this._isUTC = false; | |
if (keepLocalTime) { | |
this.subtract(getDateOffset(this), 'm'); | |
} | |
} | |
return this; | |
} | |
function setOffsetToParsedOffset () { | |
if (this._tzm != null) { | |
this.utcOffset(this._tzm, false, true); | |
} else if (typeof this._i === 'string') { | |
var tZone = offsetFromString(matchOffset, this._i); | |
if (tZone != null) { | |
this.utcOffset(tZone); | |
} | |
else { | |
this.utcOffset(0, true); | |
} | |
} | |
return this; | |
} | |
function hasAlignedHourOffset (input) { | |
if (!this.isValid()) { | |
return false; | |
} | |
input = input ? createLocal(input).utcOffset() : 0; | |
return (this.utcOffset() - input) % 60 === 0; | |
} | |
function isDaylightSavingTime () { | |
return ( | |
this.utcOffset() > this.clone().month(0).utcOffset() || | |
this.utcOffset() > this.clone().month(5).utcOffset() | |
); | |
} | |
function isDaylightSavingTimeShifted () { | |
if (!isUndefined(this._isDSTShifted)) { | |
return this._isDSTShifted; | |
} | |
var c = {}; | |
copyConfig(c, this); | |
c = prepareConfig(c); | |
if (c._a) { | |
var other = c._isUTC ? createUTC(c._a) : createLocal(c._a); | |
this._isDSTShifted = this.isValid() && | |
compareArrays(c._a, other.toArray()) > 0; | |
} else { | |
this._isDSTShifted = false; | |
} | |
return this._isDSTShifted; | |
} | |
function isLocal () { | |
return this.isValid() ? !this._isUTC : false; | |
} | |
function isUtcOffset () { | |
return this.isValid() ? this._isUTC : false; | |
} | |
function isUtc () { | |
return this.isValid() ? this._isUTC && this._offset === 0 : false; | |
} | |
// ASP.NET json date format regex | |
var aspNetRegex = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/; | |
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html | |
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere | |
// and further modified to allow for strings containing both week and day | |
var isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; | |
function createDuration (input, key) { | |
var duration = input, | |
// matching against regexp is expensive, do it on demand | |
match = null, | |
sign, | |
ret, | |
diffRes; | |
if (isDuration(input)) { | |
duration = { | |
ms : input._milliseconds, | |
d : input._days, | |
M : input._months | |
}; | |
} else if (isNumber(input)) { | |
duration = {}; | |
if (key) { | |
duration[key] = input; | |
} else { | |
duration.milliseconds = input; | |
} | |
} else if (!!(match = aspNetRegex.exec(input))) { | |
sign = (match[1] === '-') ? -1 : 1; | |
duration = { | |
y : 0, | |
d : toInt(match[DATE]) * sign, | |
h : toInt(match[HOUR]) * sign, | |
m : toInt(match[MINUTE]) * sign, | |
s : toInt(match[SECOND]) * sign, | |
ms : toInt(absRound(match[MILLISECOND] * 1000)) * sign // the millisecond decimal point is included in the match | |
}; | |
} else if (!!(match = isoRegex.exec(input))) { | |
sign = (match[1] === '-') ? -1 : (match[1] === '+') ? 1 : 1; | |
duration = { | |
y : parseIso(match[2], sign), | |
M : parseIso(match[3], sign), | |
w : parseIso(match[4], sign), | |
d : parseIso(match[5], sign), | |
h : parseIso(match[6], sign), | |
m : parseIso(match[7], sign), | |
s : parseIso(match[8], sign) | |
}; | |
} else if (duration == null) {// checks for null or undefined | |
duration = {}; | |
} else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { | |
diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); | |
duration = {}; | |
duration.ms = diffRes.milliseconds; | |
duration.M = diffRes.months; | |
} | |
ret = new Duration(duration); | |
if (isDuration(input) && hasOwnProp(input, '_locale')) { | |
ret._locale = input._locale; | |
} | |
return ret; | |
} | |
createDuration.fn = Duration.prototype; | |
createDuration.invalid = createInvalid$1; | |
function parseIso (inp, sign) { | |
// We'd normally use ~~inp for this, but unfortunately it also | |
// converts floats to ints. | |
// inp may be undefined, so careful calling replace on it. | |
var res = inp && parseFloat(inp.replace(',', '.')); | |
// apply sign while we're at it | |
return (isNaN(res) ? 0 : res) * sign; | |
} | |
function positiveMomentsDifference(base, other) { | |
var res = {milliseconds: 0, months: 0}; | |
res.months = other.month() - base.month() + | |
(other.year() - base.year()) * 12; | |
if (base.clone().add(res.months, 'M').isAfter(other)) { | |
--res.months; | |
} | |
res.milliseconds = +other - +(base.clone().add(res.months, 'M')); | |
return res; | |
} | |
function momentsDifference(base, other) { | |
var res; | |
if (!(base.isValid() && other.isValid())) { | |
return {milliseconds: 0, months: 0}; | |
} | |
other = cloneWithOffset(other, base); | |
if (base.isBefore(other)) { | |
res = positiveMomentsDifference(base, other); | |
} else { | |
res = positiveMomentsDifference(other, base); | |
res.milliseconds = -res.milliseconds; | |
res.months = -res.months; | |
} | |
return res; | |
} | |
// TODO: remove 'name' arg after deprecation is removed | |
function createAdder(direction, name) { | |
return function (val, period) { | |
var dur, tmp; | |
//invert the arguments, but complain about it | |
if (period !== null && !isNaN(+period)) { | |
deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + | |
'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.'); | |
tmp = val; val = period; period = tmp; | |
} | |
val = typeof val === 'string' ? +val : val; | |
dur = createDuration(val, period); | |
addSubtract(this, dur, direction); | |
return this; | |
}; | |
} | |
function addSubtract (mom, duration, isAdding, updateOffset) { | |
var milliseconds = duration._milliseconds, | |
days = absRound(duration._days), | |
months = absRound(duration._months); | |
if (!mom.isValid()) { | |
// No op | |
return; | |
} | |
updateOffset = updateOffset == null ? true : updateOffset; | |
if (months) { | |
setMonth(mom, get(mom, 'Month') + months * isAdding); | |
} | |
if (days) { | |
set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); | |
} | |
if (milliseconds) { | |
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); | |
} | |
if (updateOffset) { | |
hooks.updateOffset(mom, days || months); | |
} | |
} | |
var add = createAdder(1, 'add'); | |
var subtract = createAdder(-1, 'subtract'); | |
function getCalendarFormat(myMoment, now) { | |
var diff = myMoment.diff(now, 'days', true); | |
return diff < -6 ? 'sameElse' : | |
diff < -1 ? 'lastWeek' : | |
diff < 0 ? 'lastDay' : | |
diff < 1 ? 'sameDay' : | |
diff < 2 ? 'nextDay' : | |
diff < 7 ? 'nextWeek' : 'sameElse'; | |
} | |
function calendar$1 (time, formats) { | |
// We want to compare the start of today, vs this. | |
// Getting start-of-today depends on whether we're local/utc/offset or not. | |
var now = time || createLocal(), | |
sod = cloneWithOffset(now, this).startOf('day'), | |
format = hooks.calendarFormat(this, sod) || 'sameElse'; | |
var output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); | |
return this.format(output || this.localeData().calendar(format, this, createLocal(now))); | |
} | |
function clone () { | |
return new Moment(this); | |
} | |
function isAfter (input, units) { | |
var localInput = isMoment(input) ? input : createLocal(input); | |
if (!(this.isValid() && localInput.isValid())) { | |
return false; | |
} | |
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); | |
if (units === 'millisecond') { | |
return this.valueOf() > localInput.valueOf(); | |
} else { | |
return localInput.valueOf() < this.clone().startOf(units).valueOf(); | |
} | |
} | |
function isBefore (input, units) { | |
var localInput = isMoment(input) ? input : createLocal(input); | |
if (!(this.isValid() && localInput.isValid())) { | |
return false; | |
} | |
units = normalizeUnits(!isUndefined(units) ? units : 'millisecond'); | |
if (units === 'millisecond') { | |
return this.valueOf() < localInput.valueOf(); | |
} else { | |
return this.clone().endOf(units).valueOf() < localInput.valueOf(); | |
} | |
} | |
function isBetween (from, to, units, inclusivity) { | |
inclusivity = inclusivity || '()'; | |
return (inclusivity[0] === '(' ? this.isAfter(from, units) : !this.isBefore(from, units)) && | |
(inclusivity[1] === ')' ? this.isBefore(to, units) : !this.isAfter(to, units)); | |
} | |
function isSame (input, units) { | |
var localInput = isMoment(input) ? input : createLocal(input), | |
inputMs; | |
if (!(this.isValid() && localInput.isValid())) { | |
return false; | |
} | |
units = normalizeUnits(units || 'millisecond'); | |
if (units === 'millisecond') { | |
return this.valueOf() === localInput.valueOf(); | |
} else { | |
inputMs = localInput.valueOf(); | |
return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); | |
} | |
} | |
function isSameOrAfter (input, units) { | |
return this.isSame(input, units) || this.isAfter(input,units); | |
} | |
function isSameOrBefore (input, units) { | |
return this.isSame(input, units) || this.isBefore(input,units); | |
} | |
function diff (input, units, asFloat) { | |
var that, | |
zoneDelta, | |
delta, output; | |
if (!this.isValid()) { | |
return NaN; | |
} | |
that = cloneWithOffset(input, this); | |
if (!that.isValid()) { | |
return NaN; | |
} | |
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; | |
units = normalizeUnits(units); | |
switch (units) { | |
case 'year': output = monthDiff(this, that) / 12; break; | |
case 'month': output = monthDiff(this, that); break; | |
case 'quarter': output = monthDiff(this, that) / 3; break; | |
case 'second': output = (this - that) / 1e3; break; // 1000 | |
case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 | |
case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 | |
case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst | |
case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst | |
default: output = this - that; | |
} | |
return asFloat ? output : absFloor(output); | |
} | |
function monthDiff (a, b) { | |
// difference in months | |
var wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month()), | |
// b is in (anchor - 1 month, anchor + 1 month) | |
anchor = a.clone().add(wholeMonthDiff, 'months'), | |
anchor2, adjust; | |
if (b - anchor < 0) { | |
anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); | |
// linear across the month | |
adjust = (b - anchor) / (anchor - anchor2); | |
} else { | |
anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); | |
// linear across the month | |
adjust = (b - anchor) / (anchor2 - anchor); | |
} | |
//check for negative zero, return zero if negative zero | |
return -(wholeMonthDiff + adjust) || 0; | |
} | |
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; | |
hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; | |
function toString () { | |
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); | |
} | |
function toISOString(keepOffset) { | |
if (!this.isValid()) { | |
return null; | |
} | |
var utc = keepOffset !== true; | |
var m = utc ? this.clone().utc() : this; | |
if (m.year() < 0 || m.year() > 9999) { | |
return formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ'); | |
} | |
if (isFunction(Date.prototype.toISOString)) { | |
// native implementation is ~50x faster, use it when we can | |
if (utc) { | |
return this.toDate().toISOString(); | |
} else { | |
return new Date(this._d.valueOf()).toISOString().replace('Z', formatMoment(m, 'Z')); | |
} | |
} | |
return formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ'); | |
} | |
/** | |
* Return a human readable representation of a moment that can | |
* also be evaluated to get a new moment which is the same | |
* | |
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects | |
*/ | |
function inspect () { | |
if (!this.isValid()) { | |
return 'moment.invalid(/* ' + this._i + ' */)'; | |
} | |
var func = 'moment'; | |
var zone = ''; | |
if (!this.isLocal()) { | |
func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; | |
zone = 'Z'; | |
} | |
var prefix = '[' + func + '("]'; | |
var year = (0 <= this.year() && this.year() <= 9999) ? 'YYYY' : 'YYYYYY'; | |
var datetime = '-MM-DD[T]HH:mm:ss.SSS'; | |
var suffix = zone + '[")]'; | |
return this.format(prefix + year + datetime + suffix); | |
} | |
function format (inputString) { | |
if (!inputString) { | |
inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; | |
} | |
var output = formatMoment(this, inputString); | |
return this.localeData().postformat(output); | |
} | |
function from (time, withoutSuffix) { | |
if (this.isValid() && | |
((isMoment(time) && time.isValid()) || | |
createLocal(time).isValid())) { | |
return createDuration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); | |
} else { | |
return this.localeData().invalidDate(); | |
} | |
} | |
function fromNow (withoutSuffix) { | |
return this.from(createLocal(), withoutSuffix); | |
} | |
function to (time, withoutSuffix) { | |
if (this.isValid() && | |
((isMoment(time) && time.isValid()) || | |
createLocal(time).isValid())) { | |
return createDuration({from: this, to: time}).locale(this.locale()).humanize(!withoutSuffix); | |
} else { | |
return this.localeData().invalidDate(); | |
} | |
} | |
function toNow (withoutSuffix) { | |
return this.to(createLocal(), withoutSuffix); | |
} | |
// If passed a locale key, it will set the locale for this | |
// instance. Otherwise, it will return the locale configuration | |
// variables for this instance. | |
function locale (key) { | |
var newLocaleData; | |
if (key === undefined) { | |
return this._locale._abbr; | |
} else { | |
newLocaleData = getLocale(key); | |
if (newLocaleData != null) { | |
this._locale = newLocaleData; | |
} | |
return this; | |
} | |
} | |
var lang = deprecate( | |
'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', | |
function (key) { | |
if (key === undefined) { | |
return this.localeData(); | |
} else { | |
return this.locale(key); | |
} | |
} | |
); | |
function localeData () { | |
return this._locale; | |
} | |
function startOf (units) { | |
units = normalizeUnits(units); | |
// the following switch intentionally omits break keywords | |
// to utilize falling through the cases. | |
switch (units) { | |
case 'year': | |
this.month(0); | |
/* falls through */ | |
case 'quarter': | |
case 'month': | |
this.date(1); | |
/* falls through */ | |
case 'week': | |
case 'isoWeek': | |
case 'day': | |
case 'date': | |
this.hours(0); | |
/* falls through */ | |
case 'hour': | |
this.minutes(0); | |
/* falls through */ | |
case 'minute': | |
this.seconds(0); | |
/* falls through */ | |
case 'second': | |
this.milliseconds(0); | |
} | |
// weeks are a special case | |
if (units === 'week') { | |
this.weekday(0); | |
} | |
if (units === 'isoWeek') { | |
this.isoWeekday(1); | |
} | |
// quarters are also special | |
if (units === 'quarter') { | |
this.month(Math.floor(this.month() / 3) * 3); | |
} | |
return this; | |
} | |
function endOf (units) { | |
units = normalizeUnits(units); | |
if (units === undefined || units === 'millisecond') { | |
return this; | |
} | |
// 'date' is an alias for 'day', so it should be considered as such. | |
if (units === 'date') { | |
units = 'day'; | |
} | |
return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); | |
} | |
function valueOf () { | |
return this._d.valueOf() - ((this._offset || 0) * 60000); | |
} | |
function unix () { | |
return Math.floor(this.valueOf() / 1000); | |
} | |
function toDate () { | |
return new Date(this.valueOf()); | |
} | |
function toArray () { | |
var m = this; | |
return [m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond()]; | |
} | |
function toObject () { | |
var m = this; | |
return { | |
years: m.year(), | |
months: m.month(), | |
date: m.date(), | |
hours: m.hours(), | |
minutes: m.minutes(), | |
seconds: m.seconds(), | |
milliseconds: m.milliseconds() | |
}; | |
} | |
function toJSON () { | |
// new Date(NaN).toJSON() === null | |
return this.isValid() ? this.toISOString() : null; | |
} | |
function isValid$2 () { | |
return isValid(this); | |
} | |
function parsingFlags () { | |
return extend({}, getParsingFlags(this)); | |
} | |
function invalidAt () { | |
return getParsingFlags(this).overflow; | |
} | |
function creationData() { | |
return { | |
input: this._i, | |
format: this._f, | |
locale: this._locale, | |
isUTC: this._isUTC, | |
strict: this._strict | |
}; | |
} | |
// FORMATTING | |
addFormatToken(0, ['gg', 2], 0, function () { | |
return this.weekYear() % 100; | |
}); | |
addFormatToken(0, ['GG', 2], 0, function () { | |
return this.isoWeekYear() % 100; | |
}); | |
function addWeekYearFormatToken (token, getter) { | |
addFormatToken(0, [token, token.length], 0, getter); | |
} | |
addWeekYearFormatToken('gggg', 'weekYear'); | |
addWeekYearFormatToken('ggggg', 'weekYear'); | |
addWeekYearFormatToken('GGGG', 'isoWeekYear'); | |
addWeekYearFormatToken('GGGGG', 'isoWeekYear'); | |
// ALIASES | |
addUnitAlias('weekYear', 'gg'); | |
addUnitAlias('isoWeekYear', 'GG'); | |
// PRIORITY | |
addUnitPriority('weekYear', 1); | |
addUnitPriority('isoWeekYear', 1); | |
// PARSING | |
addRegexToken('G', matchSigned); | |
addRegexToken('g', matchSigned); | |
addRegexToken('GG', match1to2, match2); | |
addRegexToken('gg', match1to2, match2); | |
addRegexToken('GGGG', match1to4, match4); | |
addRegexToken('gggg', match1to4, match4); | |
addRegexToken('GGGGG', match1to6, match6); | |
addRegexToken('ggggg', match1to6, match6); | |
addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function (input, week, config, token) { | |
week[token.substr(0, 2)] = toInt(input); | |
}); | |
addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { | |
week[token] = hooks.parseTwoDigitYear(input); | |
}); | |
// MOMENTS | |
function getSetWeekYear (input) { | |
return getSetWeekYearHelper.call(this, | |
input, | |
this.week(), | |
this.weekday(), | |
this.localeData()._week.dow, | |
this.localeData()._week.doy); | |
} | |
function getSetISOWeekYear (input) { | |
return getSetWeekYearHelper.call(this, | |
input, this.isoWeek(), this.isoWeekday(), 1, 4); | |
} | |
function getISOWeeksInYear () { | |
return weeksInYear(this.year(), 1, 4); | |
} | |
function getWeeksInYear () { | |
var weekInfo = this.localeData()._week; | |
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); | |
} | |
function getSetWeekYearHelper(input, week, weekday, dow, doy) { | |
var weeksTarget; | |
if (input == null) { | |
return weekOfYear(this, dow, doy).year; | |
} else { | |
weeksTarget = weeksInYear(input, dow, doy); | |
if (week > weeksTarget) { | |
week = weeksTarget; | |
} | |
return setWeekAll.call(this, input, week, weekday, dow, doy); | |
} | |
} | |
function setWeekAll(weekYear, week, weekday, dow, doy) { | |
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), | |
date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); | |
this.year(date.getUTCFullYear()); | |
this.month(date.getUTCMonth()); | |
this.date(date.getUTCDate()); | |
return this; | |
} | |
// FORMATTING | |
addFormatToken('Q', 0, 'Qo', 'quarter'); | |
// ALIASES | |
addUnitAlias('quarter', 'Q'); | |
// PRIORITY | |
addUnitPriority('quarter', 7); | |
// PARSING | |
addRegexToken('Q', match1); | |
addParseToken('Q', function (input, array) { | |
array[MONTH] = (toInt(input) - 1) * 3; | |
}); | |
// MOMENTS | |
function getSetQuarter (input) { | |
return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); | |
} | |
// FORMATTING | |
addFormatToken('D', ['DD', 2], 'Do', 'date'); | |
// ALIASES | |
addUnitAlias('date', 'D'); | |
// PRIOROITY | |
addUnitPriority('date', 9); | |
// PARSING | |
addRegexToken('D', match1to2); | |
addRegexToken('DD', match1to2, match2); | |
addRegexToken('Do', function (isStrict, locale) { | |
// TODO: Remove "ordinalParse" fallback in next major release. | |
return isStrict ? | |
(locale._dayOfMonthOrdinalParse || locale._ordinalParse) : | |
locale._dayOfMonthOrdinalParseLenient; | |
}); | |
addParseToken(['D', 'DD'], DATE); | |
addParseToken('Do', function (input, array) { | |
array[DATE] = toInt(input.match(match1to2)[0]); | |
}); | |
// MOMENTS | |
var getSetDayOfMonth = makeGetSet('Date', true); | |
// FORMATTING | |
addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); | |
// ALIASES | |
addUnitAlias('dayOfYear', 'DDD'); | |
// PRIORITY | |
addUnitPriority('dayOfYear', 4); | |
// PARSING | |
addRegexToken('DDD', match1to3); | |
addRegexToken('DDDD', match3); | |
addParseToken(['DDD', 'DDDD'], function (input, array, config) { | |
config._dayOfYear = toInt(input); | |
}); | |
// HELPERS | |
// MOMENTS | |
function getSetDayOfYear (input) { | |
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1; | |
return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); | |
} | |
// FORMATTING | |
addFormatToken('m', ['mm', 2], 0, 'minute'); | |
// ALIASES | |
addUnitAlias('minute', 'm'); | |
// PRIORITY | |
addUnitPriority('minute', 14); | |
// PARSING | |
addRegexToken('m', match1to2); | |
addRegexToken('mm', match1to2, match2); | |
addParseToken(['m', 'mm'], MINUTE); | |
// MOMENTS | |
var getSetMinute = makeGetSet('Minutes', false); | |
// FORMATTING | |
addFormatToken('s', ['ss', 2], 0, 'second'); | |
// ALIASES | |
addUnitAlias('second', 's'); | |
// PRIORITY | |
addUnitPriority('second', 15); | |
// PARSING | |
addRegexToken('s', match1to2); | |
addRegexToken('ss', match1to2, match2); | |
addParseToken(['s', 'ss'], SECOND); | |
// MOMENTS | |
var getSetSecond = makeGetSet('Seconds', false); | |
// FORMATTING | |
addFormatToken('S', 0, 0, function () { | |
return ~~(this.millisecond() / 100); | |
}); | |
addFormatToken(0, ['SS', 2], 0, function () { | |
return ~~(this.millisecond() / 10); | |
}); | |
addFormatToken(0, ['SSS', 3], 0, 'millisecond'); | |
addFormatToken(0, ['SSSS', 4], 0, function () { | |
return this.millisecond() * 10; | |
}); | |
addFormatToken(0, ['SSSSS', 5], 0, function () { | |
return this.millisecond() * 100; | |
}); | |
addFormatToken(0, ['SSSSSS', 6], 0, function () { | |
return this.millisecond() * 1000; | |
}); | |
addFormatToken(0, ['SSSSSSS', 7], 0, function () { | |
return this.millisecond() * 10000; | |
}); | |
addFormatToken(0, ['SSSSSSSS', 8], 0, function () { | |
return this.millisecond() * 100000; | |
}); | |
addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { | |
return this.millisecond() * 1000000; | |
}); | |
// ALIASES | |
addUnitAlias('millisecond', 'ms'); | |
// PRIORITY | |
addUnitPriority('millisecond', 16); | |
// PARSING | |
addRegexToken('S', match1to3, match1); | |
addRegexToken('SS', match1to3, match2); | |
addRegexToken('SSS', match1to3, match3); | |
var token; | |
for (token = 'SSSS'; token.length <= 9; token += 'S') { | |
addRegexToken(token, matchUnsigned); | |
} | |
function parseMs(input, array) { | |
array[MILLISECOND] = toInt(('0.' + input) * 1000); | |
} | |
for (token = 'S'; token.length <= 9; token += 'S') { | |
addParseToken(token, parseMs); | |
} | |
// MOMENTS | |
var getSetMillisecond = makeGetSet('Milliseconds', false); | |
// FORMATTING | |
addFormatToken('z', 0, 0, 'zoneAbbr'); | |
addFormatToken('zz', 0, 0, 'zoneName'); | |
// MOMENTS | |
function getZoneAbbr () { | |
return this._isUTC ? 'UTC' : ''; | |
} | |
function getZoneName () { | |
return this._isUTC ? 'Coordinated Universal Time' : ''; | |
} | |
var proto = Moment.prototype; | |
proto.add = add; | |
proto.calendar = calendar$1; | |
proto.clone = clone; | |
proto.diff = diff; | |
proto.endOf = endOf; | |
proto.format = format; | |
proto.from = from; | |
proto.fromNow = fromNow; | |
proto.to = to; | |
proto.toNow = toNow; | |
proto.get = stringGet; | |
proto.invalidAt = invalidAt; | |
proto.isAfter = isAfter; | |
proto.isBefore = isBefore; | |
proto.isBetween = isBetween; | |
proto.isSame = isSame; | |
proto.isSameOrAfter = isSameOrAfter; | |
proto.isSameOrBefore = isSameOrBefore; | |
proto.isValid = isValid$2; | |
proto.lang = lang; | |
proto.locale = locale; | |
proto.localeData = localeData; | |
proto.max = prototypeMax; | |
proto.min = prototypeMin; | |
proto.parsingFlags = parsingFlags; | |
proto.set = stringSet; | |
proto.startOf = startOf; | |
proto.subtract = subtract; | |
proto.toArray = toArray; | |
proto.toObject = toObject; | |
proto.toDate = toDate; | |
proto.toISOString = toISOString; | |
proto.inspect = inspect; | |
proto.toJSON = toJSON; | |
proto.toString = toString; | |
proto.unix = unix; | |
proto.valueOf = valueOf; | |
proto.creationData = creationData; | |
// Year | |
proto.year = getSetYear; | |
proto.isLeapYear = getIsLeapYear; | |
// Week Year | |
proto.weekYear = getSetWeekYear; | |
proto.isoWeekYear = getSetISOWeekYear; | |
// Quarter | |
proto.quarter = proto.quarters = getSetQuarter; | |
// Month | |
proto.month = getSetMonth; | |
proto.daysInMonth = getDaysInMonth; | |
// Week | |
proto.week = proto.weeks = getSetWeek; | |
proto.isoWeek = proto.isoWeeks = getSetISOWeek; | |
proto.weeksInYear = getWeeksInYear; | |
proto.isoWeeksInYear = getISOWeeksInYear; | |
// Day | |
proto.date = getSetDayOfMonth; | |
proto.day = proto.days = getSetDayOfWeek; | |
proto.weekday = getSetLocaleDayOfWeek; | |
proto.isoWeekday = getSetISODayOfWeek; | |
proto.dayOfYear = getSetDayOfYear; | |
// Hour | |
proto.hour = proto.hours = getSetHour; | |
// Minute | |
proto.minute = proto.minutes = getSetMinute; | |
// Second | |
proto.second = proto.seconds = getSetSecond; | |
// Millisecond | |
proto.millisecond = proto.milliseconds = getSetMillisecond; | |
// Offset | |
proto.utcOffset = getSetOffset; | |
proto.utc = setOffsetToUTC; | |
proto.local = setOffsetToLocal; | |
proto.parseZone = setOffsetToParsedOffset; | |
proto.hasAlignedHourOffset = hasAlignedHourOffset; | |
proto.isDST = isDaylightSavingTime; | |
proto.isLocal = isLocal; | |
proto.isUtcOffset = isUtcOffset; | |
proto.isUtc = isUtc; | |
proto.isUTC = isUtc; | |
// Timezone | |
proto.zoneAbbr = getZoneAbbr; | |
proto.zoneName = getZoneName; | |
// Deprecations | |
proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth); | |
proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth); | |
proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear); | |
proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone); | |
proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted); | |
function createUnix (input) { | |
return createLocal(input * 1000); | |
} | |
function createInZone () { | |
return createLocal.apply(null, arguments).parseZone(); | |
} | |
function preParsePostFormat (string) { | |
return string; | |
} | |
var proto$1 = Locale.prototype; | |
proto$1.calendar = calendar; | |
proto$1.longDateFormat = longDateFormat; | |
proto$1.invalidDate = invalidDate; | |
proto$1.ordinal = ordinal; | |
proto$1.preparse = preParsePostFormat; | |
proto$1.postformat = preParsePostFormat; | |
proto$1.relativeTime = relativeTime; | |
proto$1.pastFuture = pastFuture; | |
proto$1.set = set; | |
// Month | |
proto$1.months = localeMonths; | |
proto$1.monthsShort = localeMonthsShort; | |
proto$1.monthsParse = localeMonthsParse; | |
proto$1.monthsRegex = monthsRegex; | |
proto$1.monthsShortRegex = monthsShortRegex; | |
// Week | |
proto$1.week = localeWeek; | |
proto$1.firstDayOfYear = localeFirstDayOfYear; | |
proto$1.firstDayOfWeek = localeFirstDayOfWeek; | |
// Day of Week | |
proto$1.weekdays = localeWeekdays; | |
proto$1.weekdaysMin = localeWeekdaysMin; | |
proto$1.weekdaysShort = localeWeekdaysShort; | |
proto$1.weekdaysParse = localeWeekdaysParse; | |
proto$1.weekdaysRegex = weekdaysRegex; | |
proto$1.weekdaysShortRegex = weekdaysShortRegex; | |
proto$1.weekdaysMinRegex = weekdaysMinRegex; | |
// Hours | |
proto$1.isPM = localeIsPM; | |
proto$1.meridiem = localeMeridiem; | |
function get$1 (format, index, field, setter) { | |
var locale = getLocale(); | |
var utc = createUTC().set(setter, index); | |
return locale[field](utc, format); | |
} | |
function listMonthsImpl (format, index, field) { | |
if (isNumber(format)) { | |
index = format; | |
format = undefined; | |
} | |
format = format || ''; | |
if (index != null) { | |
return get$1(format, index, field, 'month'); | |
} | |
var i; | |
var out = []; | |
for (i = 0; i < 12; i++) { | |
out[i] = get$1(format, i, field, 'month'); | |
} | |
return out; | |
} | |
// () | |
// (5) | |
// (fmt, 5) | |
// (fmt) | |
// (true) | |
// (true, 5) | |
// (true, fmt, 5) | |
// (true, fmt) | |
function listWeekdaysImpl (localeSorted, format, index, field) { | |
if (typeof localeSorted === 'boolean') { | |
if (isNumber(format)) { | |
index = format; | |
format = undefined; | |
} | |
format = format || ''; | |
} else { | |
format = localeSorted; | |
index = format; | |
localeSorted = false; | |
if (isNumber(format)) { | |
index = format; | |
format = undefined; | |
} | |
format = format || ''; | |
} | |
var locale = getLocale(), | |
shift = localeSorted ? locale._week.dow : 0; | |
if (index != null) { | |
return get$1(format, (index + shift) % 7, field, 'day'); | |
} | |
var i; | |
var out = []; | |
for (i = 0; i < 7; i++) { | |
out[i] = get$1(format, (i + shift) % 7, field, 'day'); | |
} | |
return out; | |
} | |
function listMonths (format, index) { | |
return listMonthsImpl(format, index, 'months'); | |
} | |
function listMonthsShort (format, index) { | |
return listMonthsImpl(format, index, 'monthsShort'); | |
} | |
function listWeekdays (localeSorted, format, index) { | |
return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); | |
} | |
function listWeekdaysShort (localeSorted, format, index) { | |
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); | |
} | |
function listWeekdaysMin (localeSorted, format, index) { | |
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); | |
} | |
getSetGlobalLocale('en', { | |
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, | |
ordinal : function (number) { | |
var b = number % 10, | |
output = (toInt(number % 100 / 10) === 1) ? 'th' : | |
(b === 1) ? 'st' : | |
(b === 2) ? 'nd' : | |
(b === 3) ? 'rd' : 'th'; | |
return number + output; | |
} | |
}); | |
// Side effect imports | |
hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale); | |
hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale); | |
var mathAbs = Math.abs; | |
function abs () { | |
var data = this._data; | |
this._milliseconds = mathAbs(this._milliseconds); | |
this._days = mathAbs(this._days); | |
this._months = mathAbs(this._months); | |
data.milliseconds = mathAbs(data.milliseconds); | |
data.seconds = mathAbs(data.seconds); | |
data.minutes = mathAbs(data.minutes); | |
data.hours = mathAbs(data.hours); | |
data.months = mathAbs(data.months); | |
data.years = mathAbs(data.years); | |
return this; | |
} | |
function addSubtract$1 (duration, input, value, direction) { | |
var other = createDuration(input, value); | |
duration._milliseconds += direction * other._milliseconds; | |
duration._days += direction * other._days; | |
duration._months += direction * other._months; | |
return duration._bubble(); | |
} | |
// supports only 2.0-style add(1, 's') or add(duration) | |
function add$1 (input, value) { | |
return addSubtract$1(this, input, value, 1); | |
} | |
// supports only 2.0-style subtract(1, 's') or subtract(duration) | |
function subtract$1 (input, value) { | |
return addSubtract$1(this, input, value, -1); | |
} | |
function absCeil (number) { | |
if (number < 0) { | |
return Math.floor(number); | |
} else { | |
return Math.ceil(number); | |
} | |
} | |
function bubble () { | |
var milliseconds = this._milliseconds; | |
var days = this._days; | |
var months = this._months; | |
var data = this._data; | |
var seconds, minutes, hours, years, monthsFromDays; | |
// if we have a mix of positive and negative values, bubble down first | |
// check: https://github.com/moment/moment/issues/2166 | |
if (!((milliseconds >= 0 && days >= 0 && months >= 0) || | |
(milliseconds <= 0 && days <= 0 && months <= 0))) { | |
milliseconds += absCeil(monthsToDays(months) + days) * 864e5; | |
days = 0; | |
months = 0; | |
} | |
// The following code bubbles up values, see the tests for | |
// examples of what that means. | |
data.milliseconds = milliseconds % 1000; | |
seconds = absFloor(milliseconds / 1000); | |
data.seconds = seconds % 60; | |
minutes = absFloor(seconds / 60); | |
data.minutes = minutes % 60; | |
hours = absFloor(minutes / 60); | |
data.hours = hours % 24; | |
days += absFloor(hours / 24); | |
// convert days to months | |
monthsFromDays = absFloor(daysToMonths(days)); | |
months += monthsFromDays; | |
days -= absCeil(monthsToDays(monthsFromDays)); | |
// 12 months -> 1 year | |
years = absFloor(months / 12); | |
months %= 12; | |
data.days = days; | |
data.months = months; | |
data.years = years; | |
return this; | |
} | |
function daysToMonths (days) { | |
// 400 years have 146097 days (taking into account leap year rules) | |
// 400 years have 12 months === 4800 | |
return days * 4800 / 146097; | |
} | |
function monthsToDays (months) { | |
// the reverse of daysToMonths | |
return months * 146097 / 4800; | |
} | |
function as (units) { | |
if (!this.isValid()) { | |
return NaN; | |
} | |
var days; | |
var months; | |
var milliseconds = this._milliseconds; | |
units = normalizeUnits(units); | |
if (units === 'month' || units === 'year') { | |
days = this._days + milliseconds / 864e5; | |
months = this._months + daysToMonths(days); | |
return units === 'month' ? months : months / 12; | |
} else { | |
// handle milliseconds separately because of floating point math errors (issue #1867) | |
days = this._days + Math.round(monthsToDays(this._months)); | |
switch (units) { | |
case 'week' : return days / 7 + milliseconds / 6048e5; | |
case 'day' : return days + milliseconds / 864e5; | |
case 'hour' : return days * 24 + milliseconds / 36e5; | |
case 'minute' : return days * 1440 + milliseconds / 6e4; | |
case 'second' : return days * 86400 + milliseconds / 1000; | |
// Math.floor prevents floating point math errors here | |
case 'millisecond': return Math.floor(days * 864e5) + milliseconds; | |
default: throw new Error('Unknown unit ' + units); | |
} | |
} | |
} | |
// TODO: Use this.as('ms')? | |
function valueOf$1 () { | |
if (!this.isValid()) { | |
return NaN; | |
} | |
return ( | |
this._milliseconds + | |
this._days * 864e5 + | |
(this._months % 12) * 2592e6 + | |
toInt(this._months / 12) * 31536e6 | |
); | |
} | |
function makeAs (alias) { | |
return function () { | |
return this.as(alias); | |
}; | |
} | |
var asMilliseconds = makeAs('ms'); | |
var asSeconds = makeAs('s'); | |
var asMinutes = makeAs('m'); | |
var asHours = makeAs('h'); | |
var asDays = makeAs('d'); | |
var asWeeks = makeAs('w'); | |
var asMonths = makeAs('M'); | |
var asYears = makeAs('y'); | |
function clone$1 () { | |
return createDuration(this); | |
} | |
function get$2 (units) { | |
units = normalizeUnits(units); | |
return this.isValid() ? this[units + 's']() : NaN; | |
} | |
function makeGetter(name) { | |
return function () { | |
return this.isValid() ? this._data[name] : NaN; | |
}; | |
} | |
var milliseconds = makeGetter('milliseconds'); | |
var seconds = makeGetter('seconds'); | |
var minutes = makeGetter('minutes'); | |
var hours = makeGetter('hours'); | |
var days = makeGetter('days'); | |
var months = makeGetter('months'); | |
var years = makeGetter('years'); | |
function weeks () { | |
return absFloor(this.days() / 7); | |
} | |
var round = Math.round; | |
var thresholds = { | |
ss: 44, // a few seconds to seconds | |
s : 45, // seconds to minute | |
m : 45, // minutes to hour | |
h : 22, // hours to day | |
d : 26, // days to month | |
M : 11 // months to year | |
}; | |
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize | |
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { | |
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); | |
} | |
function relativeTime$1 (posNegDuration, withoutSuffix, locale) { | |
var duration = createDuration(posNegDuration).abs(); | |
var seconds = round(duration.as('s')); | |
var minutes = round(duration.as('m')); | |
var hours = round(duration.as('h')); | |
var days = round(duration.as('d')); | |
var months = round(duration.as('M')); | |
var years = round(duration.as('y')); | |
var a = seconds <= thresholds.ss && ['s', seconds] || | |
seconds < thresholds.s && ['ss', seconds] || | |
minutes <= 1 && ['m'] || | |
minutes < thresholds.m && ['mm', minutes] || | |
hours <= 1 && ['h'] || | |
hours < thresholds.h && ['hh', hours] || | |
days <= 1 && ['d'] || | |
days < thresholds.d && ['dd', days] || | |
months <= 1 && ['M'] || | |
months < thresholds.M && ['MM', months] || | |
years <= 1 && ['y'] || ['yy', years]; | |
a[2] = withoutSuffix; | |
a[3] = +posNegDuration > 0; | |
a[4] = locale; | |
return substituteTimeAgo.apply(null, a); | |
} | |
// This function allows you to set the rounding function for relative time strings | |
function getSetRelativeTimeRounding (roundingFunction) { | |
if (roundingFunction === undefined) { | |
return round; | |
} | |
if (typeof(roundingFunction) === 'function') { | |
round = roundingFunction; | |
return true; | |
} | |
return false; | |
} | |
// This function allows you to set a threshold for relative time strings | |
function getSetRelativeTimeThreshold (threshold, limit) { | |
if (thresholds[threshold] === undefined) { | |
return false; | |
} | |
if (limit === undefined) { | |
return thresholds[threshold]; | |
} | |
thresholds[threshold] = limit; | |
if (threshold === 's') { | |
thresholds.ss = limit - 1; | |
} | |
return true; | |
} | |
function humanize (withSuffix) { | |
if (!this.isValid()) { | |
return this.localeData().invalidDate(); | |
} | |
var locale = this.localeData(); | |
var output = relativeTime$1(this, !withSuffix, locale); | |
if (withSuffix) { | |
output = locale.pastFuture(+this, output); | |
} | |
return locale.postformat(output); | |
} | |
var abs$1 = Math.abs; | |
function sign(x) { | |
return ((x > 0) - (x < 0)) || +x; | |
} | |
function toISOString$1() { | |
// for ISO strings we do not use the normal bubbling rules: | |
// * milliseconds bubble up until they become hours | |
// * days do not bubble at all | |
// * months bubble up until they become years | |
// This is because there is no context-free conversion between hours and days | |
// (think of clock changes) | |
// and also not between days and months (28-31 days per month) | |
if (!this.isValid()) { | |
return this.localeData().invalidDate(); | |
} | |
var seconds = abs$1(this._milliseconds) / 1000; | |
var days = abs$1(this._days); | |
var months = abs$1(this._months); | |
var minutes, hours, years; | |
// 3600 seconds -> 60 minutes -> 1 hour | |
minutes = absFloor(seconds / 60); | |
hours = absFloor(minutes / 60); | |
seconds %= 60; | |
minutes %= 60; | |
// 12 months -> 1 year | |
years = absFloor(months / 12); | |
months %= 12; | |
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js | |
var Y = years; | |
var M = months; | |
var D = days; | |
var h = hours; | |
var m = minutes; | |
var s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; | |
var total = this.asSeconds(); | |
if (!total) { | |
// this is the same as C#'s (Noda) and python (isodate)... | |
// but not other JS (goog.date) | |
return 'P0D'; | |
} | |
var totalSign = total < 0 ? '-' : ''; | |
var ymSign = sign(this._months) !== sign(total) ? '-' : ''; | |
var daysSign = sign(this._days) !== sign(total) ? '-' : ''; | |
var hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; | |
return totalSign + 'P' + | |
(Y ? ymSign + Y + 'Y' : '') + | |
(M ? ymSign + M + 'M' : '') + | |
(D ? daysSign + D + 'D' : '') + | |
((h || m || s) ? 'T' : '') + | |
(h ? hmsSign + h + 'H' : '') + | |
(m ? hmsSign + m + 'M' : '') + | |
(s ? hmsSign + s + 'S' : ''); | |
} | |
var proto$2 = Duration.prototype; | |
proto$2.isValid = isValid$1; | |
proto$2.abs = abs; | |
proto$2.add = add$1; | |
proto$2.subtract = subtract$1; | |
proto$2.as = as; | |
proto$2.asMilliseconds = asMilliseconds; | |
proto$2.asSeconds = asSeconds; | |
proto$2.asMinutes = asMinutes; | |
proto$2.asHours = asHours; | |
proto$2.asDays = asDays; | |
proto$2.asWeeks = asWeeks; | |
proto$2.asMonths = asMonths; | |
proto$2.asYears = asYears; | |
proto$2.valueOf = valueOf$1; | |
proto$2._bubble = bubble; | |
proto$2.clone = clone$1; | |
proto$2.get = get$2; | |
proto$2.milliseconds = milliseconds; | |
proto$2.seconds = seconds; | |
proto$2.minutes = minutes; | |
proto$2.hours = hours; | |
proto$2.days = days; | |
proto$2.weeks = weeks; | |
proto$2.months = months; | |
proto$2.years = years; | |
proto$2.humanize = humanize; | |
proto$2.toISOString = toISOString$1; | |
proto$2.toString = toISOString$1; | |
proto$2.toJSON = toISOString$1; | |
proto$2.locale = locale; | |
proto$2.localeData = localeData; | |
// Deprecations | |
proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1); | |
proto$2.lang = lang; | |
// Side effect imports | |
// FORMATTING | |
addFormatToken('X', 0, 0, 'unix'); | |
addFormatToken('x', 0, 0, 'valueOf'); | |
// PARSING | |
addRegexToken('x', matchSigned); | |
addRegexToken('X', matchTimestamp); | |
addParseToken('X', function (input, array, config) { | |
config._d = new Date(parseFloat(input, 10) * 1000); | |
}); | |
addParseToken('x', function (input, array, config) { | |
config._d = new Date(toInt(input)); | |
}); | |
// Side effect imports | |
hooks.version = '2.20.1'; | |
setHookCallback(createLocal); | |
hooks.fn = proto; | |
hooks.min = min; | |
hooks.max = max; | |
hooks.now = now; | |
hooks.utc = createUTC; | |
hooks.unix = createUnix; | |
hooks.months = listMonths; | |
hooks.isDate = isDate; | |
hooks.locale = getSetGlobalLocale; | |
hooks.invalid = createInvalid; | |
hooks.duration = createDuration; | |
hooks.isMoment = isMoment; | |
hooks.weekdays = listWeekdays; | |
hooks.parseZone = createInZone; | |
hooks.localeData = getLocale; | |
hooks.isDuration = isDuration; | |
hooks.monthsShort = listMonthsShort; | |
hooks.weekdaysMin = listWeekdaysMin; | |
hooks.defineLocale = defineLocale; | |
hooks.updateLocale = updateLocale; | |
hooks.locales = listLocales; | |
hooks.weekdaysShort = listWeekdaysShort; | |
hooks.normalizeUnits = normalizeUnits; | |
hooks.relativeTimeRounding = getSetRelativeTimeRounding; | |
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; | |
hooks.calendarFormat = getCalendarFormat; | |
hooks.prototype = proto; | |
// currently HTML5 input type only supports 24-hour formats | |
hooks.HTML5_FMT = { | |
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // <input type="datetime-local" /> | |
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // <input type="datetime-local" step="1" /> | |
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // <input type="datetime-local" step="0.001" /> | |
DATE: 'YYYY-MM-DD', // <input type="date" /> | |
TIME: 'HH:mm', // <input type="time" /> | |
TIME_SECONDS: 'HH:mm:ss', // <input type="time" step="1" /> | |
TIME_MS: 'HH:mm:ss.SSS', // <input type="time" step="0.001" /> | |
WEEK: 'YYYY-[W]WW', // <input type="week" /> | |
MONTH: 'YYYY-MM' // <input type="month" /> | |
}; | |
return hooks; | |
}))); | |
/*** EXPORTS FROM exports-to-window-loader ***/ | |
window['moment'] = __webpack_require__(64); | |
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(435)(module))) | |
/***/ }), | |
/* 65 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var $ = __webpack_require__(21); | |
var toObject = __webpack_require__(62); | |
var nativeKeys = __webpack_require__(131); | |
var fails = __webpack_require__(28); | |
var FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); }); | |
// `Object.keys` method | |
// https://tc39.github.io/ecma262/#sec-object.keys | |
$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { | |
keys: function keys(it) { | |
return nativeKeys(toObject(it)); | |
} | |
}); | |
/***/ }), | |
/* 66 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(17); | |
__webpack_require__(15); | |
__webpack_require__(113); | |
__webpack_require__(31); | |
__webpack_require__(59); | |
__webpack_require__(42); | |
exports.__esModule = true; | |
exports.normalizeSelection = normalizeSelection; | |
exports.isSeparator = isSeparator; | |
exports.hasSubMenu = hasSubMenu; | |
exports.isDisabled = isDisabled; | |
exports.isSelectionDisabled = isSelectionDisabled; | |
exports.getValidSelection = getValidSelection; | |
exports.prepareVerticalAlignClass = prepareVerticalAlignClass; | |
exports.prepareHorizontalAlignClass = prepareHorizontalAlignClass; | |
exports.getAlignmentClasses = getAlignmentClasses; | |
exports.align = align; | |
exports.checkSelectionConsistency = checkSelectionConsistency; | |
exports.markLabelAsSelected = markLabelAsSelected; | |
exports.isItemHidden = isItemHidden; | |
exports.filterSeparators = filterSeparators; | |
var _array = __webpack_require__(3); | |
var _element = __webpack_require__(8); | |
var _separator = __webpack_require__(182); | |
function normalizeSelection(selRanges) { | |
return (0, _array.arrayMap)(selRanges, function (range) { | |
return { | |
start: range.getTopLeftCorner(), | |
end: range.getBottomRightCorner() | |
}; | |
}); | |
} | |
function isSeparator(cell) { | |
return (0, _element.hasClass)(cell, 'htSeparator'); | |
} | |
function hasSubMenu(cell) { | |
return (0, _element.hasClass)(cell, 'htSubmenu'); | |
} | |
function isDisabled(cell) { | |
return (0, _element.hasClass)(cell, 'htDisabled'); | |
} | |
function isSelectionDisabled(cell) { | |
return (0, _element.hasClass)(cell, 'htSelectionDisabled'); | |
} | |
function getValidSelection(hot) { | |
var selected = hot.getSelected(); | |
if (!selected) { | |
return null; | |
} | |
if (selected[0] < 0) { | |
return null; | |
} | |
return selected; | |
} | |
function prepareVerticalAlignClass(className, alignment) { | |
if (className.indexOf(alignment) !== -1) { | |
return className; | |
} | |
var replacedClassName = className.replace('htTop', '').replace('htMiddle', '').replace('htBottom', '').replace(' ', ''); | |
return "".concat(replacedClassName, " ").concat(alignment); | |
} | |
function prepareHorizontalAlignClass(className, alignment) { | |
if (className.indexOf(alignment) !== -1) { | |
return className; | |
} | |
var replacedClassName = className.replace('htLeft', '').replace('htCenter', '').replace('htRight', '').replace('htJustify', '').replace(' ', ''); | |
return "".concat(replacedClassName, " ").concat(alignment); | |
} | |
function getAlignmentClasses(ranges, callback) { | |
var classes = {}; | |
(0, _array.arrayEach)(ranges, function (_ref) { | |
var from = _ref.from, | |
to = _ref.to; | |
for (var row = from.row; row <= to.row; row++) { | |
for (var col = from.col; col <= to.col; col++) { | |
if (!classes[row]) { | |
classes[row] = []; | |
} | |
classes[row][col] = callback(row, col); | |
} | |
} | |
}); | |
return classes; | |
} | |
function align(ranges, type, alignment, cellDescriptor, propertySetter) { | |
(0, _array.arrayEach)(ranges, function (_ref2) { | |
var from = _ref2.from, | |
to = _ref2.to; | |
if (from.row === to.row && from.col === to.col) { | |
applyAlignClassName(from.row, from.col, type, alignment, cellDescriptor, propertySetter); | |
} else { | |
for (var row = from.row; row <= to.row; row++) { | |
for (var col = from.col; col <= to.col; col++) { | |
applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter); | |
} | |
} | |
} | |
}); | |
} | |
function applyAlignClassName(row, col, type, alignment, cellDescriptor, propertySetter) { | |
var cellMeta = cellDescriptor(row, col); | |
var className = alignment; | |
if (cellMeta.className) { | |
if (type === 'vertical') { | |
className = prepareVerticalAlignClass(cellMeta.className, alignment); | |
} else { | |
className = prepareHorizontalAlignClass(cellMeta.className, alignment); | |
} | |
} | |
propertySetter(row, col, 'className', className); | |
} | |
function checkSelectionConsistency(ranges, comparator) { | |
var result = false; | |
if (Array.isArray(ranges)) { | |
(0, _array.arrayEach)(ranges, function (range) { | |
range.forAll(function (row, col) { | |
if (comparator(row, col)) { | |
result = true; | |
return false; | |
} | |
}); | |
return result; | |
}); | |
} | |
return result; | |
} | |
function markLabelAsSelected(label) { | |
// workaround for https://github.com/handsontable/handsontable/issues/1946 | |
return "<span class=\"selected\">".concat(String.fromCharCode(10003), "</span>").concat(label); | |
} | |
function isItemHidden(item, instance) { | |
return !item.hidden || !(typeof item.hidden === 'function' && item.hidden.call(instance)); | |
} | |
function shiftSeparators(items, separator) { | |
var result = items.slice(0); | |
for (var i = 0; i < result.length;) { | |
if (result[i].name === separator) { | |
result.shift(); | |
} else { | |
break; | |
} | |
} | |
return result; | |
} | |
function popSeparators(items, separator) { | |
var result = items.slice(0); | |
result.reverse(); | |
result = shiftSeparators(result, separator); | |
result.reverse(); | |
return result; | |
} | |
function removeDuplicatedSeparators(items) { | |
var result = []; | |
(0, _array.arrayEach)(items, function (value, index) { | |
if (index > 0) { | |
if (result[result.length - 1].name !== value.name) { | |
result.push(value); | |
} | |
} else { | |
result.push(value); | |
} | |
}); | |
return result; | |
} | |
function filterSeparators(items) { | |
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _separator.KEY; | |
var result = items.slice(0); | |
result = shiftSeparators(result, separator); | |
result = popSeparators(result, separator); | |
result = removeDuplicatedSeparators(result); | |
return result; | |
} | |
/***/ }), | |
/* 67 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
// toObject with fallback for non-array-like ES3 strings | |
var IndexedObject = __webpack_require__(124); | |
var requireObjectCoercible = __webpack_require__(54); | |
module.exports = function (it) { | |
return IndexedObject(requireObjectCoercible(it)); | |
}; | |
/***/ }), | |
/* 68 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var DESCRIPTORS = __webpack_require__(51); | |
var definePropertyModule = __webpack_require__(56); | |
var createPropertyDescriptor = __webpack_require__(97); | |
module.exports = DESCRIPTORS ? function (object, key, value) { | |
return definePropertyModule.f(object, key, createPropertyDescriptor(1, value)); | |
} : function (object, key, value) { | |
object[key] = value; | |
return object; | |
}; | |
/***/ }), | |
/* 69 */ | |
/***/ (function(module, exports) { | |
function _taggedTemplateLiteral(strings, raw) { | |
if (!raw) { | |
raw = strings.slice(0); | |
} | |
return Object.freeze(Object.defineProperties(strings, { | |
raw: { | |
value: Object.freeze(raw) | |
} | |
})); | |
} | |
module.exports = _taggedTemplateLiteral; | |
/***/ }), | |
/* 70 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(42); | |
__webpack_require__(137); | |
exports.__esModule = true; | |
exports.toSingleLine = toSingleLine; | |
var _array = __webpack_require__(3); | |
/* eslint-disable import/prefer-default-export */ | |
/** | |
* Tags a multiline string and return new one without line break characters and following spaces. | |
* | |
* @param {Array} strings Parts of the entire string without expressions. | |
* @param {...String} expressions Expressions converted to strings, which are added to the entire string. | |
* @returns {String} | |
*/ | |
function toSingleLine(strings) { | |
for (var _len = arguments.length, expressions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
expressions[_key - 1] = arguments[_key]; | |
} | |
var result = (0, _array.arrayReduce)(strings, function (previousValue, currentValue, index) { | |
var valueWithoutWhiteSpaces = currentValue.replace(/(?:\r?\n\s+)/g, ''); | |
var expressionForIndex = expressions[index] ? expressions[index] : ''; | |
return previousValue + valueWithoutWhiteSpaces + expressionForIndex; | |
}, ''); | |
return result.trim(); | |
} | |
/***/ }), | |
/* 71 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var aFunction = __webpack_require__(157); | |
var toObject = __webpack_require__(62); | |
var fails = __webpack_require__(28); | |
var sloppyArrayMethod = __webpack_require__(107); | |
var nativeSort = [].sort; | |
var test = [1, 2, 3]; | |
// IE8- | |
var FAILS_ON_UNDEFINED = fails(function () { | |
test.sort(undefined); | |
}); | |
// V8 bug | |
var FAILS_ON_NULL = fails(function () { | |
test.sort(null); | |
}); | |
// Old WebKit | |
var SLOPPY_METHOD = sloppyArrayMethod('sort'); | |
var FORCED = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || SLOPPY_METHOD; | |
// `Array.prototype.sort` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.sort | |
$({ target: 'Array', proto: true, forced: FORCED }, { | |
sort: function sort(comparefn) { | |
return comparefn === undefined | |
? nativeSort.call(toObject(this)) | |
: nativeSort.call(toObject(this), aFunction(comparefn)); | |
} | |
}); | |
/***/ }), | |
/* 72 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
var _indexMapper = _interopRequireDefault(__webpack_require__(501)); | |
exports.IndexMapper = _indexMapper.default; | |
var _physicalIndexToValueMap = _interopRequireDefault(__webpack_require__(370)); | |
exports.PhysicalIndexToValueMap = _physicalIndexToValueMap.default; | |
var _visualIndexToPhysicalIndexMap = _interopRequireDefault(__webpack_require__(367)); | |
exports.VisualIndexToPhysicalIndexMap = _visualIndexToPhysicalIndexMap.default; | |
var _skipMap = _interopRequireDefault(__webpack_require__(369)); | |
exports.SkipMap = _skipMap.default; | |
var _indexMap = _interopRequireDefault(__webpack_require__(179)); | |
exports.IndexMap = _indexMap.default; | |
var _utils = __webpack_require__(502); | |
exports.getIncreasedIndexes = _utils.getIncreasedIndexes; | |
exports.getDecreasedIndexes = _utils.getDecreasedIndexes; | |
exports.alterUtilsFactory = _utils.alterUtilsFactory; | |
/***/ }), | |
/* 73 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var global = __webpack_require__(38); | |
var shared = __webpack_require__(99); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var has = __webpack_require__(55); | |
var setGlobal = __webpack_require__(148); | |
var nativeFunctionToString = __webpack_require__(191); | |
var InternalStateModule = __webpack_require__(88); | |
var getInternalState = InternalStateModule.get; | |
var enforceInternalState = InternalStateModule.enforce; | |
var TEMPLATE = String(nativeFunctionToString).split('toString'); | |
shared('inspectSource', function (it) { | |
return nativeFunctionToString.call(it); | |
}); | |
(module.exports = function (O, key, value, options) { | |
var unsafe = options ? !!options.unsafe : false; | |
var simple = options ? !!options.enumerable : false; | |
var noTargetGet = options ? !!options.noTargetGet : false; | |
if (typeof value == 'function') { | |
if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); | |
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); | |
} | |
if (O === global) { | |
if (simple) O[key] = value; | |
else setGlobal(key, value); | |
return; | |
} else if (!unsafe) { | |
delete O[key]; | |
} else if (!noTargetGet && O[key]) { | |
simple = true; | |
} | |
if (simple) O[key] = value; | |
else createNonEnumerableProperty(O, key, value); | |
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative | |
})(Function.prototype, 'toString', function toString() { | |
return typeof this == 'function' && getInternalState(this).source || nativeFunctionToString.call(this); | |
}); | |
/***/ }), | |
/* 74 */ | |
/***/ (function(module, exports) { | |
function _defineProperty(obj, key, value) { | |
if (key in obj) { | |
Object.defineProperty(obj, key, { | |
value: value, | |
enumerable: true, | |
configurable: true, | |
writable: true | |
}); | |
} else { | |
obj[key] = value; | |
} | |
return obj; | |
} | |
module.exports = _defineProperty; | |
/***/ }), | |
/* 75 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var collection = __webpack_require__(134); | |
var collectionStrong = __webpack_require__(210); | |
// `Set` constructor | |
// https://tc39.github.io/ecma262/#sec-set-objects | |
module.exports = collection('Set', function (get) { | |
return function Set() { return get(this, arguments.length ? arguments[0] : undefined); }; | |
}, collectionStrong); | |
/***/ }), | |
/* 76 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.setBrowserMeta = setBrowserMeta; | |
exports.isChrome = isChrome; | |
exports.isEdge = isEdge; | |
exports.isIE = isIE; | |
exports.isIE8 = isIE8; | |
exports.isIE9 = isIE9; | |
exports.isMSBrowser = isMSBrowser; | |
exports.isMobileBrowser = isMobileBrowser; | |
exports.isSafari = isSafari; | |
exports.isFirefox = isFirefox; | |
var _object = __webpack_require__(4); | |
var tester = function tester(testerFunc) { | |
var result = { | |
value: false | |
}; | |
result.test = function (ua, vendor) { | |
result.value = testerFunc(ua, vendor); | |
}; | |
return result; | |
}; | |
var browsers = { | |
chrome: tester(function (ua, vendor) { | |
return /Chrome/.test(ua) && /Google/.test(vendor); | |
}), | |
edge: tester(function (ua) { | |
return /Edge/.test(ua); | |
}), | |
firefox: tester(function (ua) { | |
return /Firefox/.test(ua); | |
}), | |
ie: tester(function (ua) { | |
return /Trident/.test(ua); | |
}), | |
// eslint-disable-next-line no-restricted-globals | |
ie8: tester(function () { | |
return !document.createTextNode('test').textContent; | |
}), | |
// eslint-disable-next-line no-restricted-globals | |
ie9: tester(function () { | |
return !!document.documentMode; | |
}), | |
mobile: tester(function (ua) { | |
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua); | |
}), | |
safari: tester(function (ua, vendor) { | |
return /Safari/.test(ua) && /Apple Computer/.test(vendor); | |
}) | |
}; | |
function setBrowserMeta() { | |
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | |
_ref$userAgent = _ref.userAgent, | |
userAgent = _ref$userAgent === void 0 ? navigator.userAgent : _ref$userAgent, | |
_ref$vendor = _ref.vendor, | |
vendor = _ref$vendor === void 0 ? navigator.vendor : _ref$vendor; | |
(0, _object.objectEach)(browsers, function (_ref2) { | |
var test = _ref2.test; | |
return void test(userAgent, vendor); | |
}); | |
} | |
setBrowserMeta(); | |
function isChrome() { | |
return browsers.chrome.value; | |
} | |
function isEdge() { | |
return browsers.edge.value; | |
} | |
function isIE() { | |
return browsers.ie.value; | |
} | |
function isIE8() { | |
return browsers.ie8.value; | |
} | |
function isIE9() { | |
return browsers.ie9.value; | |
} | |
function isMSBrowser() { | |
return browsers.ie.value || browsers.edge.value; | |
} | |
function isMobileBrowser() { | |
return browsers.mobile.value; | |
} | |
function isSafari() { | |
return browsers.safari.value; | |
} | |
function isFirefox() { | |
return browsers.firefox.value; | |
} | |
/***/ }), | |
/* 77 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(15); | |
__webpack_require__(9); | |
__webpack_require__(39); | |
__webpack_require__(42); | |
exports.__esModule = true; | |
exports.toUpperCaseFirst = toUpperCaseFirst; | |
exports.equalsIgnoreCase = equalsIgnoreCase; | |
exports.randomString = randomString; | |
exports.isPercentValue = isPercentValue; | |
exports.substitute = substitute; | |
exports.stripTags = stripTags; | |
var _mixed = __webpack_require__(24); | |
/** | |
* Convert string to upper case first letter. | |
* | |
* @param {String} string String to convert. | |
* @returns {String} | |
*/ | |
function toUpperCaseFirst(string) { | |
return string[0].toUpperCase() + string.substr(1); | |
} | |
/** | |
* Compare strings case insensitively. | |
* | |
* @param {...String} strings Strings to compare. | |
* @returns {Boolean} | |
*/ | |
function equalsIgnoreCase() { | |
var unique = []; | |
for (var _len = arguments.length, strings = new Array(_len), _key = 0; _key < _len; _key++) { | |
strings[_key] = arguments[_key]; | |
} | |
var length = strings.length; | |
while (length) { | |
length -= 1; | |
var string = (0, _mixed.stringify)(strings[length]).toLowerCase(); | |
if (unique.indexOf(string) === -1) { | |
unique.push(string); | |
} | |
} | |
return unique.length === 1; | |
} | |
/** | |
* Generates a random hex string. Used as namespace for Handsontable instance events. | |
* | |
* @return {String} Returns 16-long character random string (eq. `'92b1bfc74ec4'`). | |
*/ | |
function randomString() { | |
function s4() { | |
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); | |
} | |
return s4() + s4() + s4() + s4(); | |
} | |
/** | |
* Checks if value is valid percent. | |
* | |
* @param {String} value | |
* @returns {Boolean} | |
*/ | |
function isPercentValue(value) { | |
return /^([0-9][0-9]?%$)|(^100%$)/.test(value); | |
} | |
/** | |
* Substitute strings placed beetwen square brackets into value defined in `variables` object. String names defined in | |
* square brackets must be the same as property name of `variables` object. | |
* | |
* @param {String} template Template string. | |
* @param {Object} variables Object which contains all available values which can be injected into template. | |
* @returns {String} | |
*/ | |
function substitute(template) { | |
var variables = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | |
return "".concat(template).replace(/(?:\\)?\[([^[\]]+)]/g, function (match, name) { | |
if (match.charAt(0) === '\\') { | |
return match.substr(1, match.length - 1); | |
} | |
return variables[name] === void 0 ? '' : variables[name]; | |
}); | |
} | |
var STRIP_TAGS_REGEX = /<\/?\w+\/?>|<\w+[\s|/][^>]*>/gi; | |
/** | |
* Strip any HTML tag from the string. | |
* | |
* @param {String} string String to cut HTML from. | |
* @return {String} | |
*/ | |
function stripTags(string) { | |
return "".concat(string).replace(STRIP_TAGS_REGEX, ''); | |
} | |
/***/ }), | |
/* 78 */ | |
/***/ (function(module, exports) { | |
var toString = {}.toString; | |
module.exports = function (it) { | |
return toString.call(it).slice(8, -1); | |
}; | |
/***/ }), | |
/* 79 */ | |
/***/ (function(module, exports) { | |
var ceil = Math.ceil; | |
var floor = Math.floor; | |
// `ToInteger` abstract operation | |
// https://tc39.github.io/ecma262/#sec-tointeger | |
module.exports = function (argument) { | |
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); | |
}; | |
/***/ }), | |
/* 80 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(12); | |
__webpack_require__(41); | |
__webpack_require__(9); | |
__webpack_require__(11); | |
__webpack_require__(13); | |
exports.__esModule = true; | |
exports.default = staticRegister; | |
exports.collection = void 0; | |
var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(33)); | |
var collection = new Map(); | |
exports.collection = collection; | |
function staticRegister() { | |
var namespace = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'common'; | |
if (!collection.has(namespace)) { | |
collection.set(namespace, new Map()); | |
} | |
var subCollection = collection.get(namespace); | |
/** | |
* Register an item to the collection. If the item under the same was exist earlier then this item will be replaced with new one. | |
* | |
* @param {String} name Identification of the item. | |
* @param {*} item Item to save in the collection. | |
*/ | |
function register(name, item) { | |
subCollection.set(name, item); | |
} | |
/** | |
* Retrieve the item from the collection. | |
* | |
* @param {String} name Identification of the item. | |
* @returns {*} Returns item which was saved in the collection. | |
*/ | |
function getItem(name) { | |
return subCollection.get(name); | |
} | |
/** | |
* Check if item under specyfied name is exists. | |
* | |
* @param {String} name Identification of the item. | |
* @returns {Boolean} Returns `true` or `false` depends on if element exists in the collection. | |
*/ | |
function hasItem(name) { | |
return subCollection.has(name); | |
} | |
/** | |
* Retrieve list of names registered from the collection. | |
* | |
* @returns {Array} Returns an array of strings with all names under which objects are stored. | |
*/ | |
function getNames() { | |
return (0, _toConsumableArray2.default)(subCollection.keys()); | |
} | |
/** | |
* Retrieve all registered values from the collection. | |
* | |
* @returns {Array} Returns an array with all values stored in the collection. | |
*/ | |
function getValues() { | |
return (0, _toConsumableArray2.default)(subCollection.values()); | |
} | |
return { | |
register: register, | |
getItem: getItem, | |
hasItem: hasItem, | |
getNames: getNames, | |
getValues: getValues | |
}; | |
} | |
/***/ }), | |
/* 81 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(9); | |
__webpack_require__(39); | |
__webpack_require__(93); | |
__webpack_require__(36); | |
exports.__esModule = true; | |
exports.requestAnimationFrame = requestAnimationFrame; | |
exports.isClassListSupported = isClassListSupported; | |
exports.isTextContentSupported = isTextContentSupported; | |
exports.isGetComputedStyleSupported = isGetComputedStyleSupported; | |
exports.cancelAnimationFrame = cancelAnimationFrame; | |
exports.isTouchSupported = isTouchSupported; | |
exports.isWebComponentSupportedNatively = isWebComponentSupportedNatively; | |
exports.hasCaptionProblem = hasCaptionProblem; | |
exports.getComparisonFunction = getComparisonFunction; | |
exports.isPassiveEventSupported = isPassiveEventSupported; | |
var _typeof2 = _interopRequireDefault(__webpack_require__(46)); | |
// https://gist.github.com/paulirish/1579671 | |
/* eslint-disable no-restricted-globals */ | |
var lastTime = 0; | |
var vendors = ['ms', 'moz', 'webkit', 'o']; | |
var _requestAnimationFrame = window.requestAnimationFrame; | |
var _cancelAnimationFrame = window.cancelAnimationFrame; | |
for (var x = 0; x < vendors.length && !_requestAnimationFrame; ++x) { | |
_requestAnimationFrame = window["".concat(vendors[x], "RequestAnimationFrame")]; | |
_cancelAnimationFrame = window["".concat(vendors[x], "CancelAnimationFrame")] || window["".concat(vendors[x], "CancelRequestAnimationFrame")]; | |
} | |
if (!_requestAnimationFrame) { | |
_requestAnimationFrame = function _requestAnimationFrame(callback) { | |
var currTime = new Date().getTime(); | |
var timeToCall = Math.max(0, 16 - (currTime - lastTime)); | |
var id = window.setTimeout(function () { | |
callback(currTime + timeToCall); | |
}, timeToCall); | |
lastTime = currTime + timeToCall; | |
return id; | |
}; | |
} | |
if (!_cancelAnimationFrame) { | |
_cancelAnimationFrame = function _cancelAnimationFrame(id) { | |
clearTimeout(id); | |
}; | |
} | |
/** | |
* Polyfill for requestAnimationFrame | |
* | |
* @param {Function} callback | |
* @returns {Number} | |
*/ | |
function requestAnimationFrame(callback) { | |
return _requestAnimationFrame.call(window, callback); | |
} | |
function isClassListSupported() { | |
return !!document.documentElement.classList; | |
} | |
function isTextContentSupported() { | |
return !!document.createTextNode('test').textContent; | |
} | |
function isGetComputedStyleSupported() { | |
return !!window.getComputedStyle; | |
} | |
/** | |
* Polyfill for cancelAnimationFrame | |
* | |
* @param {Number} id | |
*/ | |
function cancelAnimationFrame(id) { | |
_cancelAnimationFrame.call(window, id); | |
} | |
function isTouchSupported() { | |
return 'ontouchstart' in window; | |
} | |
/** | |
* Checks if browser is support web components natively | |
* | |
* @returns {Boolean} | |
*/ | |
function isWebComponentSupportedNatively() { | |
var test = document.createElement('div'); | |
return !!(test.createShadowRoot && test.createShadowRoot.toString().match(/\[native code\]/)); | |
} | |
var _hasCaptionProblem; | |
function detectCaptionProblem() { | |
var TABLE = document.createElement('TABLE'); | |
TABLE.style.borderSpacing = '0'; | |
TABLE.style.borderWidth = '0'; | |
TABLE.style.padding = '0'; | |
var TBODY = document.createElement('TBODY'); | |
TABLE.appendChild(TBODY); | |
TBODY.appendChild(document.createElement('TR')); | |
TBODY.firstChild.appendChild(document.createElement('TD')); | |
TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>'; | |
var CAPTION = document.createElement('CAPTION'); | |
CAPTION.innerHTML = 'c<br>c<br>c<br>c'; | |
CAPTION.style.padding = '0'; | |
CAPTION.style.margin = '0'; | |
TABLE.insertBefore(CAPTION, TBODY); | |
document.body.appendChild(TABLE); | |
_hasCaptionProblem = TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight; // boolean | |
document.body.removeChild(TABLE); | |
} | |
function hasCaptionProblem() { | |
if (_hasCaptionProblem === void 0) { | |
detectCaptionProblem(); | |
} | |
return _hasCaptionProblem; | |
} | |
var comparisonFunction; | |
/** | |
* Get string comparison function for sorting purposes. It supports multilingual string comparison base on Internationalization API. | |
* | |
* @param {String} [language] | |
* @param {Object} [options] | |
* @returns {*} | |
*/ | |
function getComparisonFunction(language) { | |
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | |
if (comparisonFunction) { | |
return comparisonFunction; | |
} | |
if ((typeof Intl === "undefined" ? "undefined" : (0, _typeof2.default)(Intl)) === 'object') { | |
comparisonFunction = new Intl.Collator(language, options).compare; | |
} else if (typeof String.prototype.localeCompare === 'function') { | |
comparisonFunction = function comparisonFunction(a, b) { | |
return "".concat(a).localeCompare(b); | |
}; | |
} else { | |
comparisonFunction = function comparisonFunction(a, b) { | |
if (a === b) { | |
return 0; | |
} | |
return a > b ? -1 : 1; | |
}; | |
} | |
return comparisonFunction; | |
} | |
var passiveSupported; | |
/** | |
* Checks if browser supports passive events. | |
* | |
* @returns {Boolean} | |
*/ | |
function isPassiveEventSupported() { | |
if (passiveSupported !== void 0) { | |
return passiveSupported; | |
} | |
try { | |
var options = { | |
get passive() { | |
passiveSupported = true; | |
} | |
}; // eslint-disable-next-line no-restricted-globals | |
window.addEventListener('test', options, options); // eslint-disable-next-line no-restricted-globals | |
window.removeEventListener('test', options, options); | |
} catch (err) { | |
passiveSupported = false; | |
} | |
return passiveSupported; | |
} | |
/***/ }), | |
/* 82 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
exports.getValidator = _getItem; | |
exports.getRegisteredValidators = exports.getRegisteredValidatorNames = exports.hasValidator = exports.registerValidator = void 0; | |
var _staticRegister2 = _interopRequireDefault(__webpack_require__(80)); | |
var _autocompleteValidator = _interopRequireDefault(__webpack_require__(476)); | |
var _dateValidator = _interopRequireDefault(__webpack_require__(477)); | |
var _numericValidator = _interopRequireDefault(__webpack_require__(479)); | |
var _timeValidator = _interopRequireDefault(__webpack_require__(480)); | |
var _staticRegister = (0, _staticRegister2.default)('validators'), | |
register = _staticRegister.register, | |
getItem = _staticRegister.getItem, | |
hasItem = _staticRegister.hasItem, | |
getNames = _staticRegister.getNames, | |
getValues = _staticRegister.getValues; | |
exports.getRegisteredValidators = getValues; | |
exports.getRegisteredValidatorNames = getNames; | |
exports.hasValidator = hasItem; | |
exports.registerValidator = register; | |
register('autocomplete', _autocompleteValidator.default); | |
register('date', _dateValidator.default); | |
register('numeric', _numericValidator.default); | |
register('time', _timeValidator.default); | |
/** | |
* Retrieve validator function. | |
* | |
* @param {String} name Validator identification. | |
* @returns {Function} Returns validator function. | |
*/ | |
function _getItem(name) { | |
if (typeof name === 'function') { | |
return name; | |
} | |
if (!hasItem(name)) { | |
throw Error("No registered validator found under \"".concat(name, "\" name")); | |
} | |
return getItem(name); | |
} | |
/***/ }), | |
/* 83 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var DESCRIPTORS = __webpack_require__(51); | |
var global = __webpack_require__(38); | |
var isForced = __webpack_require__(130); | |
var redefine = __webpack_require__(73); | |
var has = __webpack_require__(55); | |
var classof = __webpack_require__(78); | |
var inheritIfRequired = __webpack_require__(159); | |
var toPrimitive = __webpack_require__(98); | |
var fails = __webpack_require__(28); | |
var create = __webpack_require__(103); | |
var getOwnPropertyNames = __webpack_require__(101).f; | |
var getOwnPropertyDescriptor = __webpack_require__(92).f; | |
var defineProperty = __webpack_require__(56).f; | |
var trim = __webpack_require__(213).trim; | |
var NUMBER = 'Number'; | |
var NativeNumber = global[NUMBER]; | |
var NumberPrototype = NativeNumber.prototype; | |
// Opera ~12 has broken Object#toString | |
var BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER; | |
// `ToNumber` abstract operation | |
// https://tc39.github.io/ecma262/#sec-tonumber | |
var toNumber = function (argument) { | |
var it = toPrimitive(argument, false); | |
var first, third, radix, maxCode, digits, length, index, code; | |
if (typeof it == 'string' && it.length > 2) { | |
it = trim(it); | |
first = it.charCodeAt(0); | |
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 of /^0b[01]+$/i | |
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i | |
default: return +it; | |
} | |
digits = it.slice(2); | |
length = digits.length; | |
for (index = 0; index < length; index++) { | |
code = digits.charCodeAt(index); | |
// 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; | |
}; | |
// `Number` constructor | |
// https://tc39.github.io/ecma262/#sec-number-constructor | |
if (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { | |
var NumberWrapper = function Number(value) { | |
var it = arguments.length < 1 ? 0 : value; | |
var dummy = this; | |
return dummy instanceof NumberWrapper | |
// check on 1..constructor(foo) case | |
&& (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER) | |
? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); | |
}; | |
for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : ( | |
// ES3: | |
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + | |
// ES2015 (in case, if modules with ES2015 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(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) { | |
defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key)); | |
} | |
} | |
NumberWrapper.prototype = NumberPrototype; | |
NumberPrototype.constructor = NumberWrapper; | |
redefine(global, NUMBER, NumberWrapper); | |
} | |
/***/ }), | |
/* 84 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var $ = __webpack_require__(21); | |
var isInteger = __webpack_require__(490); | |
// `Number.isInteger` method | |
// https://tc39.github.io/ecma262/#sec-number.isinteger | |
$({ target: 'Number', stat: true }, { | |
isInteger: isInteger | |
}); | |
/***/ }), | |
/* 85 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
var _interopRequireWildcard = __webpack_require__(10); | |
__webpack_require__(15); | |
exports.__esModule = true; | |
exports.predefinedItems = predefinedItems; | |
exports.addItem = addItem; | |
exports.ITEMS = exports.UNDO = exports.NO_ITEMS = exports.SEPARATOR = exports.ROW_BELOW = exports.ROW_ABOVE = exports.REMOVE_ROW = exports.REMOVE_COLUMN = exports.REDO = exports.READ_ONLY = exports.COLUMN_RIGHT = exports.COLUMN_LEFT = exports.CLEAR_COLUMN = exports.ALIGNMENT = void 0; | |
var _defineProperty2 = _interopRequireDefault(__webpack_require__(74)); | |
var _object = __webpack_require__(4); | |
var _alignment = _interopRequireWildcard(__webpack_require__(542)); | |
exports.ALIGNMENT = _alignment.KEY; | |
var _clearColumn = _interopRequireWildcard(__webpack_require__(543)); | |
exports.CLEAR_COLUMN = _clearColumn.KEY; | |
var _columnLeft = _interopRequireWildcard(__webpack_require__(544)); | |
exports.COLUMN_LEFT = _columnLeft.KEY; | |
var _columnRight = _interopRequireWildcard(__webpack_require__(545)); | |
exports.COLUMN_RIGHT = _columnRight.KEY; | |
var _readOnly = _interopRequireWildcard(__webpack_require__(546)); | |
exports.READ_ONLY = _readOnly.KEY; | |
var _redo = _interopRequireWildcard(__webpack_require__(547)); | |
exports.REDO = _redo.KEY; | |
var _removeColumn = _interopRequireWildcard(__webpack_require__(548)); | |
exports.REMOVE_COLUMN = _removeColumn.KEY; | |
var _removeRow = _interopRequireWildcard(__webpack_require__(549)); | |
exports.REMOVE_ROW = _removeRow.KEY; | |
var _rowAbove = _interopRequireWildcard(__webpack_require__(550)); | |
exports.ROW_ABOVE = _rowAbove.KEY; | |
var _rowBelow = _interopRequireWildcard(__webpack_require__(551)); | |
exports.ROW_BELOW = _rowBelow.KEY; | |
var _separator = _interopRequireWildcard(__webpack_require__(182)); | |
exports.SEPARATOR = _separator.KEY; | |
var _noItems = _interopRequireWildcard(__webpack_require__(552)); | |
exports.NO_ITEMS = _noItems.KEY; | |
var _undo = _interopRequireWildcard(__webpack_require__(553)); | |
exports.UNDO = _undo.KEY; | |
var _predefinedItems2; | |
var ITEMS = [_rowAbove.KEY, _rowBelow.KEY, _columnLeft.KEY, _columnRight.KEY, _clearColumn.KEY, _removeRow.KEY, _removeColumn.KEY, _undo.KEY, _redo.KEY, _readOnly.KEY, _alignment.KEY, _separator.KEY, _noItems.KEY]; | |
exports.ITEMS = ITEMS; | |
var _predefinedItems = (_predefinedItems2 = {}, (0, _defineProperty2.default)(_predefinedItems2, _separator.KEY, _separator.default), (0, _defineProperty2.default)(_predefinedItems2, _noItems.KEY, _noItems.default), (0, _defineProperty2.default)(_predefinedItems2, _rowAbove.KEY, _rowAbove.default), (0, _defineProperty2.default)(_predefinedItems2, _rowBelow.KEY, _rowBelow.default), (0, _defineProperty2.default)(_predefinedItems2, _columnLeft.KEY, _columnLeft.default), (0, _defineProperty2.default)(_predefinedItems2, _columnRight.KEY, _columnRight.default), (0, _defineProperty2.default)(_predefinedItems2, _clearColumn.KEY, _clearColumn.default), (0, _defineProperty2.default)(_predefinedItems2, _removeRow.KEY, _removeRow.default), (0, _defineProperty2.default)(_predefinedItems2, _removeColumn.KEY, _removeColumn.default), (0, _defineProperty2.default)(_predefinedItems2, _undo.KEY, _undo.default), (0, _defineProperty2.default)(_predefinedItems2, _redo.KEY, _redo.default), (0, _defineProperty2.default)(_predefinedItems2, _readOnly.KEY, _readOnly.default), (0, _defineProperty2.default)(_predefinedItems2, _alignment.KEY, _alignment.default), _predefinedItems2); | |
/** | |
* Gets new object with all predefined menu items. | |
* | |
* @returns {Object} | |
*/ | |
function predefinedItems() { | |
var items = {}; | |
(0, _object.objectEach)(_predefinedItems, function (itemFactory, key) { | |
items[key] = itemFactory(); | |
}); | |
return items; | |
} | |
/** | |
* Add new predefined menu item to the collection. | |
* | |
* @param {String} key Menu command id. | |
* @param {Object} item Object command descriptor. | |
*/ | |
function addItem(key, item) { | |
if (ITEMS.indexOf(key) === -1) { | |
_predefinedItems[key] = item; | |
} | |
} | |
/***/ }), | |
/* 86 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(93); | |
__webpack_require__(42); | |
exports.__esModule = true; | |
exports.isFormulaExpression = isFormulaExpression; | |
exports.isFormulaExpressionEscaped = isFormulaExpressionEscaped; | |
exports.unescapeFormulaExpression = unescapeFormulaExpression; | |
exports.toUpperCaseFormula = toUpperCaseFormula; | |
exports.cellCoordFactory = cellCoordFactory; | |
/** | |
* Check if provided expression is valid formula expression. | |
* | |
* @param {*} expression Expression to check. | |
* @returns {Boolean} | |
*/ | |
function isFormulaExpression(expression) { | |
return typeof expression === 'string' && expression.length >= 2 && expression.charAt(0) === '='; | |
} | |
/** | |
* Check if provided formula expression is escaped. | |
* | |
* @param {*} expression Expression to check. | |
* @returns {Boolean} | |
*/ | |
function isFormulaExpressionEscaped(expression) { | |
return typeof expression === 'string' && expression.charAt(0) === '\'' && expression.charAt(1) === '='; | |
} | |
/** | |
* Replace escaped formula expression into valid string. | |
* | |
* @param {String} expression Expression to process. | |
* @returns {String} | |
*/ | |
function unescapeFormulaExpression(expression) { | |
return isFormulaExpressionEscaped(expression) ? expression.substr(1) : expression; | |
} | |
/** | |
* Upper case formula expression. | |
* | |
* @param {String} expression Formula expression. | |
* @returns {String} | |
*/ | |
function toUpperCaseFormula(expression) { | |
var PATTERN = /(\\"|"(?:\\"|[^"])*"|(\+))|(\\'|'(?:\\'|[^'])*'|(\+))/g; | |
var strings = expression.match(PATTERN) || []; | |
var index = -1; | |
return expression.toUpperCase().replace(PATTERN, function () { | |
index += 1; | |
return strings[index]; | |
}); | |
} | |
/** | |
* Cell coordinates function factory. | |
* | |
* @param {String} axis An axis name (`row` or `column`) which default index will be applied to. | |
* @param {Number} defaultIndex Default index. | |
* @returns {Function} | |
*/ | |
function cellCoordFactory(axis, defaultIndex) { | |
return function (cell) { | |
return { | |
row: axis === 'row' ? defaultIndex : cell.row, | |
column: axis === 'column' ? defaultIndex : cell.column | |
}; | |
}; | |
} | |
/***/ }), | |
/* 87 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(15); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(6)); | |
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(5)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _inherits2 = _interopRequireDefault(__webpack_require__(7)); | |
var _hotFormulaParser = __webpack_require__(122); | |
var _array = __webpack_require__(3); | |
var _base = _interopRequireDefault(__webpack_require__(404)); | |
var STATE_OUT_OFF_DATE = 1; | |
var STATE_COMPUTING = 2; | |
var STATE_UP_TO_DATE = 3; | |
var states = [STATE_OUT_OFF_DATE, STATE_COMPUTING, STATE_UP_TO_DATE]; | |
/** | |
* Class responsible for wrapping formula expression. It contains calculated value of | |
* the formula, an error if it has happened and cell references which indicates a relationship with regular | |
* cells. This object uses physical cell coordinates. | |
* | |
* @class CellValue | |
* @util | |
*/ | |
var CellValue = | |
/*#__PURE__*/ | |
function (_BaseCell) { | |
(0, _inherits2.default)(CellValue, _BaseCell); | |
(0, _createClass2.default)(CellValue, null, [{ | |
key: "STATE_OUT_OFF_DATE", | |
/** | |
* Out of date state indicates cells ready for recomputing. | |
* | |
* @returns {Number} | |
*/ | |
get: function get() { | |
return 1; // PhantomJS crashes when we want to use constant above | |
} | |
/** | |
* Computing state indicates cells under processing. | |
* | |
* @returns {Number} | |
*/ | |
}, { | |
key: "STATE_COMPUTING", | |
get: function get() { | |
return 2; // PhantomJS crashes when we want to use constant above | |
} | |
/** | |
* Up to date state indicates cells with fresh computed value. | |
* | |
* @returns {Number} | |
*/ | |
}, { | |
key: "STATE_UP_TO_DATE", | |
get: function get() { | |
return 3; // PhantomJS crashes when we want to use constant above | |
} | |
}]); | |
function CellValue(row, column) { | |
var _this; | |
(0, _classCallCheck2.default)(this, CellValue); | |
_this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(CellValue).call(this, row, column)); | |
/** | |
* List of precedents cells. | |
* | |
* @type {Array} | |
*/ | |
_this.precedents = []; | |
/** | |
* Computed value. | |
* | |
* @type {*} | |
*/ | |
_this.value = null; | |
/** | |
* Error name. | |
* | |
* @type {String|null} | |
*/ | |
_this.error = null; | |
/** | |
* Indicates cell state. | |
* | |
* @type {String} | |
*/ | |
_this.state = CellValue.STATE_UP_TO_DATE; | |
return _this; | |
} | |
/** | |
* Set computed value. | |
* | |
* @param {*} value | |
*/ | |
(0, _createClass2.default)(CellValue, [{ | |
key: "setValue", | |
value: function setValue(value) { | |
this.value = value; | |
} | |
/** | |
* Get computed value. | |
* | |
* @returns {*} | |
*/ | |
}, { | |
key: "getValue", | |
value: function getValue() { | |
return this.value; | |
} | |
/** | |
* Set error message for this cell. | |
* | |
* @param {String} error Error name. | |
*/ | |
}, { | |
key: "setError", | |
value: function setError(error) { | |
this.error = error; | |
} | |
/** | |
* Get error name for this cell. | |
* | |
* @returns {String|null} | |
*/ | |
}, { | |
key: "getError", | |
value: function getError() { | |
return this.error; | |
} | |
/** | |
* Check if cell value is marked as error. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "hasError", | |
value: function hasError() { | |
return this.error !== null; | |
} | |
/** | |
* Set cell state. | |
* | |
* @param {Number} state Cell state. | |
*/ | |
}, { | |
key: "setState", | |
value: function setState(state) { | |
if (states.indexOf(state) === -1) { | |
throw Error("Unrecognized state: ".concat(state)); | |
} | |
this.state = state; | |
} | |
/** | |
* Check cell state. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isState", | |
value: function isState(state) { | |
return this.state === state; | |
} | |
/** | |
* Add precedent cell to the collection. | |
* | |
* @param {CellReference} cellReference Cell reference object. | |
*/ | |
}, { | |
key: "addPrecedent", | |
value: function addPrecedent(cellReference) { | |
if (this.isEqual(cellReference)) { | |
throw Error(_hotFormulaParser.ERROR_REF); | |
} | |
if (!this.hasPrecedent(cellReference)) { | |
this.precedents.push(cellReference); | |
} | |
} | |
/** | |
* Remove precedent cell from the collection. | |
* | |
* @param {CellReference} cellReference Cell reference object. | |
*/ | |
}, { | |
key: "removePrecedent", | |
value: function removePrecedent(cellReference) { | |
if (this.isEqual(cellReference)) { | |
throw Error(_hotFormulaParser.ERROR_REF); | |
} | |
this.precedents = (0, _array.arrayFilter)(this.precedents, function (cell) { | |
return !cell.isEqual(cellReference); | |
}); | |
} | |
/** | |
* Clear all precedent cells. | |
*/ | |
}, { | |
key: "clearPrecedents", | |
value: function clearPrecedents() { | |
this.precedents.length = 0; | |
} | |
/** | |
* Get precedent cells. | |
* | |
* @returns {Array} | |
*/ | |
}, { | |
key: "getPrecedents", | |
value: function getPrecedents() { | |
return this.precedents; | |
} | |
/** | |
* Check if cell value has precedents cells. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "hasPrecedents", | |
value: function hasPrecedents() { | |
return this.precedents.length > 0; | |
} | |
/** | |
* Check if cell reference is precedents this cell. | |
* | |
* @param {CellReference} cellReference Cell reference object. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "hasPrecedent", | |
value: function hasPrecedent(cellReference) { | |
return (0, _array.arrayFilter)(this.precedents, function (cell) { | |
return cell.isEqual(cellReference); | |
}).length > 0; | |
} | |
}]); | |
return CellValue; | |
}(_base.default); | |
var _default = CellValue; | |
exports.default = _default; | |
/***/ }), | |
/* 88 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var NATIVE_WEAK_MAP = __webpack_require__(192); | |
var global = __webpack_require__(38); | |
var isObject = __webpack_require__(44); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var objectHas = __webpack_require__(55); | |
var sharedKey = __webpack_require__(126); | |
var hiddenKeys = __webpack_require__(100); | |
var WeakMap = global.WeakMap; | |
var set, get, has; | |
var enforce = function (it) { | |
return has(it) ? get(it) : set(it, {}); | |
}; | |
var getterFor = function (TYPE) { | |
return function (it) { | |
var state; | |
if (!isObject(it) || (state = get(it)).type !== TYPE) { | |
throw TypeError('Incompatible receiver, ' + TYPE + ' required'); | |
} return state; | |
}; | |
}; | |
if (NATIVE_WEAK_MAP) { | |
var store = new WeakMap(); | |
var wmget = store.get; | |
var wmhas = store.has; | |
var wmset = store.set; | |
set = function (it, metadata) { | |
wmset.call(store, it, metadata); | |
return metadata; | |
}; | |
get = function (it) { | |
return wmget.call(store, it) || {}; | |
}; | |
has = function (it) { | |
return wmhas.call(store, it); | |
}; | |
} else { | |
var STATE = sharedKey('state'); | |
hiddenKeys[STATE] = true; | |
set = function (it, metadata) { | |
createNonEnumerableProperty(it, STATE, metadata); | |
return metadata; | |
}; | |
get = function (it) { | |
return objectHas(it, STATE) ? it[STATE] : {}; | |
}; | |
has = function (it) { | |
return objectHas(it, STATE); | |
}; | |
} | |
module.exports = { | |
set: set, | |
get: get, | |
has: has, | |
enforce: enforce, | |
getterFor: getterFor | |
}; | |
/***/ }), | |
/* 89 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var bind = __webpack_require__(105); | |
var IndexedObject = __webpack_require__(124); | |
var toObject = __webpack_require__(62); | |
var toLength = __webpack_require__(52); | |
var arraySpeciesCreate = __webpack_require__(160); | |
var push = [].push; | |
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation | |
var createMethod = function (TYPE) { | |
var IS_MAP = TYPE == 1; | |
var IS_FILTER = TYPE == 2; | |
var IS_SOME = TYPE == 3; | |
var IS_EVERY = TYPE == 4; | |
var IS_FIND_INDEX = TYPE == 6; | |
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; | |
return function ($this, callbackfn, that, specificCreate) { | |
var O = toObject($this); | |
var self = IndexedObject(O); | |
var boundFunction = bind(callbackfn, that, 3); | |
var length = toLength(self.length); | |
var index = 0; | |
var create = specificCreate || arraySpeciesCreate; | |
var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; | |
var value, result; | |
for (;length > index; index++) if (NO_HOLES || index in self) { | |
value = self[index]; | |
result = boundFunction(value, index, O); | |
if (TYPE) { | |
if (IS_MAP) target[index] = result; // map | |
else if (result) switch (TYPE) { | |
case 3: return true; // some | |
case 5: return value; // find | |
case 6: return index; // findIndex | |
case 2: push.call(target, value); // filter | |
} else if (IS_EVERY) return false; // every | |
} | |
} | |
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; | |
}; | |
}; | |
module.exports = { | |
// `Array.prototype.forEach` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach | |
forEach: createMethod(0), | |
// `Array.prototype.map` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.map | |
map: createMethod(1), | |
// `Array.prototype.filter` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.filter | |
filter: createMethod(2), | |
// `Array.prototype.some` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.some | |
some: createMethod(3), | |
// `Array.prototype.every` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.every | |
every: createMethod(4), | |
// `Array.prototype.find` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.find | |
find: createMethod(5), | |
// `Array.prototype.findIndex` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex | |
findIndex: createMethod(6) | |
}; | |
/***/ }), | |
/* 90 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(15); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _element = __webpack_require__(8); | |
var _object = __webpack_require__(4); | |
var _array = __webpack_require__(3); | |
var _console = __webpack_require__(57); | |
var _eventManager = _interopRequireDefault(__webpack_require__(25)); | |
var _core = _interopRequireDefault(__webpack_require__(348)); | |
var registeredOverlays = {}; | |
/** | |
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable | |
* and (optionally) implements behavior needed for native horizontal and vertical scrolling. | |
* | |
* @class Overlay | |
*/ | |
var Overlay = | |
/*#__PURE__*/ | |
function () { | |
(0, _createClass2.default)(Overlay, null, [{ | |
key: "registerOverlay", | |
/** | |
* Register overlay class. | |
* | |
* @param {String} type Overlay type, one of the CLONE_TYPES value | |
* @param {Overlay} overlayClass Overlay class extended from base overlay class {@link Overlay} | |
*/ | |
value: function registerOverlay(type, overlayClass) { | |
if (Overlay.CLONE_TYPES.indexOf(type) === -1) { | |
throw new Error("Unsupported overlay (".concat(type, ").")); | |
} | |
registeredOverlays[type] = overlayClass; | |
} | |
/** | |
* Create new instance of overlay type. | |
* | |
* @param {String} type Overlay type, one of the CLONE_TYPES value | |
* @param {Walkontable} wot Walkontable instance | |
*/ | |
}, { | |
key: "createOverlay", | |
value: function createOverlay(type, wot) { | |
return new registeredOverlays[type](wot); | |
} | |
/** | |
* Check if specified overlay was registered. | |
* | |
* @param {String} type Overlay type, one of the CLONE_TYPES value | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "hasOverlay", | |
value: function hasOverlay(type) { | |
return registeredOverlays[type] !== void 0; | |
} | |
/** | |
* Checks if overlay object (`overlay`) is instance of overlay type (`type`). | |
* | |
* @param {Overlay} overlay Overlay object | |
* @param {String} type Overlay type, one of the CLONE_TYPES value | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isOverlayTypeOf", | |
value: function isOverlayTypeOf(overlay, type) { | |
if (!overlay || !registeredOverlays[type]) { | |
return false; | |
} | |
return overlay instanceof registeredOverlays[type]; | |
} | |
/** | |
* @param {Walkontable} wotInstance | |
*/ | |
}, { | |
key: "CLONE_TOP", | |
/** | |
* @type {String} | |
*/ | |
get: function get() { | |
return 'top'; | |
} | |
/** | |
* @type {String} | |
*/ | |
}, { | |
key: "CLONE_BOTTOM", | |
get: function get() { | |
return 'bottom'; | |
} | |
/** | |
* @type {String} | |
*/ | |
}, { | |
key: "CLONE_LEFT", | |
get: function get() { | |
return 'left'; | |
} | |
/** | |
* @type {String} | |
*/ | |
}, { | |
key: "CLONE_TOP_LEFT_CORNER", | |
get: function get() { | |
return 'top_left_corner'; | |
} | |
/** | |
* @type {String} | |
*/ | |
}, { | |
key: "CLONE_BOTTOM_LEFT_CORNER", | |
get: function get() { | |
return 'bottom_left_corner'; | |
} | |
/** | |
* @type {String} | |
*/ | |
}, { | |
key: "CLONE_DEBUG", | |
get: function get() { | |
return 'debug'; | |
} | |
/** | |
* List of all availables clone types | |
* | |
* @type {Array} | |
*/ | |
}, { | |
key: "CLONE_TYPES", | |
get: function get() { | |
return [Overlay.CLONE_TOP, Overlay.CLONE_BOTTOM, Overlay.CLONE_LEFT, Overlay.CLONE_TOP_LEFT_CORNER, Overlay.CLONE_BOTTOM_LEFT_CORNER, Overlay.CLONE_DEBUG]; | |
} | |
}]); | |
function Overlay(wotInstance) { | |
(0, _classCallCheck2.default)(this, Overlay); | |
(0, _object.defineGetter)(this, 'wot', wotInstance, { | |
writable: false | |
}); | |
var _this$wot$wtTable = this.wot.wtTable, | |
TABLE = _this$wot$wtTable.TABLE, | |
hider = _this$wot$wtTable.hider, | |
spreader = _this$wot$wtTable.spreader, | |
holder = _this$wot$wtTable.holder, | |
wtRootElement = _this$wot$wtTable.wtRootElement; // legacy support, deprecated in the future | |
this.instance = this.wot; | |
this.type = ''; | |
this.mainTableScrollableElement = null; | |
this.TABLE = TABLE; | |
this.hider = hider; | |
this.spreader = spreader; | |
this.holder = holder; | |
this.wtRootElement = wtRootElement; | |
this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode); | |
this.areElementSizesAdjusted = false; | |
this.updateStateOfRendering(); | |
} | |
/** | |
* Update internal state of object with an information about the need of full rendering of the overlay. | |
* | |
* @returns {Boolean} Returns `true` if the state has changed since the last check. | |
*/ | |
(0, _createClass2.default)(Overlay, [{ | |
key: "updateStateOfRendering", | |
value: function updateStateOfRendering() { | |
var previousState = this.needFullRender; | |
this.needFullRender = this.shouldBeRendered(); | |
var changed = previousState !== this.needFullRender; | |
if (changed && !this.needFullRender) { | |
this.reset(); | |
} | |
return changed; | |
} | |
/** | |
* Checks if overlay should be fully rendered | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "shouldBeRendered", | |
value: function shouldBeRendered() { | |
return true; | |
} | |
/** | |
* Update the trimming container. | |
*/ | |
}, { | |
key: "updateTrimmingContainer", | |
value: function updateTrimmingContainer() { | |
this.trimmingContainer = (0, _element.getTrimmingContainer)(this.hider.parentNode.parentNode); | |
} | |
/** | |
* Update the main scrollable element. | |
*/ | |
}, { | |
key: "updateMainScrollableElement", | |
value: function updateMainScrollableElement() { | |
var _this$wot = this.wot, | |
wtTable = _this$wot.wtTable, | |
rootWindow = _this$wot.rootWindow; | |
if (rootWindow.getComputedStyle(wtTable.wtRootElement.parentNode).getPropertyValue('overflow') === 'hidden') { | |
this.mainTableScrollableElement = this.wot.wtTable.holder; | |
} else { | |
this.mainTableScrollableElement = (0, _element.getScrollableElement)(wtTable.TABLE); | |
} | |
} | |
/** | |
* Calculates coordinates of the provided element, relative to the root Handsontable element. | |
* NOTE: The element needs to be a child of the overlay in order for the method to work correctly. | |
* | |
* @param {HTMLElement} element The cell element to calculate the position for. | |
* @param {Number} rowIndex Visual row index. | |
* @param {Number} columnIndex Visual column index. | |
* @returns {{top: Number, left: Number}|undefined} | |
*/ | |
}, { | |
key: "getRelativeCellPosition", | |
value: function getRelativeCellPosition(element, rowIndex, columnIndex) { | |
if (this.clone.wtTable.holder.contains(element) === false) { | |
(0, _console.warn)("The provided element is not a child of the ".concat(this.type, " overlay")); | |
return; | |
} | |
var windowScroll = this.mainTableScrollableElement === this.wot.rootWindow; | |
var fixedColumn = columnIndex < this.wot.getSetting('fixedColumnsLeft'); | |
var fixedRowTop = rowIndex < this.wot.getSetting('fixedRowsTop'); | |
var fixedRowBottom = rowIndex >= this.wot.getSetting('totalRows') - this.wot.getSetting('fixedRowsBottom'); | |
var spreaderOffset = { | |
left: this.clone.wtTable.spreader.offsetLeft, | |
top: this.clone.wtTable.spreader.offsetTop | |
}; | |
var elementOffset = { | |
left: element.offsetLeft, | |
top: element.offsetTop | |
}; | |
var offsetObject = null; | |
if (windowScroll) { | |
offsetObject = this.getRelativeCellPositionWithinWindow(fixedRowTop, fixedColumn, elementOffset, spreaderOffset); | |
} else { | |
offsetObject = this.getRelativeCellPositionWithinHolder(fixedRowTop, fixedRowBottom, fixedColumn, elementOffset, spreaderOffset); | |
} | |
return offsetObject; | |
} | |
/** | |
* Calculates coordinates of the provided element, relative to the root Handsontable element within a table with window | |
* as a scrollable element. | |
* | |
* @private | |
* @param {Boolean} onFixedRowTop `true` if the coordinates point to a place within the top fixed rows. | |
* @param {Boolean} onFixedColumn `true` if the coordinates point to a place within the fixed columns. | |
* @param {Number} elementOffset Offset position of the cell element. | |
* @param {Number} spreaderOffset Offset position of the spreader element. | |
* @returns {{top: Number, left: Number}} | |
*/ | |
}, { | |
key: "getRelativeCellPositionWithinWindow", | |
value: function getRelativeCellPositionWithinWindow(onFixedRowTop, onFixedColumn, elementOffset, spreaderOffset) { | |
var absoluteRootElementPosition = this.wot.wtTable.wtRootElement.getBoundingClientRect(); | |
var horizontalOffset = 0; | |
var verticalOffset = 0; | |
if (!onFixedColumn) { | |
horizontalOffset = spreaderOffset.left; | |
} else { | |
horizontalOffset = absoluteRootElementPosition.left <= 0 ? -1 * absoluteRootElementPosition.left : 0; | |
} | |
if (onFixedRowTop) { | |
var absoluteOverlayPosition = this.clone.wtTable.TABLE.getBoundingClientRect(); | |
verticalOffset = absoluteOverlayPosition.top - absoluteRootElementPosition.top; | |
} else { | |
verticalOffset = spreaderOffset.top; | |
} | |
return { | |
left: elementOffset.left + horizontalOffset, | |
top: elementOffset.top + verticalOffset | |
}; | |
} | |
/** | |
* Calculates coordinates of the provided element, relative to the root Handsontable element within a table with window | |
* as a scrollable element. | |
* | |
* @private | |
* @param {Boolean} onFixedRowTop `true` if the coordinates point to a place within the top fixed rows. | |
* @param {Boolean} onFixedRowBottom `true` if the coordinates point to a place within the bottom fixed rows. | |
* @param {Boolean} onFixedColumn `true` if the coordinates point to a place within the fixed columns. | |
* @param {Number} elementOffset Offset position of the cell element. | |
* @param {Number} spreaderOffset Offset position of the spreader element. | |
* @returns {{top: Number, left: Number}} | |
*/ | |
}, { | |
key: "getRelativeCellPositionWithinHolder", | |
value: function getRelativeCellPositionWithinHolder(onFixedRowTop, onFixedRowBottom, onFixedColumn, elementOffset, spreaderOffset) { | |
var tableScrollPosition = { | |
horizontal: this.clone.cloneSource.wtOverlays.leftOverlay.getScrollPosition(), | |
vertical: this.clone.cloneSource.wtOverlays.topOverlay.getScrollPosition() | |
}; | |
var horizontalOffset = 0; | |
var verticalOffset = 0; | |
if (!onFixedColumn) { | |
horizontalOffset = tableScrollPosition.horizontal - spreaderOffset.left; | |
} | |
if (onFixedRowBottom) { | |
var absoluteRootElementPosition = this.wot.wtTable.wtRootElement.getBoundingClientRect(); | |
var absoluteOverlayPosition = this.clone.wtTable.TABLE.getBoundingClientRect(); | |
verticalOffset = absoluteOverlayPosition.top * -1 + absoluteRootElementPosition.top; | |
} else if (!onFixedRowTop) { | |
verticalOffset = tableScrollPosition.vertical - spreaderOffset.top; | |
} | |
return { | |
left: elementOffset.left - horizontalOffset, | |
top: elementOffset.top - verticalOffset | |
}; | |
} | |
/** | |
* Make a clone of table for overlay | |
* | |
* @param {String} direction Can be `Overlay.CLONE_TOP`, `Overlay.CLONE_LEFT`, | |
* `Overlay.CLONE_TOP_LEFT_CORNER`, `Overlay.CLONE_DEBUG` | |
* @returns {Walkontable} | |
*/ | |
}, { | |
key: "makeClone", | |
value: function makeClone(direction) { | |
if (Overlay.CLONE_TYPES.indexOf(direction) === -1) { | |
throw new Error("Clone type \"".concat(direction, "\" is not supported.")); | |
} | |
var _this$wot2 = this.wot, | |
wtTable = _this$wot2.wtTable, | |
rootDocument = _this$wot2.rootDocument, | |
rootWindow = _this$wot2.rootWindow; | |
var clone = rootDocument.createElement('DIV'); | |
var clonedTable = rootDocument.createElement('TABLE'); | |
clone.className = "ht_clone_".concat(direction, " handsontable"); | |
clone.style.position = 'absolute'; | |
clone.style.top = 0; | |
clone.style.left = 0; | |
clone.style.overflow = 'visible'; | |
clonedTable.className = wtTable.TABLE.className; | |
clone.appendChild(clonedTable); | |
this.type = direction; | |
wtTable.wtRootElement.parentNode.appendChild(clone); | |
var preventOverflow = this.wot.getSetting('preventOverflow'); | |
if (preventOverflow === true || preventOverflow === 'horizontal' && this.type === Overlay.CLONE_TOP || preventOverflow === 'vertical' && this.type === Overlay.CLONE_LEFT) { | |
this.mainTableScrollableElement = rootWindow; | |
} else if (rootWindow.getComputedStyle(wtTable.wtRootElement.parentNode).getPropertyValue('overflow') === 'hidden') { | |
this.mainTableScrollableElement = wtTable.holder; | |
} else { | |
this.mainTableScrollableElement = (0, _element.getScrollableElement)(wtTable.TABLE); | |
} | |
return new _core.default({ | |
cloneSource: this.wot, | |
cloneOverlay: this, | |
table: clonedTable | |
}); | |
} | |
/** | |
* Refresh/Redraw overlay | |
* | |
* @param {Boolean} [fastDraw=false] | |
*/ | |
}, { | |
key: "refresh", | |
value: function refresh() { | |
var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; | |
// When hot settings are changed we allow to refresh overlay once before blocking | |
var nextCycleRenderFlag = this.shouldBeRendered(); | |
if (this.clone && (this.needFullRender || nextCycleRenderFlag)) { | |
this.clone.draw(fastDraw); | |
} | |
this.needFullRender = nextCycleRenderFlag; | |
} | |
/** | |
* Reset overlay styles to initial values. | |
*/ | |
}, { | |
key: "reset", | |
value: function reset() { | |
if (!this.clone) { | |
return; | |
} | |
var holder = this.clone.wtTable.holder; | |
var hider = this.clone.wtTable.hider; | |
var holderStyle = holder.style; | |
var hidderStyle = hider.style; | |
var rootStyle = holder.parentNode.style; | |
(0, _array.arrayEach)([holderStyle, hidderStyle, rootStyle], function (style) { | |
style.width = ''; | |
style.height = ''; | |
}); | |
} | |
/** | |
* Destroy overlay instance | |
*/ | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
new _eventManager.default(this.clone).destroy(); | |
} | |
}]); | |
return Overlay; | |
}(); | |
var _default = Overlay; | |
exports.default = _default; | |
/***/ }), | |
/* 91 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(71); | |
exports.__esModule = true; | |
var _registry = __webpack_require__(388); | |
exports.registerRootComparator = _registry.registerRootComparator; | |
exports.getRootComparator = _registry.getRootComparator; | |
exports.getCompareFunctionFactory = _registry.getCompareFunctionFactory; | |
var _engine = __webpack_require__(534); | |
exports.FIRST_AFTER_SECOND = _engine.FIRST_AFTER_SECOND; | |
exports.FIRST_BEFORE_SECOND = _engine.FIRST_BEFORE_SECOND; | |
exports.DO_NOT_SWAP = _engine.DO_NOT_SWAP; | |
exports.sort = _engine.sort; | |
/***/ }), | |
/* 92 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var DESCRIPTORS = __webpack_require__(51); | |
var propertyIsEnumerableModule = __webpack_require__(146); | |
var createPropertyDescriptor = __webpack_require__(97); | |
var toIndexedObject = __webpack_require__(67); | |
var toPrimitive = __webpack_require__(98); | |
var has = __webpack_require__(55); | |
var IE8_DOM_DEFINE = __webpack_require__(190); | |
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; | |
// `Object.getOwnPropertyDescriptor` method | |
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor | |
exports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { | |
O = toIndexedObject(O); | |
P = toPrimitive(P, true); | |
if (IE8_DOM_DEFINE) try { | |
return nativeGetOwnPropertyDescriptor(O, P); | |
} catch (error) { /* empty */ } | |
if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]); | |
}; | |
/***/ }), | |
/* 93 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var fixRegExpWellKnownSymbolLogic = __webpack_require__(135); | |
var anObject = __webpack_require__(47); | |
var toLength = __webpack_require__(52); | |
var requireObjectCoercible = __webpack_require__(54); | |
var advanceStringIndex = __webpack_require__(164); | |
var regExpExec = __webpack_require__(136); | |
// @@match logic | |
fixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { | |
return [ | |
// `String.prototype.match` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype.match | |
function match(regexp) { | |
var O = requireObjectCoercible(this); | |
var matcher = regexp == undefined ? undefined : regexp[MATCH]; | |
return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); | |
}, | |
// `RegExp.prototype[@@match]` method | |
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match | |
function (regexp) { | |
var res = maybeCallNative(nativeMatch, regexp, this); | |
if (res.done) return res.value; | |
var rx = anObject(regexp); | |
var S = String(this); | |
if (!rx.global) return regExpExec(rx, S); | |
var fullUnicode = rx.unicode; | |
rx.lastIndex = 0; | |
var A = []; | |
var n = 0; | |
var result; | |
while ((result = regExpExec(rx, S)) !== null) { | |
var matchStr = String(result[0]); | |
A[n] = matchStr; | |
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); | |
n++; | |
} | |
return n === 0 ? null : A; | |
} | |
]; | |
}); | |
/***/ }), | |
/* 94 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(48); | |
__webpack_require__(27); | |
__webpack_require__(11); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _toConsumableArray2 = _interopRequireDefault(__webpack_require__(33)); | |
var _slicedToArray2 = _interopRequireDefault(__webpack_require__(18)); | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _element = __webpack_require__(8); | |
var _function = __webpack_require__(63); | |
var _coords = _interopRequireDefault(__webpack_require__(111)); | |
var _column = _interopRequireDefault(__webpack_require__(219)); | |
var _row = _interopRequireDefault(__webpack_require__(220)); | |
var _renderer = __webpack_require__(224); | |
var _base = _interopRequireDefault(__webpack_require__(90)); | |
var _column2 = _interopRequireDefault(__webpack_require__(441)); | |
var _row2 = _interopRequireDefault(__webpack_require__(442)); | |
var _borderRenderer = __webpack_require__(443); | |
/** | |
* | |
*/ | |
var Table = | |
/*#__PURE__*/ | |
function () { | |
/** | |
* @param {Walkontable} wotInstance | |
* @param {HTMLTableElement} table | |
*/ | |
function Table(wotInstance, table) { | |
var _this = this; | |
(0, _classCallCheck2.default)(this, Table); | |
/** | |
* Indicates if this instance is of type `MasterTable` (i.e. it is NOT an overlay) | |
* | |
* @type {Boolean} | |
*/ | |
this.isMaster = !wotInstance.cloneOverlay; // "instanceof" operator isn't used, because it caused a circular reference in Webpack | |
this.wot = wotInstance; // legacy support | |
this.instance = this.wot; | |
this.TABLE = table; | |
this.TBODY = null; | |
this.THEAD = null; | |
this.COLGROUP = null; | |
this.tableOffset = 0; | |
this.holderOffset = 0; | |
/** | |
* Indicates if the table has height bigger than 0px. | |
* | |
* @type {Boolean} | |
*/ | |
this.hasTableHeight = true; | |
/** | |
* Indicates if the table has width bigger than 0px. | |
* | |
* @type {Boolean} | |
*/ | |
this.hasTableWidth = true; | |
/** | |
* Indicates if the table is visible. By visible, it means that the holder | |
* element has CSS 'display' property different than 'none'. | |
* | |
* @type {Boolean} | |
*/ | |
this.isTableVisible = false; | |
(0, _element.removeTextNodes)(this.TABLE); | |
this.spreader = this.createSpreader(this.TABLE); | |
this.hider = this.createHider(this.spreader); | |
this.holder = this.createHolder(this.hider); | |
this.wtRootElement = this.holder.parentNode; | |
if (this.isMaster) { | |
this.alignOverlaysWithTrimmingContainer(); | |
} | |
this.fixTableDomTree(); | |
this.rowFilter = null; | |
this.columnFilter = null; | |
this.correctHeaderWidth = false; | |
var origRowHeaderWidth = this.wot.wtSettings.settings.rowHeaderWidth; // Fix for jumping row headers (https://github.com/handsontable/handsontable/issues/3850) | |
this.wot.wtSettings.settings.rowHeaderWidth = function () { | |
return _this._modifyRowHeaderWidth(origRowHeaderWidth); | |
}; | |
this.rowUtils = new _row2.default(this.wot); | |
this.columnUtils = new _column2.default(this.wot); | |
this.tableRenderer = new _renderer.Renderer({ | |
TABLE: this.TABLE, | |
THEAD: this.THEAD, | |
COLGROUP: this.COLGROUP, | |
TBODY: this.TBODY, | |
rowUtils: this.rowUtils, | |
columnUtils: this.columnUtils, | |
cellRenderer: this.wot.wtSettings.settings.cellRenderer | |
}); | |
this.borderRenderer = new _borderRenderer.BorderRenderer(this.spreader); | |
} | |
/** | |
* Returns a boolean that is true if this intance of Table represents a specific overlay, identified by the overlay name. | |
* For MasterTable, it returns false. | |
* | |
* @param {String} overlayTypeName | |
* @returns {Boolean} | |
*/ | |
(0, _createClass2.default)(Table, [{ | |
key: "is", | |
value: function is(overlayTypeName) { | |
return _base.default.isOverlayTypeOf(this.wot.cloneOverlay, overlayTypeName); | |
} | |
/** | |
* | |
*/ | |
}, { | |
key: "fixTableDomTree", | |
value: function fixTableDomTree() { | |
var rootDocument = this.wot.rootDocument; | |
this.TBODY = this.TABLE.querySelector('tbody'); | |
if (!this.TBODY) { | |
this.TBODY = rootDocument.createElement('tbody'); | |
this.TABLE.appendChild(this.TBODY); | |
} | |
this.THEAD = this.TABLE.querySelector('thead'); | |
if (!this.THEAD) { | |
this.THEAD = rootDocument.createElement('thead'); | |
this.TABLE.insertBefore(this.THEAD, this.TBODY); | |
} | |
this.COLGROUP = this.TABLE.querySelector('colgroup'); | |
if (!this.COLGROUP) { | |
this.COLGROUP = rootDocument.createElement('colgroup'); | |
this.TABLE.insertBefore(this.COLGROUP, this.THEAD); | |
} | |
if (this.wot.getSetting('columnHeaders').length && !this.THEAD.childNodes.length) { | |
this.THEAD.appendChild(rootDocument.createElement('TR')); | |
} | |
} | |
/** | |
* @param table | |
* @returns {HTMLElement} | |
*/ | |
}, { | |
key: "createSpreader", | |
value: function createSpreader(table) { | |
var parent = table.parentNode; | |
var spreader; | |
if (!parent || parent.nodeType !== Node.ELEMENT_NODE || !(0, _element.hasClass)(parent, 'wtHolder')) { | |
spreader = this.wot.rootDocument.createElement('div'); | |
spreader.className = 'wtSpreader'; | |
if (parent) { | |
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it | |
parent.insertBefore(spreader, table); | |
} | |
spreader.appendChild(table); | |
} | |
spreader.style.position = 'relative'; | |
return spreader; | |
} | |
/** | |
* @param spreader | |
* @returns {HTMLElement} | |
*/ | |
}, { | |
key: "createHider", | |
value: function createHider(spreader) { | |
var parent = spreader.parentNode; | |
var hider; | |
if (!parent || parent.nodeType !== Node.ELEMENT_NODE || !(0, _element.hasClass)(parent, 'wtHolder')) { | |
hider = this.wot.rootDocument.createElement('div'); | |
hider.className = 'wtHider'; | |
if (parent) { | |
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it | |
parent.insertBefore(hider, spreader); | |
} | |
hider.appendChild(spreader); | |
} | |
return hider; | |
} | |
/** | |
* | |
* @param hider | |
* @returns {HTMLElement} | |
*/ | |
}, { | |
key: "createHolder", | |
value: function createHolder(hider) { | |
var parent = hider.parentNode; | |
var holder; | |
if (!parent || parent.nodeType !== Node.ELEMENT_NODE || !(0, _element.hasClass)(parent, 'wtHolder')) { | |
holder = this.wot.rootDocument.createElement('div'); | |
holder.style.position = 'relative'; | |
holder.className = 'wtHolder'; | |
if (parent) { | |
// if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it | |
parent.insertBefore(holder, hider); | |
} | |
if (this.isMaster) { | |
holder.parentNode.className += 'ht_master handsontable'; | |
} | |
holder.appendChild(hider); | |
} | |
return holder; | |
} | |
/** | |
* Redraws the table | |
* | |
* @param {Boolean} [fastDraw=false] If TRUE, will try to avoid full redraw and only update the border positions. | |
* If FALSE or UNDEFINED, will perform a full redraw. | |
* @returns {Table} | |
*/ | |
}, { | |
key: "draw", | |
value: function draw() { | |
var fastDraw = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; | |
var wot = this.wot; | |
var wtOverlays = wot.wtOverlays, | |
wtViewport = wot.wtViewport; | |
var totalRows = wot.getSetting('totalRows'); | |
var totalColumns = wot.getSetting('totalColumns'); | |
var rowHeaders = wot.getSetting('rowHeaders'); | |
var rowHeadersCount = rowHeaders.length; | |
var columnHeaders = wot.getSetting('columnHeaders'); | |
var columnHeadersCount = columnHeaders.length; | |
var syncScroll = false; | |
var runFastDraw = fastDraw; | |
if (this.isMaster) { | |
this.holderOffset = (0, _element.offset)(this.holder); | |
runFastDraw = wtViewport.createRenderCalculators(runFastDraw); | |
if (rowHeadersCount && !wot.getSetting('fixedColumnsLeft')) { | |
var leftScrollPos = wtOverlays.leftOverlay.getScrollPosition(); | |
var previousState = this.correctHeaderWidth; | |
this.correctHeaderWidth = leftScrollPos > 0; | |
if (previousState !== this.correctHeaderWidth) { | |
runFastDraw = false; | |
} | |
} | |
} | |
if (this.isMaster) { | |
syncScroll = wtOverlays.prepareOverlays(); | |
} | |
if (runFastDraw) { | |
if (this.isMaster) { | |
// in case we only scrolled without redraw, update visible rows information in oldRowsCalculator | |
wtViewport.createVisibleCalculators(); | |
} | |
if (wtOverlays) { | |
wtOverlays.refresh(true); | |
} | |
} else { | |
if (this.isMaster) { | |
this.tableOffset = (0, _element.offset)(this.TABLE); | |
} else { | |
this.tableOffset = this.wot.cloneSource.wtTable.tableOffset; | |
} | |
var startRow = totalRows > 0 ? this.getFirstRenderedRow() : 0; | |
var startColumn = totalColumns > 0 ? this.getFirstRenderedColumn() : 0; | |
this.rowFilter = new _row.default(startRow, totalRows, columnHeadersCount); | |
this.columnFilter = new _column.default(startColumn, totalColumns, rowHeadersCount); | |
var performRedraw = true; // Only master table rendering can be skipped | |
if (this.isMaster) { | |
this.alignOverlaysWithTrimmingContainer(); | |
var skipRender = {}; | |
this.wot.getSetting('beforeDraw', true, skipRender); | |
performRedraw = skipRender.skipRender !== true; | |
} | |
if (performRedraw) { | |
this.tableRenderer.setHeaderContentRenderers(rowHeaders, columnHeaders); | |
if (this.is(_base.default.CLONE_BOTTOM) || this.is(_base.default.CLONE_BOTTOM_LEFT_CORNER)) { | |
// do NOT render headers on the bottom or bottom-left corner overlay | |
this.tableRenderer.setHeaderContentRenderers(rowHeaders, []); | |
} | |
this.resetOversizedRows(); | |
this.tableRenderer.setViewportSize(this.getRenderedRowsCount(), this.getRenderedColumnsCount()).setFilters(this.rowFilter, this.columnFilter).render(); | |
var workspaceWidth; | |
if (this.isMaster) { | |
workspaceWidth = this.wot.wtViewport.getWorkspaceWidth(); | |
this.wot.wtViewport.containerWidth = null; | |
this.markOversizedColumnHeaders(); | |
} | |
this.adjustColumnHeaderHeights(); | |
if (this.isMaster || this.is(_base.default.CLONE_BOTTOM)) { | |
this.markOversizedRows(); | |
} | |
if (this.isMaster) { | |
this.wot.wtViewport.createVisibleCalculators(); | |
this.wot.wtOverlays.refresh(false); | |
this.wot.wtOverlays.applyToDOM(); | |
var hiderWidth = (0, _element.outerWidth)(this.hider); | |
var tableWidth = (0, _element.outerWidth)(this.TABLE); | |
if (hiderWidth !== 0 && tableWidth !== hiderWidth) { | |
// Recalculate the column widths, if width changes made in the overlays removed the scrollbar, thus changing the viewport width. | |
this.columnUtils.calculateWidths(); | |
this.tableRenderer.renderer.colGroup.render(); | |
} | |
if (workspaceWidth !== this.wot.wtViewport.getWorkspaceWidth()) { | |
// workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching | |
this.wot.wtViewport.containerWidth = null; | |
this.columnUtils.calculateWidths(); | |
this.tableRenderer.renderer.colGroup.render(); | |
} | |
this.wot.getSetting('onDraw', true); | |
} else if (this.is(_base.default.CLONE_BOTTOM)) { | |
this.wot.cloneSource.wtOverlays.adjustElementsSize(); | |
} | |
} | |
} | |
if (this.isMaster) { | |
wtOverlays.topOverlay.resetFixedPosition(); | |
if (wtOverlays.bottomOverlay.clone) { | |
wtOverlays.bottomOverlay.resetFixedPosition(); | |
} | |
wtOverlays.leftOverlay.resetFixedPosition(); | |
if (wtOverlays.topLeftCornerOverlay) { | |
wtOverlays.topLeftCornerOverlay.resetFixedPosition(); | |
} | |
if (wtOverlays.bottomLeftCornerOverlay && wtOverlays.bottomLeftCornerOverlay.clone) { | |
wtOverlays.bottomLeftCornerOverlay.resetFixedPosition(); | |
} | |
} | |
this.refreshSelections(runFastDraw); | |
if (syncScroll) { | |
wtOverlays.syncScrollWithMaster(); | |
} | |
wot.drawn = true; | |
return this; | |
} | |
}, { | |
key: "markIfOversizedColumnHeader", | |
value: function markIfOversizedColumnHeader(col) { | |
var sourceColIndex = this.wot.wtTable.columnFilter.renderedToSource(col); | |
var level = this.wot.getSetting('columnHeaders').length; | |
var defaultRowHeight = this.wot.wtSettings.settings.defaultRowHeight; | |
var previousColHeaderHeight; | |
var currentHeader; | |
var currentHeaderHeight; | |
var columnHeaderHeightSetting = this.wot.getSetting('columnHeaderHeight') || []; | |
while (level) { | |
level -= 1; | |
previousColHeaderHeight = this.wot.wtTable.getColumnHeaderHeight(level); | |
currentHeader = this.wot.wtTable.getColumnHeader(sourceColIndex, level); | |
if (!currentHeader) { | |
/* eslint-disable no-continue */ | |
continue; | |
} | |
currentHeaderHeight = (0, _element.innerHeight)(currentHeader); | |
if (!previousColHeaderHeight && defaultRowHeight < currentHeaderHeight || previousColHeaderHeight < currentHeaderHeight) { | |
this.wot.wtViewport.oversizedColumnHeaders[level] = currentHeaderHeight; | |
} | |
if (Array.isArray(columnHeaderHeightSetting)) { | |
if (columnHeaderHeightSetting[level] !== null && columnHeaderHeightSetting[level] !== void 0) { | |
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level]; | |
} | |
} else if (!isNaN(columnHeaderHeightSetting)) { | |
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting; | |
} | |
if (this.wot.wtViewport.oversizedColumnHeaders[level] < (columnHeaderHeightSetting[level] || columnHeaderHeightSetting)) { | |
this.wot.wtViewport.oversizedColumnHeaders[level] = columnHeaderHeightSetting[level] || columnHeaderHeightSetting; | |
} | |
} | |
} | |
}, { | |
key: "adjustColumnHeaderHeights", | |
value: function adjustColumnHeaderHeights() { | |
var wot = this.wot; | |
var children = wot.wtTable.THEAD.childNodes; | |
var oversizedColumnHeaders = wot.wtViewport.oversizedColumnHeaders; | |
var columnHeaders = wot.getSetting('columnHeaders'); | |
for (var i = 0, len = columnHeaders.length; i < len; i++) { | |
if (oversizedColumnHeaders[i]) { | |
if (!children[i] || children[i].childNodes.length === 0) { | |
return; | |
} | |
children[i].childNodes[0].style.height = "".concat(oversizedColumnHeaders[i], "px"); | |
} | |
} | |
} | |
/** | |
* Resets cache of row heights. The cache should be cached for each render cycle in a case | |
* when new cell values have content which increases/decreases cell height. | |
*/ | |
}, { | |
key: "resetOversizedRows", | |
value: function resetOversizedRows() { | |
var wot = this.wot; | |
if (!this.isMaster && !this.is(_base.default.CLONE_BOTTOM)) { | |
return; | |
} | |
if (!wot.getSetting('externalRowCalculator')) { | |
var rowsToRender = this.getRenderedRowsCount(); // Reset the oversized row cache for rendered rows | |
for (var visibleRowIndex = 0; visibleRowIndex < rowsToRender; visibleRowIndex++) { | |
var sourceRow = this.rowFilter.renderedToSource(visibleRowIndex); | |
if (wot.wtViewport.oversizedRows && wot.wtViewport.oversizedRows[sourceRow]) { | |
wot.wtViewport.oversizedRows[sourceRow] = void 0; | |
} | |
} | |
} | |
} | |
}, { | |
key: "removeClassFromCells", | |
value: function removeClassFromCells(className) { | |
var nodes = this.TABLE.querySelectorAll(".".concat(className)); | |
for (var i = 0, len = nodes.length; i < len; i++) { | |
(0, _element.removeClass)(nodes[i], className); | |
} | |
} | |
/** | |
* Refresh the table selection by re-rendering Selection instances connected with that instance. | |
* | |
* @param {Boolean} fastDraw If fast drawing is enabled than additionally className clearing is applied. | |
*/ | |
}, { | |
key: "refreshSelections", | |
value: function refreshSelections(fastDraw) { | |
var wot = this.wot; | |
if (!wot.selections) { | |
return; | |
} | |
var highlights = Array.from(wot.selections); | |
var len = highlights.length; | |
if (fastDraw) { | |
var classesToRemove = []; | |
for (var i = 0; i < len; i++) { | |
var _highlights$i$setting = highlights[i].settings, | |
highlightHeaderClassName = _highlights$i$setting.highlightHeaderClassName, | |
highlightRowClassName = _highlights$i$setting.highlightRowClassName, | |
highlightColumnClassName = _highlights$i$setting.highlightColumnClassName; | |
var classNames = highlights[i].classNames; | |
var classNamesLength = classNames.length; | |
for (var j = 0; j < classNamesLength; j++) { | |
if (!classesToRemove.includes(classNames[j])) { | |
classesToRemove.push(classNames[j]); | |
} | |
} | |
if (highlightHeaderClassName && !classesToRemove.includes(highlightHeaderClassName)) { | |
classesToRemove.push(highlightHeaderClassName); | |
} | |
if (highlightRowClassName && !classesToRemove.includes(highlightRowClassName)) { | |
classesToRemove.push(highlightRowClassName); | |
} | |
if (highlightColumnClassName && !classesToRemove.includes(highlightColumnClassName)) { | |
classesToRemove.push(highlightColumnClassName); | |
} | |
} | |
var additionalClassesToRemove = wot.getSetting('onBeforeRemoveCellClassNames'); | |
if (Array.isArray(additionalClassesToRemove)) { | |
for (var _i = 0; _i < additionalClassesToRemove.length; _i++) { | |
classesToRemove.push(additionalClassesToRemove[_i]); | |
} | |
} | |
var classesToRemoveLength = classesToRemove.length; | |
for (var _i2 = 0; _i2 < classesToRemoveLength; _i2++) { | |
// there was no rerender, so we need to remove classNames by ourselves | |
this.removeClassFromCells(classesToRemove[_i2]); | |
} | |
} | |
var borderEdgesDescriptors = []; | |
for (var _i3 = 0; _i3 < len; _i3++) { | |
var selection = highlights[_i3]; | |
selection.draw(wot); | |
var borderEdgesDescriptor = selection.getBorderEdgesDescriptor(); | |
if (borderEdgesDescriptor.length > 0) { | |
borderEdgesDescriptors.push(selection.getBorderEdgesDescriptor()); | |
} | |
} | |
this.borderRenderer.skipFirstRowTopEdge = !!this.wot.getSetting('columnHeaders').length; | |
this.borderRenderer.skipFirstColumnLeftEdge = !!this.wot.getSetting('rowHeaders').length; | |
this.borderRenderer.render(this.TABLE, borderEdgesDescriptors); | |
} | |
/** | |
* Get cell element at coords. | |
* Negative coords.row or coords.col are used to retrieve header cells. If there are multiple header levels, the | |
* negative value corresponds to the distance from the working area. For example, when there are 3 levels of column | |
* headers, coords.col=-1 corresponds to the most inner header element, while coords.col=-3 corresponds to the | |
* outmost header element. | |
* | |
* In case an element for the coords is not rendered, the method returns an error code. | |
* To produce the error code, the input parameters are validated in the order in which they | |
* are given. Thus, if both the row and the column coords are out of the rendered bounds, | |
* the method returns the error code for the row. | |
* | |
* @param {CellCoords} coords | |
* @returns {HTMLElement|Number} HTMLElement on success or Number one of the exit codes on error: | |
* -1 row before viewport | |
* -2 row after viewport | |
* -3 column before viewport | |
* -4 column after viewport | |
*/ | |
}, { | |
key: "getCell", | |
value: function getCell(coords) { | |
var row = coords.row; | |
var column = coords.col; | |
var hookResult = this.wot.getSetting('onModifyGetCellCoords', row, column); | |
if (hookResult && Array.isArray(hookResult)) { | |
var _hookResult = (0, _slicedToArray2.default)(hookResult, 2); | |
row = _hookResult[0]; | |
column = _hookResult[1]; | |
} | |
if (this.isRowBeforeRenderedRows(row)) { | |
// row before rendered rows | |
return -1; | |
} else if (this.isRowAfterRenderedRows(row)) { | |
// row after rendered rows | |
return -2; | |
} else if (this.isColumnBeforeRenderedColumns(column)) { | |
// column before rendered columns | |
return -3; | |
} else if (this.isColumnAfterRenderedColumns(column)) { | |
// column after rendered columns | |
return -4; | |
} | |
if (row < 0) { | |
var columnHeaders = this.wot.getSetting('columnHeaders'); | |
var columnHeadersCount = columnHeaders.length; | |
var zeroBasedHeaderLevel = columnHeadersCount + row; | |
return this.getColumnHeader(column, zeroBasedHeaderLevel); | |
} | |
var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)]; | |
if (!TR && row >= 0) { | |
throw new Error('TR was expected to be rendered but is not'); | |
} | |
var TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(column)]; | |
if (!TD && column >= 0) { | |
throw new Error('TD or TH was expected to be rendered but is not'); | |
} | |
return TD; | |
} | |
/** | |
* getColumnHeader | |
* | |
* @param {Number} col Column index | |
* @param {Number} [level=0] Header level (0 = most distant to the table) | |
* @returns {Object} HTMLElement on success or undefined on error | |
*/ | |
}, { | |
key: "getColumnHeader", | |
value: function getColumnHeader(col) { | |
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; | |
var TR = this.THEAD.childNodes[level]; | |
if (TR) { | |
return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(col)]; | |
} | |
} | |
/** | |
* getRowHeader | |
* | |
* @param {Number} row Row index | |
* @returns {HTMLElement} HTMLElement on success or Number one of the exit codes on error: `null table doesn't have row headers` | |
*/ | |
}, { | |
key: "getRowHeader", | |
value: function getRowHeader(row) { | |
if (this.columnFilter.sourceColumnToVisibleRowHeadedColumn(0) === 0) { | |
return null; | |
} | |
var TR = this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)]; | |
if (TR) { | |
return TR.childNodes[0]; | |
} | |
} | |
/** | |
* Returns cell coords object for a given TD (or a child element of a TD element). | |
* | |
* @param {HTMLTableCellElement} TD A cell DOM element (or a child of one). | |
* @returns {CellCoords|null} The coordinates of the provided TD element (or the closest TD element) or null, if the provided element is not applicable. | |
*/ | |
}, { | |
key: "getCoords", | |
value: function getCoords(TD) { | |
var cellElement = TD; | |
if (cellElement.nodeName !== 'TD' && cellElement.nodeName !== 'TH') { | |
cellElement = (0, _element.closest)(cellElement, ['TD', 'TH']); | |
} | |
if (cellElement === null) { | |
return null; | |
} | |
var TR = cellElement.parentNode; | |
var CONTAINER = TR.parentNode; | |
var row = (0, _element.index)(TR); | |
var col = cellElement.cellIndex; | |
if ((0, _element.overlayContainsElement)(_base.default.CLONE_TOP_LEFT_CORNER, cellElement, this.wtRootElement) || (0, _element.overlayContainsElement)(_base.default.CLONE_TOP, cellElement, this.wtRootElement)) { | |
if (CONTAINER.nodeName === 'THEAD') { | |
row -= CONTAINER.childNodes.length; | |
} | |
} else if ((0, _element.overlayContainsElement)(_base.default.CLONE_BOTTOM_LEFT_CORNER, cellElement, this.wtRootElement) || (0, _element.overlayContainsElement)(_base.default.CLONE_BOTTOM, cellElement, this.wtRootElement)) { | |
var totalRows = this.wot.getSetting('totalRows'); | |
row = totalRows - CONTAINER.childNodes.length + row; | |
} else if (CONTAINER === this.THEAD) { | |
row = this.rowFilter.visibleColHeadedRowToSourceRow(row); | |
} else { | |
row = this.rowFilter.renderedToSource(row); | |
} | |
if ((0, _element.overlayContainsElement)(_base.default.CLONE_TOP_LEFT_CORNER, cellElement, this.wtRootElement) || (0, _element.overlayContainsElement)(_base.default.CLONE_LEFT, cellElement, this.wtRootElement) || (0, _element.overlayContainsElement)(_base.default.CLONE_BOTTOM_LEFT_CORNER, cellElement, this.wtRootElement)) { | |
col = this.columnFilter.offsettedTH(col); | |
} else { | |
col = this.columnFilter.visibleRowHeadedColumnToSourceColumn(col); | |
} | |
return new _coords.default(row, col); | |
} | |
/** | |
* Check if any of the rendered rows is higher than expected, and if so, cache them | |
*/ | |
}, { | |
key: "markOversizedRows", | |
value: function markOversizedRows() { | |
if (this.wot.getSetting('externalRowCalculator')) { | |
return; | |
} | |
var rowCount = this.TBODY.childNodes.length; | |
var expectedTableHeight = rowCount * this.wot.wtSettings.settings.defaultRowHeight; | |
var actualTableHeight = (0, _element.innerHeight)(this.TBODY) - 1; | |
var previousRowHeight; | |
var rowInnerHeight; | |
var sourceRowIndex; | |
var currentTr; | |
var rowHeader; | |
if (expectedTableHeight === actualTableHeight && !this.wot.getSetting('fixedRowsBottom')) { | |
// If the actual table height equals rowCount * default single row height, no row is oversized -> no need to iterate over them | |
return; | |
} | |
while (rowCount) { | |
rowCount -= 1; | |
sourceRowIndex = this.rowFilter.renderedToSource(rowCount); | |
previousRowHeight = this.getRowHeight(sourceRowIndex); | |
currentTr = this.getTrForRow(sourceRowIndex); | |
rowHeader = currentTr.querySelector('th'); | |
if (rowHeader) { | |
rowInnerHeight = (0, _element.innerHeight)(rowHeader); | |
} else { | |
rowInnerHeight = (0, _element.innerHeight)(currentTr) - 1; | |
} | |
if (!previousRowHeight && this.wot.wtSettings.settings.defaultRowHeight < rowInnerHeight || previousRowHeight < rowInnerHeight) { | |
rowInnerHeight += 1; | |
this.wot.wtViewport.oversizedRows[sourceRowIndex] = rowInnerHeight; | |
} | |
} | |
} | |
}, { | |
key: "getTrForRow", | |
value: function getTrForRow(row) { | |
return this.TBODY.childNodes[this.rowFilter.sourceToRendered(row)]; | |
} | |
/** | |
* 0-based index of column header | |
* | |
* @param {Number} level | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isColumnHeaderLevelRendered", | |
value: function isColumnHeaderLevelRendered(level) { | |
var columnHeaders = this.wot.getSetting('columnHeaders'); | |
var columnHeadersCount = columnHeaders.length; | |
return level > columnHeadersCount - 1; | |
} | |
/** | |
* 0-based index of row header | |
* | |
* @param {Number} level | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isRowHeaderLevelRendered", | |
value: function isRowHeaderLevelRendered(level) { | |
var columnHeaders = this.wot.getSetting('rowHeaders'); | |
var columnHeadersCount = columnHeaders.length; | |
return level > columnHeadersCount - 1; | |
} | |
/** | |
* Check if the given row index is smaller than the index of the first row that is currently redered | |
* and return TRUE in that case, or FALSE otherwise. | |
* | |
* Negative row index is used to check the header cells. As a simplification, it checks negative row index | |
* the same way as a regular row 0. You can interpret this as follows: If the row 0 is rendered, all header | |
* cells are also rendered. | |
* | |
* @param {Number} row | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isRowBeforeRenderedRows", | |
value: function isRowBeforeRenderedRows(row) { | |
var first = this.getFirstRenderedRow(); | |
if (row < 0) { | |
row = 0; | |
} | |
if (first === -1) { | |
return true; | |
} | |
return row < first; | |
} | |
}, { | |
key: "isRowAfterViewport", | |
value: function isRowAfterViewport(row) { | |
return this.rowFilter && row > this.getLastVisibleRow(); | |
} | |
/** | |
* Check if the given column index is larger than the index of the last column that is currently redered | |
* and return TRUE in that case, or FALSE otherwise. | |
* | |
* Negative column index is used to check the header cells. | |
* | |
* @param {Number} column | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isRowAfterRenderedRows", | |
value: function isRowAfterRenderedRows(row) { | |
if (row < 0) { | |
var columnHeaders = this.wot.getSetting('columnHeaders'); | |
var columnHeadersCount = columnHeaders.length; | |
var zeroBasedHeaderLevel = columnHeadersCount + row; | |
return this.isColumnHeaderLevelRendered(zeroBasedHeaderLevel); | |
} | |
return row > this.getLastRenderedRow(); | |
} | |
}, { | |
key: "isColumnBeforeViewport", | |
value: function isColumnBeforeViewport(column) { | |
return this.columnFilter && this.columnFilter.sourceToRendered(column) < 0 && column >= 0; | |
} | |
/** | |
* Check if the given column index is smaller than the index of the first column that is currently redered | |
* and return TRUE in that case, or FALSE otherwise. | |
* | |
* Negative column index is used to check the header cells. As a simplification, it checks negative column index | |
* the same way as a regular column 0. You can interpret this as follows: If the column 0 is rendered, all header | |
* cells are also rendered. | |
* | |
* @param {Number} column | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isColumnBeforeRenderedColumns", | |
value: function isColumnBeforeRenderedColumns(column) { | |
var first = this.getFirstRenderedColumn(); | |
if (column < 0) { | |
column = 0; | |
} | |
if (first === -1) { | |
return true; | |
} | |
return column < first; | |
} | |
}, { | |
key: "isColumnAfterViewport", | |
value: function isColumnAfterViewport(column) { | |
return this.columnFilter && column > this.getLastVisibleColumn(); | |
} | |
/** | |
* Check if the given column index is larger than the index of the last column that is currently redered | |
* and return TRUE in that case, or FALSE otherwise. | |
* | |
* Negative column index is used to check the header cells. | |
* | |
* @param {Number} column | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isColumnAfterRenderedColumns", | |
value: function isColumnAfterRenderedColumns(column) { | |
if (column < 0) { | |
var rowHeaders = this.wot.getSetting('rowHeaders'); | |
var rowHeadersCount = rowHeaders.length; | |
var zeroBasedHeaderLevel = rowHeadersCount + column; | |
return this.isRowHeaderLevelRendered(zeroBasedHeaderLevel); | |
} | |
return this.columnFilter && column > this.getLastRenderedColumn(); | |
} | |
}, { | |
key: "isLastRowFullyVisible", | |
value: function isLastRowFullyVisible() { | |
return this.getLastVisibleRow() === this.getLastRenderedRow(); | |
} | |
}, { | |
key: "isLastColumnFullyVisible", | |
value: function isLastColumnFullyVisible() { | |
return this.getLastVisibleColumn() === this.getLastRenderedColumn(); | |
} | |
}, { | |
key: "allRowsInViewport", | |
value: function allRowsInViewport() { | |
return this.wot.getSetting('totalRows') === this.getVisibleRowsCount(); | |
} | |
}, { | |
key: "allColumnsInViewport", | |
value: function allColumnsInViewport() { | |
return this.wot.getSetting('totalColumns') === this.getVisibleColumnsCount(); | |
} | |
/** | |
* Checks if any of the row's cells content exceeds its initial height, and if so, returns the oversized height | |
* | |
* @param {Number} sourceRow | |
* @returns {Number} | |
*/ | |
}, { | |
key: "getRowHeight", | |
value: function getRowHeight(sourceRow) { | |
return this.rowUtils.getHeight(sourceRow); | |
} | |
}, { | |
key: "getColumnHeaderHeight", | |
value: function getColumnHeaderHeight(level) { | |
return this.columnUtils.getHeaderHeight(level); | |
} | |
}, { | |
key: "getColumnWidth", | |
value: function getColumnWidth(sourceColumn) { | |
return this.columnUtils.getWidth(sourceColumn); | |
} | |
}, { | |
key: "getStretchedColumnWidth", | |
value: function getStretchedColumnWidth(sourceColumn) { | |
return this.columnUtils.getStretchedColumnWidth(sourceColumn); | |
} | |
/** | |
* Checks if the table has defined size. It returns `true` when the table has width and height | |
* set bigger than `0px`. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "hasDefinedSize", | |
value: function hasDefinedSize() { | |
return this.hasTableHeight && this.hasTableWidth; | |
} | |
/** | |
* Checks if the table is visible. It returns `true` when the holder element (or its parents) | |
* has CSS 'display' property different than 'none'. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isVisible", | |
value: function isVisible() { | |
return (0, _element.isVisible)(this.TABLE); | |
} | |
/** | |
* Modify row header widths provided by user in class contructor. | |
* | |
* @private | |
*/ | |
}, { | |
key: "_modifyRowHeaderWidth", | |
value: function _modifyRowHeaderWidth(rowHeaderWidthFactory) { | |
var widths = (0, _function.isFunction)(rowHeaderWidthFactory) ? rowHeaderWidthFactory() : null; | |
if (Array.isArray(widths)) { | |
widths = (0, _toConsumableArray2.default)(widths); | |
widths[widths.length - 1] = this._correctRowHeaderWidth(widths[widths.length - 1]); | |
} else { | |
widths = this._correctRowHeaderWidth(widths); | |
} | |
return widths; | |
} | |
/** | |
* Correct row header width if necessary. | |
* | |
* @private | |
*/ | |
}, { | |
key: "_correctRowHeaderWidth", | |
value: function _correctRowHeaderWidth(width) { | |
var rowHeaderWidth = width; | |
if (typeof width !== 'number') { | |
rowHeaderWidth = this.wot.getSetting('defaultColumnWidth'); | |
} | |
if (this.correctHeaderWidth) { | |
rowHeaderWidth += 1; | |
} | |
return rowHeaderWidth; | |
} | |
}]); | |
return Table; | |
}(); | |
var _default = Table; | |
exports.default = _default; | |
/***/ }), | |
/* 95 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var $map = __webpack_require__(89).map; | |
var arrayMethodHasSpeciesSupport = __webpack_require__(109); | |
// `Array.prototype.map` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.map | |
// with adding support of @@species | |
$({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('map') }, { | |
map: function map(callbackfn /* , thisArg */) { | |
return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); | |
} | |
}); | |
/***/ }), | |
/* 96 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(17); | |
exports.__esModule = true; | |
exports.createId = createId; | |
exports.createDefaultCustomBorder = createDefaultCustomBorder; | |
exports.createSingleEmptyBorder = createSingleEmptyBorder; | |
exports.createDefaultHtBorder = createDefaultHtBorder; | |
exports.createEmptyBorders = createEmptyBorders; | |
exports.extendDefaultBorder = extendDefaultBorder; | |
exports.checkSelectionBorders = checkSelectionBorders; | |
exports.markSelected = markSelected; | |
var _object = __webpack_require__(4); | |
var _array = __webpack_require__(3); | |
/** | |
* Create separated id for borders for each cell. | |
* | |
* @param {Number} row Visual row index. | |
* @param {Number} col Visual column index. | |
* @returns {String} | |
*/ | |
function createId(row, col) { | |
return "border_row".concat(row, "col").concat(col); | |
} | |
/** | |
* Create default single border for each position (top/right/bottom/left). | |
* | |
* @returns {Object} `{{width: number, color: string}}` | |
*/ | |
function createDefaultCustomBorder() { | |
return { | |
width: 1, | |
color: '#000' | |
}; | |
} | |
/** | |
* Create default object for empty border. | |
* | |
* @returns {Object} `{{hide: boolean}}` | |
*/ | |
function createSingleEmptyBorder() { | |
return { | |
hide: true | |
}; | |
} | |
/** | |
* Create default Handsontable border object. | |
* | |
* @returns {Object} `{{width: number, color: string, cornerVisible: boolean}}` | |
*/ | |
function createDefaultHtBorder() { | |
return { | |
width: 1, | |
color: '#000', | |
cornerVisible: false | |
}; | |
} | |
/** | |
* Prepare empty border for each cell with all custom borders hidden. | |
* | |
* @param {Number} row Visual row index. | |
* @param {Number} col Visual column index. | |
* @returns {Object} `{{id: *, border: *, row: *, col: *, top: {hide: boolean}, right: {hide: boolean}, bottom: {hide: boolean}, left: {hide: boolean}}}` | |
*/ | |
function createEmptyBorders(row, col) { | |
return { | |
id: createId(row, col), | |
border: createDefaultHtBorder(), | |
row: row, | |
col: col, | |
top: createSingleEmptyBorder(), | |
right: createSingleEmptyBorder(), | |
bottom: createSingleEmptyBorder(), | |
left: createSingleEmptyBorder() | |
}; | |
} | |
function extendDefaultBorder(defaultBorder, customBorder) { | |
if ((0, _object.hasOwnProperty)(customBorder, 'border')) { | |
defaultBorder.border = customBorder.border; | |
} | |
if ((0, _object.hasOwnProperty)(customBorder, 'top')) { | |
if (customBorder.top) { | |
if (!(0, _object.isObject)(customBorder.top)) { | |
customBorder.top = createDefaultCustomBorder(); | |
} | |
defaultBorder.top = customBorder.top; | |
} else { | |
customBorder.top = createSingleEmptyBorder(); | |
defaultBorder.top = customBorder.top; | |
} | |
} | |
if ((0, _object.hasOwnProperty)(customBorder, 'right')) { | |
if (customBorder.right) { | |
if (!(0, _object.isObject)(customBorder.right)) { | |
customBorder.right = createDefaultCustomBorder(); | |
} | |
defaultBorder.right = customBorder.right; | |
} else { | |
customBorder.right = createSingleEmptyBorder(); | |
defaultBorder.right = customBorder.right; | |
} | |
} | |
if ((0, _object.hasOwnProperty)(customBorder, 'bottom')) { | |
if (customBorder.bottom) { | |
if (!(0, _object.isObject)(customBorder.bottom)) { | |
customBorder.bottom = createDefaultCustomBorder(); | |
} | |
defaultBorder.bottom = customBorder.bottom; | |
} else { | |
customBorder.bottom = createSingleEmptyBorder(); | |
defaultBorder.bottom = customBorder.bottom; | |
} | |
} | |
if ((0, _object.hasOwnProperty)(customBorder, 'left')) { | |
if (customBorder.left) { | |
if (!(0, _object.isObject)(customBorder.left)) { | |
customBorder.left = createDefaultCustomBorder(); | |
} | |
defaultBorder.left = customBorder.left; | |
} else { | |
customBorder.left = createSingleEmptyBorder(); | |
defaultBorder.left = customBorder.left; | |
} | |
} | |
return defaultBorder; | |
} | |
/** | |
* Check if selection has border. | |
* | |
* @param hot | |
* @param direction | |
*/ | |
function checkSelectionBorders(hot, direction) { | |
var atLeastOneHasBorder = false; | |
(0, _array.arrayEach)(hot.getSelectedRange(), function (range) { | |
range.forAll(function (r, c) { | |
var metaBorders = hot.getCellMeta(r, c).borders; | |
if (metaBorders) { | |
if (direction) { | |
if (!(0, _object.hasOwnProperty)(metaBorders[direction], 'hide') || metaBorders[direction].hide === false) { | |
atLeastOneHasBorder = true; | |
return false; // breaks forAll | |
} | |
} else { | |
atLeastOneHasBorder = true; | |
return false; // breaks forAll | |
} | |
} | |
}); | |
}); | |
return atLeastOneHasBorder; | |
} | |
/** | |
* Mark label in contextMenu as selected. | |
* | |
* @param label | |
* @returns {string} | |
*/ | |
function markSelected(label) { | |
return "<span class=\"selected\">".concat(String.fromCharCode(10003), "</span>").concat(label); // workaround for https://github.com/handsontable/handsontable/issues/1946 | |
} | |
/***/ }), | |
/* 97 */ | |
/***/ (function(module, exports) { | |
module.exports = function (bitmap, value) { | |
return { | |
enumerable: !(bitmap & 1), | |
configurable: !(bitmap & 2), | |
writable: !(bitmap & 4), | |
value: value | |
}; | |
}; | |
/***/ }), | |
/* 98 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var isObject = __webpack_require__(44); | |
// `ToPrimitive` abstract operation | |
// https://tc39.github.io/ecma262/#sec-toprimitive | |
// 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 (input, PREFERRED_STRING) { | |
if (!isObject(input)) return input; | |
var fn, val; | |
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; | |
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; | |
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; | |
throw TypeError("Can't convert object to primitive value"); | |
}; | |
/***/ }), | |
/* 99 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var IS_PURE = __webpack_require__(125); | |
var store = __webpack_require__(408); | |
(module.exports = function (key, value) { | |
return store[key] || (store[key] = value !== undefined ? value : {}); | |
})('versions', []).push({ | |
version: '3.3.2', | |
mode: IS_PURE ? 'pure' : 'global', | |
copyright: '© 2019 Denis Pushkarev (zloirock.ru)' | |
}); | |
/***/ }), | |
/* 100 */ | |
/***/ (function(module, exports) { | |
module.exports = {}; | |
/***/ }), | |
/* 101 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var internalObjectKeys = __webpack_require__(196); | |
var enumBugKeys = __webpack_require__(150); | |
var hiddenKeys = enumBugKeys.concat('length', 'prototype'); | |
// `Object.getOwnPropertyNames` method | |
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames | |
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { | |
return internalObjectKeys(O, hiddenKeys); | |
}; | |
/***/ }), | |
/* 102 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var wellKnownSymbol = __webpack_require__(37); | |
var create = __webpack_require__(103); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var UNSCOPABLES = wellKnownSymbol('unscopables'); | |
var ArrayPrototype = Array.prototype; | |
// Array.prototype[@@unscopables] | |
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables | |
if (ArrayPrototype[UNSCOPABLES] == undefined) { | |
createNonEnumerableProperty(ArrayPrototype, UNSCOPABLES, create(null)); | |
} | |
// add a key to Array.prototype[@@unscopables] | |
module.exports = function (key) { | |
ArrayPrototype[UNSCOPABLES][key] = true; | |
}; | |
/***/ }), | |
/* 103 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var anObject = __webpack_require__(47); | |
var defineProperties = __webpack_require__(413); | |
var enumBugKeys = __webpack_require__(150); | |
var hiddenKeys = __webpack_require__(100); | |
var html = __webpack_require__(199); | |
var documentCreateElement = __webpack_require__(147); | |
var sharedKey = __webpack_require__(126); | |
var IE_PROTO = sharedKey('IE_PROTO'); | |
var PROTOTYPE = 'prototype'; | |
var Empty = function () { /* empty */ }; | |
// Create object with fake `null` prototype: use iframe Object with cleared prototype | |
var createDict = function () { | |
// Thrash, waste and sodomy: IE GC bug | |
var iframe = documentCreateElement('iframe'); | |
var length = enumBugKeys.length; | |
var lt = '<'; | |
var script = 'script'; | |
var gt = '>'; | |
var js = 'java' + script + ':'; | |
var iframeDocument; | |
iframe.style.display = 'none'; | |
html.appendChild(iframe); | |
iframe.src = String(js); | |
iframeDocument = iframe.contentWindow.document; | |
iframeDocument.open(); | |
iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt); | |
iframeDocument.close(); | |
createDict = iframeDocument.F; | |
while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]]; | |
return createDict(); | |
}; | |
// `Object.create` method | |
// https://tc39.github.io/ecma262/#sec-object.create | |
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 : defineProperties(result, Properties); | |
}; | |
hiddenKeys[IE_PROTO] = true; | |
/***/ }), | |
/* 104 */ | |
/***/ (function(module, exports) { | |
module.exports = {}; | |
/***/ }), | |
/* 105 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var aFunction = __webpack_require__(157); | |
// optional / simple context binding | |
module.exports = function (fn, that, length) { | |
aFunction(fn); | |
if (that === undefined) return fn; | |
switch (length) { | |
case 0: return function () { | |
return fn.call(that); | |
}; | |
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); | |
}; | |
}; | |
/***/ }), | |
/* 106 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var classof = __webpack_require__(78); | |
// `IsArray` abstract operation | |
// https://tc39.github.io/ecma262/#sec-isarray | |
module.exports = Array.isArray || function isArray(arg) { | |
return classof(arg) == 'Array'; | |
}; | |
/***/ }), | |
/* 107 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var fails = __webpack_require__(28); | |
module.exports = function (METHOD_NAME, argument) { | |
var method = [][METHOD_NAME]; | |
return !method || !fails(function () { | |
// eslint-disable-next-line no-useless-call,no-throw-literal | |
method.call(null, argument || function () { throw 1; }, 1); | |
}); | |
}; | |
/***/ }), | |
/* 108 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var toPrimitive = __webpack_require__(98); | |
var definePropertyModule = __webpack_require__(56); | |
var createPropertyDescriptor = __webpack_require__(97); | |
module.exports = function (object, key, value) { | |
var propertyKey = toPrimitive(key); | |
if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value)); | |
else object[propertyKey] = value; | |
}; | |
/***/ }), | |
/* 109 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var fails = __webpack_require__(28); | |
var wellKnownSymbol = __webpack_require__(37); | |
var SPECIES = wellKnownSymbol('species'); | |
module.exports = function (METHOD_NAME) { | |
return !fails(function () { | |
var array = []; | |
var constructor = array.constructor = {}; | |
constructor[SPECIES] = function () { | |
return { foo: 1 }; | |
}; | |
return array[METHOD_NAME](Boolean).foo !== 1; | |
}); | |
}; | |
/***/ }), | |
/* 110 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(137); | |
exports.__esModule = true; | |
exports.default = exports.EditorState = void 0; | |
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(6)); | |
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(5)); | |
var _inherits2 = _interopRequireDefault(__webpack_require__(7)); | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _src = __webpack_require__(26); | |
var _mixed = __webpack_require__(24); | |
var _object = __webpack_require__(4); | |
var _hooksRefRegisterer = _interopRequireDefault(__webpack_require__(458)); | |
var EditorState = { | |
VIRGIN: 'STATE_VIRGIN', | |
// before editing | |
EDITING: 'STATE_EDITING', | |
WAITING: 'STATE_WAITING', | |
// waiting for async validation | |
FINISHED: 'STATE_FINISHED' | |
}; | |
/** | |
* @util | |
* @class BaseEditor | |
*/ | |
exports.EditorState = EditorState; | |
var BaseEditor = | |
/*#__PURE__*/ | |
function () { | |
function BaseEditor(instance) { | |
(0, _classCallCheck2.default)(this, BaseEditor); | |
/** | |
* A reference to the source instance of the Handsontable. | |
* | |
* @type {Handsontable} | |
*/ | |
this.hot = instance; | |
/** | |
* A reference to the source instance of the Handsontable. | |
* @deprecated | |
* | |
* @type {Handsontable} | |
*/ | |
this.instance = instance; | |
/** | |
* Editor's state. | |
* | |
* @type {String} | |
*/ | |
this.state = EditorState.VIRGIN; | |
/** | |
* Flag to store information about editor's opening status. | |
* @private | |
* | |
* @type {Boolean} | |
*/ | |
this._opened = false; | |
/** | |
* Defines the editor's editing mode. When false, then an editor works in fast editing mode. | |
* @private | |
* | |
* @type {Boolean} | |
*/ | |
this._fullEditMode = false; | |
/** | |
* Callback to call after closing editor. | |
* | |
* @type {Function} | |
*/ | |
this._closeCallback = null; | |
/** | |
* Currently rendered cell's TD element. | |
* | |
* @type {HTMLTableCellElement} | |
*/ | |
this.TD = null; | |
/** | |
* Visual row index. | |
* | |
* @type {Number} | |
*/ | |
this.row = null; | |
/** | |
* Visual column index. | |
* | |
* @type {Number} | |
*/ | |
this.col = null; | |
/** | |
* Column property name or a column index, if datasource is an array of arrays. | |
* | |
* @type {Number|String} | |
*/ | |
this.prop = null; | |
/** | |
* Original cell's value. | |
* | |
* @type {*} | |
*/ | |
this.originalValue = null; | |
/** | |
* Object containing the cell's properties. | |
* | |
* @type {Object} | |
*/ | |
this.cellProperties = null; | |
this.init(); | |
} | |
/** | |
* Fires callback after closing editor. | |
* | |
* @private | |
* @param {Boolean} result | |
*/ | |
(0, _createClass2.default)(BaseEditor, [{ | |
key: "_fireCallbacks", | |
value: function _fireCallbacks(result) { | |
if (this._closeCallback) { | |
this._closeCallback(result); | |
this._closeCallback = null; | |
} | |
} | |
/** | |
* Initializes an editor's intance. | |
*/ | |
}, { | |
key: "init", | |
value: function init() {} | |
/** | |
* Required method to get current value from editable element. | |
*/ | |
}, { | |
key: "getValue", | |
value: function getValue() { | |
throw Error('Editor getValue() method unimplemented'); | |
} | |
/** | |
* Required method to set new value into editable element. | |
*/ | |
}, { | |
key: "setValue", | |
value: function setValue() { | |
throw Error('Editor setValue() method unimplemented'); | |
} | |
/** | |
* Required method to open editor. | |
*/ | |
}, { | |
key: "open", | |
value: function open() { | |
throw Error('Editor open() method unimplemented'); | |
} | |
/** | |
* Required method to close editor. | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
throw Error('Editor close() method unimplemented'); | |
} | |
/** | |
* Prepares editor's meta data. | |
* | |
* @param {Number} row | |
* @param {Number} col | |
* @param {Number|String} prop | |
* @param {HTMLTableCellElement} td | |
* @param {*} originalValue | |
* @param {Object} cellProperties | |
*/ | |
}, { | |
key: "prepare", | |
value: function prepare(row, col, prop, td, originalValue, cellProperties) { | |
this.TD = td; | |
this.row = row; | |
this.col = col; | |
this.prop = prop; | |
this.originalValue = originalValue; | |
this.cellProperties = cellProperties; | |
this.state = EditorState.VIRGIN; | |
} | |
/** | |
* Fallback method to provide extendable editors in ES5. | |
*/ | |
}, { | |
key: "extend", | |
value: function extend() { | |
return ( | |
/*#__PURE__*/ | |
function (_this$constructor) { | |
(0, _inherits2.default)(Editor, _this$constructor); | |
function Editor() { | |
(0, _classCallCheck2.default)(this, Editor); | |
return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Editor).apply(this, arguments)); | |
} | |
return Editor; | |
}(this.constructor) | |
); | |
} | |
/** | |
* Saves value from editor into data storage. | |
* | |
* @param {*} value | |
* @param {Boolean} ctrlDown If true, applies value to each cell in the last selected range. | |
*/ | |
}, { | |
key: "saveValue", | |
value: function saveValue(value, ctrlDown) { | |
var selection; | |
var tmp; // if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) | |
if (ctrlDown) { | |
selection = this.hot.getSelectedLast(); | |
if (selection[0] > selection[2]) { | |
tmp = selection[0]; | |
selection[0] = selection[2]; | |
selection[2] = tmp; | |
} | |
if (selection[1] > selection[3]) { | |
tmp = selection[1]; | |
selection[1] = selection[3]; | |
selection[3] = tmp; | |
} | |
} else { | |
selection = [this.row, this.col, null, null]; | |
} | |
this.hot.populateFromArray(selection[0], selection[1], value, selection[2], selection[3], 'edit'); | |
} | |
/** | |
* Begins editing on a highlighted cell and hides fillHandle corner if was present. | |
* | |
* @param {*} newInitialValue | |
* @param {*} event | |
*/ | |
}, { | |
key: "beginEditing", | |
value: function beginEditing(newInitialValue, event) { | |
if (this.state !== EditorState.VIRGIN) { | |
return; | |
} | |
this.hot.view.scrollViewport(new _src.CellCoords(this.row, this.col)); | |
this.state = EditorState.EDITING; // Set the editor value only in the full edit mode. In other mode the focusable element has to be empty, | |
// otherwise IME (editor for Asia users) doesn't work. | |
if (this.isInFullEditMode()) { | |
var stringifiedInitialValue = typeof newInitialValue === 'string' ? newInitialValue : (0, _mixed.stringify)(this.originalValue); | |
this.setValue(stringifiedInitialValue); | |
} | |
this.open(event); | |
this._opened = true; | |
this.focus(); // only rerender the selections (FillHandle should disappear when beginediting is triggered) | |
this.hot.view.render(); | |
this.hot.runHooks('afterBeginEditing', this.row, this.col); | |
} | |
/** | |
* Finishes editing and start saving or restoring process for editing cell or last selected range. | |
* | |
* @param {Boolean} restoreOriginalValue If true, then closes editor without saving value from the editor into a cell. | |
* @param {Boolean} ctrlDown If true, then saveValue will save editor's value to each cell in the last selected range. | |
* @param {Function} callback | |
*/ | |
}, { | |
key: "finishEditing", | |
value: function finishEditing(restoreOriginalValue, ctrlDown, callback) { | |
var _this = this; | |
var val; | |
if (callback) { | |
var previousCloseCallback = this._closeCallback; | |
this._closeCallback = function (result) { | |
if (previousCloseCallback) { | |
previousCloseCallback(result); | |
} | |
callback(result); | |
_this.hot.view.render(); | |
}; | |
} | |
if (this.isWaiting()) { | |
return; | |
} | |
if (this.state === EditorState.VIRGIN) { | |
this.hot._registerTimeout(function () { | |
_this._fireCallbacks(true); | |
}); | |
return; | |
} | |
if (this.state === EditorState.EDITING) { | |
if (restoreOriginalValue) { | |
this.cancelChanges(); | |
this.hot.view.render(); | |
return; | |
} | |
var value = this.getValue(); | |
if (this.hot.getSettings().trimWhitespace) { | |
// We trim only string values | |
val = [[typeof value === 'string' ? String.prototype.trim.call(value || '') : value]]; | |
} else { | |
val = [[value]]; | |
} | |
this.state = EditorState.WAITING; | |
this.saveValue(val, ctrlDown); | |
if (this.hot.getCellValidator(this.cellProperties)) { | |
this.hot.addHookOnce('postAfterValidate', function (result) { | |
_this.state = EditorState.FINISHED; | |
_this.discardEditor(result); | |
}); | |
} else { | |
this.state = EditorState.FINISHED; | |
this.discardEditor(true); | |
} | |
} | |
} | |
/** | |
* Finishes editing without singout saving value. | |
*/ | |
}, { | |
key: "cancelChanges", | |
value: function cancelChanges() { | |
this.state = EditorState.FINISHED; | |
this.discardEditor(); | |
} | |
/** | |
* Verifies result of validation or closes editor if user's cancelled changes. | |
* | |
* @param {Boolean|undefined} result | |
*/ | |
}, { | |
key: "discardEditor", | |
value: function discardEditor(result) { | |
if (this.state !== EditorState.FINISHED) { | |
return; | |
} // validator was defined and failed | |
if (result === false && this.cellProperties.allowInvalid !== true) { | |
this.hot.selectCell(this.row, this.col); | |
this.focus(); | |
this.state = EditorState.EDITING; | |
this._fireCallbacks(false); | |
} else { | |
this.close(); | |
this._opened = false; | |
this._fullEditMode = false; | |
this.state = EditorState.VIRGIN; | |
this._fireCallbacks(true); | |
} | |
} | |
/** | |
* Switch editor into full edit mode. In this state navigation keys don't close editor. This mode is activated | |
* automatically after hit ENTER or F2 key on the cell or while editing cell press F2 key. | |
*/ | |
}, { | |
key: "enableFullEditMode", | |
value: function enableFullEditMode() { | |
this._fullEditMode = true; | |
} | |
/** | |
* Checks if editor is in full edit mode. | |
* | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isInFullEditMode", | |
value: function isInFullEditMode() { | |
return this._fullEditMode; | |
} | |
/** | |
* Returns information whether the editor is open. | |
*/ | |
}, { | |
key: "isOpened", | |
value: function isOpened() { | |
return this._opened; | |
} | |
/** | |
* Returns information whether the editor is waiting, eg.: for async validation. | |
*/ | |
}, { | |
key: "isWaiting", | |
value: function isWaiting() { | |
return this.state === EditorState.WAITING; | |
} | |
/** | |
* Gets className of the edited cell if exist. | |
* | |
* @returns {string} | |
*/ | |
}, { | |
key: "getEditedCellsLayerClass", | |
value: function getEditedCellsLayerClass() { | |
var editorSection = this.checkEditorSection(); | |
switch (editorSection) { | |
case 'right': | |
return 'ht_clone_right'; | |
case 'left': | |
return 'ht_clone_left'; | |
case 'bottom': | |
return 'ht_clone_bottom'; | |
case 'bottom-right-corner': | |
return 'ht_clone_bottom_right_corner'; | |
case 'bottom-left-corner': | |
return 'ht_clone_bottom_left_corner'; | |
case 'top': | |
return 'ht_clone_top'; | |
case 'top-right-corner': | |
return 'ht_clone_top_right_corner'; | |
case 'top-left-corner': | |
return 'ht_clone_top_left_corner'; | |
default: | |
return 'ht_clone_master'; | |
} | |
} | |
/** | |
* Gets HTMLTableCellElement of the edited cell if exist. | |
* | |
* @returns {HTMLTableCellElement|null} | |
*/ | |
}, { | |
key: "getEditedCell", | |
value: function getEditedCell() { | |
return this.hot.getCell(this.row, this.col, true); | |
} | |
/** | |
* Returns name of the overlay, where editor is placed. | |
* | |
* @private | |
*/ | |
}, { | |
key: "checkEditorSection", | |
value: function checkEditorSection() { | |
var totalRows = this.hot.countRows(); | |
var section = ''; | |
if (this.row < this.hot.getSettings().fixedRowsTop) { | |
if (this.col < this.hot.getSettings().fixedColumnsLeft) { | |
section = 'top-left-corner'; | |
} else { | |
section = 'top'; | |
} | |
} else if (this.hot.getSettings().fixedRowsBottom && this.row >= totalRows - this.hot.getSettings().fixedRowsBottom) { | |
if (this.col < this.hot.getSettings().fixedColumnsLeft) { | |
section = 'bottom-left-corner'; | |
} else { | |
section = 'bottom'; | |
} | |
} else if (this.col < this.hot.getSettings().fixedColumnsLeft) { | |
section = 'left'; | |
} | |
return section; | |
} | |
}]); | |
return BaseEditor; | |
}(); | |
(0, _object.mixin)(BaseEditor, _hooksRefRegisterer.default); | |
var _default = BaseEditor; | |
exports.default = _default; | |
/***/ }), | |
/* 111 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
/** | |
* CellCoords holds cell coordinates (row, column) and few method to validate them and retrieve as an array or an object. | |
* | |
* @util | |
*/ | |
var CellCoords = | |
/*#__PURE__*/ | |
function () { | |
function CellCoords(row, column) { | |
(0, _classCallCheck2.default)(this, CellCoords); | |
/** | |
* Row index. | |
* | |
* @type {Number} | |
*/ | |
this.row = null; | |
/** | |
* Column index. | |
* | |
* @type {Number} | |
*/ | |
this.col = null; | |
if (typeof row !== 'undefined' && typeof column !== 'undefined') { | |
this.row = row; | |
this.col = column; | |
} | |
} | |
/** | |
* Checks if given set of coordinates is valid in context of a given Walkontable instance. | |
* | |
* @param {Walkontable} wot A Walkontable instance. | |
* @returns {Boolean} | |
*/ | |
(0, _createClass2.default)(CellCoords, [{ | |
key: "isValid", | |
value: function isValid(wot) { | |
// is it a valid cell index (0 or higher) | |
if (this.row < 0 || this.col < 0) { | |
return false; | |
} // is selection within total rows and columns | |
if (this.row >= wot.getSetting('totalRows') || this.col >= wot.getSetting('totalColumns')) { | |
return false; | |
} | |
return true; | |
} | |
/** | |
* Checks if this cell coordinates are the same as cell coordinates given as an argument. | |
* | |
* @param {CellCoords} cellCoords Cell coordinates to equal. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isEqual", | |
value: function isEqual(cellCoords) { | |
if (cellCoords === this) { | |
return true; | |
} | |
return this.row === cellCoords.row && this.col === cellCoords.col; | |
} | |
/** | |
* Checks if tested coordinates are positioned in south-east from this cell coordinates. | |
* | |
* @param {Object} testedCoords Cell coordinates to check. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isSouthEastOf", | |
value: function isSouthEastOf(testedCoords) { | |
return this.row >= testedCoords.row && this.col >= testedCoords.col; | |
} | |
/** | |
* Checks if tested coordinates are positioned in north-east from this cell coordinates. | |
* | |
* @param {Object} testedCoords Cell coordinates to check. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isNorthWestOf", | |
value: function isNorthWestOf(testedCoords) { | |
return this.row <= testedCoords.row && this.col <= testedCoords.col; | |
} | |
/** | |
* Checks if tested coordinates are positioned in south-west from this cell coordinates. | |
* | |
* @param {Object} testedCoords Cell coordinates to check. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isSouthWestOf", | |
value: function isSouthWestOf(testedCoords) { | |
return this.row >= testedCoords.row && this.col <= testedCoords.col; | |
} | |
/** | |
* Checks if tested coordinates are positioned in north-east from this cell coordinates. | |
* | |
* @param {Object} testedCoords Cell coordinates to check. | |
* @returns {Boolean} | |
*/ | |
}, { | |
key: "isNorthEastOf", | |
value: function isNorthEastOf(testedCoords) { | |
return this.row <= testedCoords.row && this.col >= testedCoords.col; | |
} | |
/** | |
* Converts CellCoords to literal object with `row` and `col` properties. | |
* | |
* @return {Object} Returns a literal object with `row` and `col` properties. | |
*/ | |
}, { | |
key: "toObject", | |
value: function toObject() { | |
return { | |
row: this.row, | |
col: this.col | |
}; | |
} | |
}]); | |
return CellCoords; | |
}(); | |
var _default = CellCoords; | |
exports.default = _default; | |
/***/ }), | |
/* 112 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var DESCRIPTORS = __webpack_require__(51); | |
var global = __webpack_require__(38); | |
var isForced = __webpack_require__(130); | |
var inheritIfRequired = __webpack_require__(159); | |
var defineProperty = __webpack_require__(56).f; | |
var getOwnPropertyNames = __webpack_require__(101).f; | |
var isRegExp = __webpack_require__(163); | |
var getFlags = __webpack_require__(161); | |
var redefine = __webpack_require__(73); | |
var fails = __webpack_require__(28); | |
var setSpecies = __webpack_require__(211); | |
var wellKnownSymbol = __webpack_require__(37); | |
var MATCH = wellKnownSymbol('match'); | |
var NativeRegExp = global.RegExp; | |
var RegExpPrototype = NativeRegExp.prototype; | |
var re1 = /a/g; | |
var re2 = /a/g; | |
// "new" should create a new object, old webkit bug | |
var CORRECT_NEW = new NativeRegExp(re1) !== re1; | |
var FORCED = DESCRIPTORS && isForced('RegExp', (!CORRECT_NEW || fails(function () { | |
re2[MATCH] = false; | |
// RegExp constructor can alter flags and IsRegExp works correct with @@match | |
return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; | |
}))); | |
// `RegExp` constructor | |
// https://tc39.github.io/ecma262/#sec-regexp-constructor | |
if (FORCED) { | |
var RegExpWrapper = function RegExp(pattern, flags) { | |
var thisIsRegExp = this instanceof RegExpWrapper; | |
var patternIsRegExp = isRegExp(pattern); | |
var flagsAreUndefined = flags === undefined; | |
return !thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined ? pattern | |
: inheritIfRequired(CORRECT_NEW | |
? new NativeRegExp(patternIsRegExp && !flagsAreUndefined ? pattern.source : pattern, flags) | |
: NativeRegExp((patternIsRegExp = pattern instanceof RegExpWrapper) | |
? pattern.source | |
: pattern, patternIsRegExp && flagsAreUndefined ? getFlags.call(pattern) : flags) | |
, thisIsRegExp ? this : RegExpPrototype, RegExpWrapper); | |
}; | |
var proxy = function (key) { | |
key in RegExpWrapper || defineProperty(RegExpWrapper, key, { | |
configurable: true, | |
get: function () { return NativeRegExp[key]; }, | |
set: function (it) { NativeRegExp[key] = it; } | |
}); | |
}; | |
var keys = getOwnPropertyNames(NativeRegExp); | |
var index = 0; | |
while (keys.length > index) proxy(keys[index++]); | |
RegExpPrototype.constructor = RegExpWrapper; | |
RegExpWrapper.prototype = RegExpPrototype; | |
redefine(global, 'RegExp', RegExpWrapper); | |
} | |
// https://tc39.github.io/ecma262/#sec-get-regexp-@@species | |
setSpecies('RegExp'); | |
/***/ }), | |
/* 113 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var isArray = __webpack_require__(106); | |
var nativeReverse = [].reverse; | |
var test = [1, 2]; | |
// `Array.prototype.reverse` method | |
// https://tc39.github.io/ecma262/#sec-array.prototype.reverse | |
// fix for Safari 12.0 bug | |
// https://bugs.webkit.org/show_bug.cgi?id=188794 | |
$({ target: 'Array', proto: true, forced: String(test) === String(test.reverse()) }, { | |
reverse: function reverse() { | |
if (isArray(this)) this.length = this.length; | |
return nativeReverse.call(this); | |
} | |
}); | |
/***/ }), | |
/* 114 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireDefault = __webpack_require__(0); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _nodesPool = _interopRequireDefault(__webpack_require__(428)); | |
/** | |
* Base renderer class, abstract logic for specialized renderers. | |
* | |
* @class BaseRenderer | |
*/ | |
var BaseRenderer = | |
/*#__PURE__*/ | |
function () { | |
function BaseRenderer(nodeType, rootNode) { | |
(0, _classCallCheck2.default)(this, BaseRenderer); | |
/** | |
* Factory for newly created DOM elements. | |
* | |
* NodePool should be used for each renderer. For the first stage of the refactoring | |
* process, only some of the renderers are implemented a new approach. | |
* | |
* @type {NodesPool|null} | |
*/ | |
this.nodesPool = typeof nodeType === 'string' ? new _nodesPool.default(nodeType) : null; | |
/** | |
* Node type which the renderer will manage while building the table (eg. 'TD', 'TR', 'TH'). | |
* | |
* @type {String} | |
*/ | |
this.nodeType = nodeType; | |
/** | |
* The root node to which newly created elements will be inserted. | |
* | |
* @type {HTMLElement} | |
*/ | |
this.rootNode = rootNode; | |
/** | |
* The instance of the Table class, a wrapper for all renderers and holder for properties describe table state. | |
* | |
* @type {TableRenderer} | |
*/ | |
this.table = null; | |
/** | |
* Counter of nodes already added. | |
* | |
* @type {Number} | |
*/ | |
this.renderedNodes = 0; | |
} | |
/** | |
* Sets the table renderer instance to the current renderer. | |
* | |
* @param {TableRenderer} table The TableRenderer instance. | |
*/ | |
(0, _createClass2.default)(BaseRenderer, [{ | |
key: "setTable", | |
value: function setTable(table) { | |
if (this.nodesPool) { | |
this.nodesPool.setRootDocument(table.rootDocument); | |
} | |
this.table = table; | |
} | |
/** | |
* Adjusts the number of rendered nodes. | |
*/ | |
}, { | |
key: "adjust", | |
value: function adjust() {} | |
/** | |
* Renders the contents to the elements. | |
*/ | |
}, { | |
key: "render", | |
value: function render() {} | |
}]); | |
return BaseRenderer; | |
}(); | |
exports.default = BaseRenderer; | |
/***/ }), | |
/* 115 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var setPrototypeOf = __webpack_require__(215); | |
function isNativeReflectConstruct() { | |
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | |
if (Reflect.construct.sham) return false; | |
if (typeof Proxy === "function") return true; | |
try { | |
Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
function _construct(Parent, args, Class) { | |
if (isNativeReflectConstruct()) { | |
module.exports = _construct = Reflect.construct; | |
} else { | |
module.exports = _construct = function _construct(Parent, args, Class) { | |
var a = [null]; | |
a.push.apply(a, args); | |
var Constructor = Function.bind.apply(Parent, a); | |
var instance = new Constructor(); | |
if (Class) setPrototypeOf(instance, Class.prototype); | |
return instance; | |
}; | |
} | |
return _construct.apply(null, arguments); | |
} | |
module.exports = _construct; | |
/***/ }), | |
/* 116 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireWildcard = __webpack_require__(10); | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(17); | |
__webpack_require__(27); | |
__webpack_require__(15); | |
__webpack_require__(31); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(6)); | |
var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(30)); | |
var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(5)); | |
var _get2 = _interopRequireDefault(__webpack_require__(16)); | |
var _inherits2 = _interopRequireDefault(__webpack_require__(7)); | |
var _element = __webpack_require__(8); | |
var _number = __webpack_require__(19); | |
var _autoResize = _interopRequireDefault(__webpack_require__(467)); | |
var _browser = __webpack_require__(76); | |
var _baseEditor = _interopRequireWildcard(__webpack_require__(110)); | |
var _eventManager = _interopRequireDefault(__webpack_require__(25)); | |
var _unicode = __webpack_require__(58); | |
var _event = __webpack_require__(32); | |
var EDITOR_VISIBLE_CLASS_NAME = 'ht_editor_visible'; | |
var EDITOR_HIDDEN_CLASS_NAME = 'ht_editor_hidden'; | |
/** | |
* @private | |
* @editor TextEditor | |
* @class TextEditor | |
* @dependencies autoResize | |
*/ | |
var TextEditor = | |
/*#__PURE__*/ | |
function (_BaseEditor) { | |
(0, _inherits2.default)(TextEditor, _BaseEditor); | |
/** | |
* @param {Handsontable} instance | |
*/ | |
function TextEditor(instance) { | |
var _this; | |
(0, _classCallCheck2.default)(this, TextEditor); | |
_this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(TextEditor).call(this, instance)); | |
/** | |
* Instance of {@link EventManager}. | |
* | |
* @private | |
* @type {EventManager} | |
*/ | |
_this.eventManager = new _eventManager.default((0, _assertThisInitialized2.default)(_this)); | |
/** | |
* Autoresize instance. Automagically resizes editor after changes. | |
* | |
* @private | |
* @type {autoResize} | |
*/ | |
_this.autoResize = (0, _autoResize.default)(); | |
/** | |
* An TEXTAREA element. | |
* | |
* @private | |
* @type {HTMLTextAreaElement} | |
*/ | |
_this.TEXTAREA = void 0; | |
/** | |
* Style declaration object of the TEXTAREA element. | |
* | |
* @private | |
* @type {CSSStyleDeclaration} | |
*/ | |
_this.textareaStyle = void 0; | |
/** | |
* Parent element of the TEXTAREA. | |
* | |
* @private | |
* @type {HTMLDivElement} | |
*/ | |
_this.TEXTAREA_PARENT = void 0; | |
/** | |
* Style declaration object of the TEXTAREA_PARENT element. | |
* | |
* @private | |
* @type {CSSStyleDeclaration} | |
*/ | |
_this.textareaParentStyle = void 0; | |
/** | |
* z-index class style for the editor. | |
* | |
* @private | |
* @type {string} | |
*/ | |
_this.layerClass = void 0; | |
_this.createElements(); | |
_this.bindEvents(); | |
_this.hot.addHookOnce('afterDestroy', function () { | |
return _this.destroy(); | |
}); | |
return _this; | |
} | |
/** | |
* Gets current value from editable element. | |
* | |
* @returns {Number} | |
*/ | |
(0, _createClass2.default)(TextEditor, [{ | |
key: "getValue", | |
value: function getValue() { | |
return this.TEXTAREA.value; | |
} | |
/** | |
* Sets new value into editable element. | |
* | |
* @param {*} newValue | |
*/ | |
}, { | |
key: "setValue", | |
value: function setValue(newValue) { | |
this.TEXTAREA.value = newValue; | |
} | |
/** | |
* Opens the editor and adjust its size. | |
*/ | |
}, { | |
key: "open", | |
value: function open() { | |
var _this2 = this; | |
this.refreshDimensions(); // need it instantly, to prevent https://github.com/handsontable/handsontable/issues/348 | |
this.showEditableElement(); | |
this.addHook('beforeKeyDown', function (event) { | |
return _this2.onBeforeKeyDown(event); | |
}); | |
} | |
/** | |
* Closes the editor. | |
*/ | |
}, { | |
key: "close", | |
value: function close() { | |
this.autoResize.unObserve(); | |
if (this.hot.rootDocument.activeElement === this.TEXTAREA) { | |
this.hot.listen(); // don't refocus the table if user focused some cell outside of HT on purpose | |
} | |
this.hideEditableElement(); | |
this.removeHooksByKey('beforeKeyDown'); | |
} | |
/** | |
* Prepares editor's meta data. | |
* | |
* @param {Number} row | |
* @param {Number} col | |
* @param {Number|String} prop | |
* @param {HTMLTableCellElement} td | |
* @param {*} originalValue | |
* @param {Object} cellProperties | |
*/ | |
}, { | |
key: "prepare", | |
value: function prepare(row, col, prop, td, originalValue, cellProperties) { | |
var _this3 = this; | |
var previousState = this.state; | |
(0, _get2.default)((0, _getPrototypeOf2.default)(TextEditor.prototype), "prepare", this).call(this, row, col, prop, td, originalValue, cellProperties); | |
if (!cellProperties.readOnly) { | |
this.refreshDimensions(true); | |
var allowInvalid = cellProperties.allowInvalid, | |
fragmentSelection = cellProperties.fragmentSelection; | |
if (allowInvalid) { | |
this.TEXTAREA.value = ''; // Remove an empty space from texarea (added by copyPaste plugin to make copy/paste functionality work with IME) | |
} | |
if (previousState !== _baseEditor.EditorState.FINISHED) { | |
this.hideEditableElement(); | |
} // @TODO: The fragmentSelection functionality is conflicted with IME. For this feature refocus has to | |
// be disabled (to make IME working). | |
var restoreFocus = !fragmentSelection; | |
if (restoreFocus && !(0, _browser.isMobileBrowser)()) { | |
this.hot._registerImmediate(function () { | |
return _this3.focus(true); | |
}); | |
} | |
} | |
} | |
/** | |
* Begins editing on a highlighted cell and hides fillHandle corner if was present. | |
* | |
* @param {*} newInitialValue | |
* @param {*} event | |
*/ | |
}, { | |
key: "beginEditing", | |
value: function beginEditing(newInitialValue, event) { | |
if (this.state !== _baseEditor.EditorState.VIRGIN) { | |
return; | |
} | |
this.TEXTAREA.value = ''; // Remove an empty space from texarea (added by copyPaste plugin to make copy/paste functionality work with IME). | |
(0, _get2.default)((0, _getPrototypeOf2.default)(TextEditor.prototype), "beginEditing", this).call(this, newInitialValue, event); | |
} | |
/** | |
* Sets focus state on the select element. | |
* | |
* @param {Boolean} [safeFocus=false] If `true` select element only when is handsontableInput. Otherwise sets focus on this element. | |
* If focus is calling without param textarea need be select and set caret position. | |
*/ | |
}, { | |
key: "focus", | |
value: function focus() { | |
var safeFocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; | |
// For IME editor textarea element must be focused using ".select" method. Using ".focus" browser automatically scroll into | |
// the focused element which is undesire effect. | |
if (safeFocus) { | |
(0, _element.selectElementIfAllowed)(this.TEXTAREA); | |
} else { | |
this.TEXTAREA.select(); | |
(0, _element.setCaretPosition)(this.TEXTAREA, this.TEXTAREA.value.length); | |
} | |
} | |
/** | |
* Creates an editor's elements and adds necessary CSS classnames. | |
*/ | |
}, { | |
key: "createElements", | |
value: function createElements() { | |
var rootDocument = this.hot.rootDocument; | |
this.TEXTAREA = rootDocument.createElement('TEXTAREA'); | |
this.TEXTAREA.tabIndex = -1; | |
(0, _element.addClass)(this.TEXTAREA, 'handsontableInput'); | |
this.textareaStyle = this.TEXTAREA.style; | |
this.textareaStyle.width = 0; | |
this.textareaStyle.height = 0; | |
this.textareaStyle.overflowY = 'visible'; | |
this.TEXTAREA_PARENT = rootDocument.createElement('DIV'); | |
(0, _element.addClass)(this.TEXTAREA_PARENT, 'handsontableInputHolder'); | |
if ((0, _element.hasClass)(this.TEXTAREA_PARENT, this.layerClass)) { | |
(0, _element.removeClass)(this.TEXTAREA_PARENT, this.layerClass); | |
} | |
(0, _element.addClass)(this.TEXTAREA_PARENT, EDITOR_HIDDEN_CLASS_NAME); | |
this.textareaParentStyle = this.TEXTAREA_PARENT.style; | |
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); | |
this.hot.rootElement.appendChild(this.TEXTAREA_PARENT); | |
} | |
/** | |
* Moves an editable element out of the viewport, but element must be able to hold focus for IME support. | |
* | |
* @private | |
*/ | |
}, { | |
key: "hideEditableElement", | |
value: function hideEditableElement() { | |
if ((0, _browser.isIE)() || (0, _browser.isEdge)()) { | |
this.textareaStyle.textIndent = '-99999px'; | |
} | |
this.textareaStyle.overflowY = 'visible'; | |
this.textareaParentStyle.opacity = '0'; | |
this.textareaParentStyle.height = '1px'; | |
if ((0, _element.hasClass)(this.TEXTAREA_PARENT, this.layerClass)) { | |
(0, _element.removeClass)(this.TEXTAREA_PARENT, this.layerClass); | |
} | |
(0, _element.addClass)(this.TEXTAREA_PARENT, EDITOR_HIDDEN_CLASS_NAME); | |
} | |
/** | |
* Resets an editable element position. | |
* | |
* @private | |
*/ | |
}, { | |
key: "showEditableElement", | |
value: function showEditableElement() { | |
this.textareaParentStyle.height = ''; | |
this.textareaParentStyle.overflow = ''; | |
this.textareaParentStyle.position = ''; | |
this.textareaParentStyle.right = 'auto'; | |
this.textareaParentStyle.opacity = '1'; | |
this.textareaStyle.textIndent = ''; | |
this.textareaStyle.overflowY = 'hidden'; | |
var childNodes = this.TEXTAREA_PARENT.childNodes; | |
var hasClassHandsontableEditor = false; | |
(0, _number.rangeEach)(childNodes.length - 1, function (index) { | |
var childNode = childNodes[index]; | |
if ((0, _element.hasClass)(childNode, 'handsontableEditor')) { | |
hasClassHandsontableEditor = true; | |
return false; | |
} | |
}); | |
if ((0, _element.hasClass)(this.TEXTAREA_PARENT, EDITOR_HIDDEN_CLASS_NAME)) { | |
(0, _element.removeClass)(this.TEXTAREA_PARENT, EDITOR_HIDDEN_CLASS_NAME); | |
} | |
if (hasClassHandsontableEditor) { | |
this.layerClass = EDITOR_VISIBLE_CLASS_NAME; | |
(0, _element.addClass)(this.TEXTAREA_PARENT, this.layerClass); | |
} else { | |
this.layerClass = this.getEditedCellsLayerClass(); | |
(0, _element.addClass)(this.TEXTAREA_PARENT, this.layerClass); | |
} | |
} | |
/** | |
* Refreshes editor's value using source data. | |
* | |
* @private | |
*/ | |
}, { | |
key: "refreshValue", | |
value: function refreshValue() { | |
var physicalRow = this.hot.toPhysicalRow(this.row); | |
var sourceData = this.hot.getSourceDataAtCell(physicalRow, this.col); | |
this.originalValue = sourceData; | |
this.setValue(sourceData); | |
this.refreshDimensions(); | |
} | |
/** | |
* Refreshes editor's size and position. | |
* | |
* @private | |
* @param {Boolean} force | |
*/ | |
}, { | |
key: "refreshDimensions", | |
value: function refreshDimensions() { | |
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; | |
if (this.state !== _baseEditor.EditorState.EDITING && !force) { | |
return; | |
} | |
this.TD = this.getEditedCell(); // TD is outside of the viewport. | |
if (!this.TD) { | |
if (!force) { | |
this.close(); // TODO shouldn't it be this.finishEditing() ? | |
} | |
return; | |
} | |
var _this$hot$view$wt = this.hot.view.wt, | |
wtOverlays = _this$hot$view$wt.wtOverlays, | |
wtViewport = _this$hot$view$wt.wtViewport; | |
var currentOffset = (0, _element.offset)(this.TD); | |
var containerOffset = (0, _element.offset)(this.hot.rootElement); | |
var scrollableContainerTop = wtOverlays.topOverlay.holder; | |
var scrollableContainerLeft = wtOverlays.leftOverlay.holder; | |
var totalRowsCount = this.hot.countRows(); | |
var containerScrollTop = scrollableContainerTop !== this.hot.rootWindow ? scrollableContainerTop.scrollTop : 0; | |
var containerScrollLeft = scrollableContainerLeft !== this.hot.rootWindow ? scrollableContainerLeft.scrollLeft : 0; | |
var editorSection = this.checkEditorSection(); | |
var scrollTop = ['', 'left'].includes(editorSection) ? containerScrollTop : 0; | |
var scrollLeft = ['', 'top', 'bottom'].includes(editorSection) ? containerScrollLeft : 0; // If colHeaders is disabled, cells in the first row have border-top | |
var editTopModifier = currentOffset.top === containerOffset.top ? 0 : 1; | |
var settings = this.hot.getSettings(); | |
var colHeadersCount = this.hot.hasColHeaders(); | |
var backgroundColor = this.TD.style.backgroundColor; | |
var editTop = currentOffset.top - containerOffset.top - editTopModifier - scrollTop; | |
var editLeft = currentOffset.left - containerOffset.left - 1 - scrollLeft; | |
var cssTransformOffset; // TODO: Refactor this to the new instance.getCell method (from #ply-59), after 0.12.1 is released | |
switch (editorSection) { | |
case 'top': | |
cssTransformOffset = (0, _element.getCssTransform)(wtOverlays.topOverlay.clone.wtTable.holder.parentNode); | |
break; | |
case 'left': | |
cssTransformOffset = (0, _element.getCssTransform)(wtOverlays.leftOverlay.clone.wtTable.holder.parentNode); | |
break; | |
case 'top-left-corner': | |
cssTransformOffset = (0, _element.getCssTransform)(wtOverlays.topLeftCornerOverlay.clone.wtTable.holder.parentNode); | |
break; | |
case 'bottom-left-corner': | |
cssTransformOffset = (0, _element.getCssTransform)(wtOverlays.bottomLeftCornerOverlay.clone.wtTable.holder.parentNode); | |
break; | |
case 'bottom': | |
cssTransformOffset = (0, _element.getCssTransform)(wtOverlays.bottomOverlay.clone.wtTable.holder.parentNode); | |
break; | |
default: | |
break; | |
} | |
if (colHeadersCount && this.hot.getSelectedLast()[0] === 0 || settings.fixedRowsBottom && this.hot.getSelectedLast()[0] === totalRowsCount - settings.fixedRowsBottom) { | |
editTop += 1; | |
} | |
if (this.hot.getSelectedLast()[1] === 0) { | |
editLeft += 1; | |
} | |
if (cssTransformOffset && cssTransformOffset !== -1) { | |
this.textareaParentStyle[cssTransformOffset[0]] = cssTransformOffset[1]; | |
} else { | |
(0, _element.resetCssTransform)(this.TEXTAREA_PARENT); | |
} | |
this.textareaParentStyle.top = "".concat(editTop, "px"); | |
this.textareaParentStyle.left = "".concat(editLeft, "px"); | |
this.showEditableElement(); | |
var firstRowOffset = wtViewport.rowsRenderCalculator.startPosition; | |
var firstColumnOffset = wtViewport.columnsRenderCalculator.startPosition; | |
var horizontalScrollPosition = wtOverlays.leftOverlay.getScrollPosition(); | |
var verticalScrollPosition = wtOverlays.topOverlay.getScrollPosition(); | |
var scrollbarWidth = (0, _element.getScrollbarWidth)(this.hot.rootDocument); | |
var cellTopOffset = this.TD.offsetTop + firstRowOffset - verticalScrollPosition; | |
var cellLeftOffset = this.TD.offsetLeft + firstColumnOffset - horizontalScrollPosition; | |
var width = (0, _element.innerWidth)(this.TD) - 8; | |
var actualVerticalScrollbarWidth = (0, _element.hasVerticalScrollbar)(scrollableContainerTop) ? scrollbarWidth : 0; | |
var actualHorizontalScrollbarWidth = (0, _element.hasHorizontalScrollbar)(scrollableContainerLeft) ? scrollbarWidth : 0; | |
var maxWidth = this.hot.view.maximumVisibleElementWidth(cellLeftOffset) - 9 - actualVerticalScrollbarWidth; | |
var height = this.TD.scrollHeight + 1; | |
var maxHeight = Math.max(this.hot.view.maximumVisibleElementHeight(cellTopOffset) - actualHorizontalScrollbarWidth, 23); | |
var cellComputedStyle = (0, _element.getComputedStyle)(this.TD, this.hot.rootWindow); | |
this.TEXTAREA.style.fontSize = cellComputedStyle.fontSize; | |
this.TEXTAREA.style.fontFamily = cellComputedStyle.fontFamily; | |
this.TEXTAREA.style.backgroundColor = backgroundColor; | |
this.autoResize.init(this.TEXTAREA, { | |
minHeight: Math.min(height, maxHeight), | |
maxHeight: maxHeight, | |
// TEXTAREA should never be higher than visible part of the viewport (should not cover the scrollbar) | |
minWidth: Math.min(width, maxWidth), | |
maxWidth: maxWidth // TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) | |
}, true); | |
} | |
/** | |
* Binds events and hooks. | |
* | |
* @private | |
*/ | |
}, { | |
key: "bindEvents", | |
value: function bindEvents() { | |
var _this4 = this; | |
this.eventManager.addEventListener(this.TEXTAREA, 'cut', function (event) { | |
return (0, _event.stopPropagation)(event); | |
}); | |
this.eventManager.addEventListener(this.TEXTAREA, 'paste', function (event) { | |
return (0, _event.stopPropagation)(event); | |
}); | |
this.addHook('afterScrollHorizontally', function () { | |
return _this4.refreshDimensions(); | |
}); | |
this.addHook('afterScrollVertically', function () { | |
return _this4.refreshDimensions(); | |
}); | |
this.addHook('afterColumnResize', function () { | |
_this4.refreshDimensions(); | |
_this4.focus(); | |
}); | |
this.addHook('afterRowResize', function () { | |
_this4.refreshDimensions(); | |
_this4.focus(); | |
}); | |
} | |
/** | |
* Ugly hack for autocompleteEditor. | |
* | |
* @private | |
*/ | |
}, { | |
key: "allowKeyEventPropagation", | |
value: function allowKeyEventPropagation() {} | |
/** | |
* Destroys the internal event manager and clears attached hooks. | |
* | |
* @private | |
*/ | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
this.eventManager.destroy(); | |
this.clearHooks(); | |
} | |
/** | |
* onBeforeKeyDown callback. | |
* | |
* @param {Event} event | |
*/ | |
}, { | |
key: "onBeforeKeyDown", | |
value: function onBeforeKeyDown(event) { | |
// catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) | |
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; // Process only events that have been fired in the editor | |
if (event.target !== this.TEXTAREA || (0, _event.isImmediatePropagationStopped)(event)) { | |
return; | |
} | |
switch (event.keyCode) { | |
case _unicode.KEY_CODES.ARROW_RIGHT: | |
if (this.isInFullEditMode()) { | |
if (!this.isWaiting() && !this.allowKeyEventPropagation(event.keyCode)) { | |
(0, _event.stopImmediatePropagation)(event); | |
} | |
} | |
break; | |
case _unicode.KEY_CODES.ARROW_LEFT: | |
if (this.isInFullEditMode()) { | |
if (!this.isWaiting() && !this.allowKeyEventPropagation(event.keyCode)) { | |
(0, _event.stopImmediatePropagation)(event); | |
} | |
} | |
break; | |
case _unicode.KEY_CODES.ARROW_UP: | |
case _unicode.KEY_CODES.ARROW_DOWN: | |
if (this.isInFullEditMode()) { | |
if (!this.isWaiting() && !this.allowKeyEventPropagation(event.keyCode)) { | |
(0, _event.stopImmediatePropagation)(event); | |
} | |
} | |
break; | |
case _unicode.KEY_CODES.ENTER: | |
{ | |
var isMultipleSelection = this.hot.selection.isMultiple(); | |
if (ctrlDown && !isMultipleSelection || event.altKey) { | |
// if ctrl+enter or alt+enter, add new line | |
if (this.isOpened()) { | |
var caretPosition = (0, _element.getCaretPosition)(this.TEXTAREA); | |
var value = this.getValue(); | |
var newValue = "".concat(value.slice(0, caretPosition), "\n").concat(value.slice(caretPosition)); | |
this.setValue(newValue); | |
(0, _element.setCaretPosition)(this.TEXTAREA, caretPosition + 1); | |
} else { | |
this.beginEditing("".concat(this.originalValue, "\n")); | |
} | |
(0, _event.stopImmediatePropagation)(event); | |
} | |
event.preventDefault(); // don't add newline to field | |
break; | |
} | |
case _unicode.KEY_CODES.BACKSPACE: | |
case _unicode.KEY_CODES.DELETE: | |
case _unicode.KEY_CODES.HOME: | |
case _unicode.KEY_CODES.END: | |
(0, _event.stopImmediatePropagation)(event); // backspace, delete, home, end should only work locally when cell is edited (not in table context) | |
break; | |
default: | |
break; | |
} | |
if ([_unicode.KEY_CODES.ARROW_UP, _unicode.KEY_CODES.ARROW_RIGHT, _unicode.KEY_CODES.ARROW_DOWN, _unicode.KEY_CODES.ARROW_LEFT].indexOf(event.keyCode) === -1) { | |
this.autoResize.resize(String.fromCharCode(event.keyCode)); | |
} | |
} | |
}]); | |
return TextEditor; | |
}(_baseEditor.default); | |
var _default = TextEditor; | |
exports.default = _default; | |
/***/ }), | |
/* 117 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var toLength = __webpack_require__(52); | |
var notARegExp = __webpack_require__(166); | |
var requireObjectCoercible = __webpack_require__(54); | |
var correctIsRegExpLogic = __webpack_require__(167); | |
var nativeStartsWith = ''.startsWith; | |
var min = Math.min; | |
// `String.prototype.startsWith` method | |
// https://tc39.github.io/ecma262/#sec-string.prototype.startswith | |
$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('startsWith') }, { | |
startsWith: function startsWith(searchString /* , position = 0 */) { | |
var that = String(requireObjectCoercible(this)); | |
notARegExp(searchString); | |
var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length)); | |
var search = String(searchString); | |
return nativeStartsWith | |
? nativeStartsWith.call(that, search, index) | |
: that.slice(index, index + search.length) === search; | |
} | |
}); | |
/***/ }), | |
/* 118 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var $ = __webpack_require__(21); | |
var global = __webpack_require__(38); | |
var IS_PURE = __webpack_require__(125); | |
var DESCRIPTORS = __webpack_require__(51); | |
var NATIVE_SYMBOL = __webpack_require__(198); | |
var fails = __webpack_require__(28); | |
var has = __webpack_require__(55); | |
var isArray = __webpack_require__(106); | |
var isObject = __webpack_require__(44); | |
var anObject = __webpack_require__(47); | |
var toObject = __webpack_require__(62); | |
var toIndexedObject = __webpack_require__(67); | |
var toPrimitive = __webpack_require__(98); | |
var createPropertyDescriptor = __webpack_require__(97); | |
var nativeObjectCreate = __webpack_require__(103); | |
var objectKeys = __webpack_require__(131); | |
var getOwnPropertyNamesModule = __webpack_require__(101); | |
var getOwnPropertyNamesExternal = __webpack_require__(197); | |
var getOwnPropertySymbolsModule = __webpack_require__(151); | |
var getOwnPropertyDescriptorModule = __webpack_require__(92); | |
var definePropertyModule = __webpack_require__(56); | |
var propertyIsEnumerableModule = __webpack_require__(146); | |
var createNonEnumerableProperty = __webpack_require__(68); | |
var redefine = __webpack_require__(73); | |
var shared = __webpack_require__(99); | |
var sharedKey = __webpack_require__(126); | |
var hiddenKeys = __webpack_require__(100); | |
var uid = __webpack_require__(127); | |
var wellKnownSymbol = __webpack_require__(37); | |
var wrappedWellKnownSymbolModule = __webpack_require__(374); | |
var defineWellKnownSymbol = __webpack_require__(375); | |
var setToStringTag = __webpack_require__(132); | |
var InternalStateModule = __webpack_require__(88); | |
var $forEach = __webpack_require__(89).forEach; | |
var HIDDEN = sharedKey('hidden'); | |
var SYMBOL = 'Symbol'; | |
var PROTOTYPE = 'prototype'; | |
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); | |
var setInternalState = InternalStateModule.set; | |
var getInternalState = InternalStateModule.getterFor(SYMBOL); | |
var ObjectPrototype = Object[PROTOTYPE]; | |
var $Symbol = global.Symbol; | |
var JSON = global.JSON; | |
var nativeJSONStringify = JSON && JSON.stringify; | |
var nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f; | |
var nativeDefineProperty = definePropertyModule.f; | |
var nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f; | |
var nativePropertyIsEnumerable = propertyIsEnumerableModule.f; | |
var AllSymbols = shared('symbols'); | |
var ObjectPrototypeSymbols = shared('op-symbols'); | |
var StringToSymbolRegistry = shared('string-to-symbol-registry'); | |
var SymbolToStringRegistry = shared('symbol-to-string-registry'); | |
var WellKnownSymbolsStore = shared('wks'); | |
var QObject = global.QObject; | |
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 | |
var USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; | |
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 | |
var setSymbolDescriptor = DESCRIPTORS && fails(function () { | |
return nativeObjectCreate(nativeDefineProperty({}, 'a', { | |
get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; } | |
})).a != 7; | |
}) ? function (O, P, Attributes) { | |
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P); | |
if (ObjectPrototypeDescriptor) delete ObjectPrototype[P]; | |
nativeDefineProperty(O, P, Attributes); | |
if (ObjectPrototypeDescriptor && O !== ObjectPrototype) { | |
nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor); | |
} | |
} : nativeDefineProperty; | |
var wrap = function (tag, description) { | |
var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]); | |
setInternalState(symbol, { | |
type: SYMBOL, | |
tag: tag, | |
description: description | |
}); | |
if (!DESCRIPTORS) symbol.description = description; | |
return symbol; | |
}; | |
var isSymbol = NATIVE_SYMBOL && typeof $Symbol.iterator == 'symbol' ? function (it) { | |
return typeof it == 'symbol'; | |
} : function (it) { | |
return Object(it) instanceof $Symbol; | |
}; | |
var $defineProperty = function defineProperty(O, P, Attributes) { | |
if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes); | |
anObject(O); | |
var key = toPrimitive(P, true); | |
anObject(Attributes); | |
if (has(AllSymbols, key)) { | |
if (!Attributes.enumerable) { | |
if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {})); | |
O[HIDDEN][key] = true; | |
} else { | |
if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; | |
Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) }); | |
} return setSymbolDescriptor(O, key, Attributes); | |
} return nativeDefineProperty(O, key, Attributes); | |
}; | |
var $defineProperties = function defineProperties(O, Properties) { | |
anObject(O); | |
var properties = toIndexedObject(Properties); | |
var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties)); | |
$forEach(keys, function (key) { | |
if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); | |
}); | |
return O; | |
}; | |
var $create = function create(O, Properties) { | |
return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties); | |
}; | |
var $propertyIsEnumerable = function propertyIsEnumerable(V) { | |
var P = toPrimitive(V, true); | |
var enumerable = nativePropertyIsEnumerable.call(this, P); | |
if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false; | |
return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; | |
}; | |
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { | |
var it = toIndexedObject(O); | |
var key = toPrimitive(P, true); | |
if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return; | |
var descriptor = nativeGetOwnPropertyDescriptor(it, key); | |
if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) { | |
descriptor.enumerable = true; | |
} | |
return descriptor; | |
}; | |
var $getOwnPropertyNames = function getOwnPropertyNames(O) { | |
var names = nativeGetOwnPropertyNames(toIndexedObject(O)); | |
var result = []; | |
$forEach(names, function (key) { | |
if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key); | |
}); | |
return result; | |
}; | |
var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { | |
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype; | |
var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O)); | |
var result = []; | |
$forEach(names, function (key) { | |
if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) { | |
result.push(AllSymbols[key]); | |
} | |
}); | |
return result; | |
}; | |
// `Symbol` constructor | |
// https://tc39.github.io/ecma262/#sec-symbol-constructor | |
if (!NATIVE_SYMBOL) { | |
$Symbol = function Symbol() { | |
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor'); | |
var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]); | |
var tag = uid(description); | |
var setter = function (value) { | |
if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value); | |
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; | |
setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value)); | |
}; | |
if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter }); | |
return wrap(tag, description); | |
}; | |
redefine($Symbol[PROTOTYPE], 'toString', function toString() { | |
return getInternalState(this).tag; | |
}); | |
propertyIsEnumerableModule.f = $propertyIsEnumerable; | |
definePropertyModule.f = $defineProperty; | |
getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor; | |
getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames; | |
getOwnPropertySymbolsModule.f = $getOwnPropertySymbols; | |
if (DESCRIPTORS) { | |
// https://github.com/tc39/proposal-Symbol-description | |
nativeDefineProperty($Symbol[PROTOTYPE], 'description', { | |
configurable: true, | |
get: function description() { | |
return getInternalState(this).description; | |
} | |
}); | |
if (!IS_PURE) { | |
redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true }); | |
} | |
} | |
wrappedWellKnownSymbolModule.f = function (name) { | |
return wrap(wellKnownSymbol(name), name); | |
}; | |
} | |
$({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, { | |
Symbol: $Symbol | |
}); | |
$forEach(objectKeys(WellKnownSymbolsStore), function (name) { | |
defineWellKnownSymbol(name); | |
}); | |
$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, { | |
// `Symbol.for` method | |
// https://tc39.github.io/ecma262/#sec-symbol.for | |
'for': function (key) { | |
var string = String(key); | |
if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; | |
var symbol = $Symbol(string); | |
StringToSymbolRegistry[string] = symbol; | |
SymbolToStringRegistry[symbol] = string; | |
return symbol; | |
}, | |
// `Symbol.keyFor` method | |
// https://tc39.github.io/ecma262/#sec-symbol.keyfor | |
keyFor: function keyFor(sym) { | |
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol'); | |
if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; | |
}, | |
useSetter: function () { USE_SETTER = true; }, | |
useSimple: function () { USE_SETTER = false; } | |
}); | |
$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, { | |
// `Object.create` method | |
// https://tc39.github.io/ecma262/#sec-object.create | |
create: $create, | |
// `Object.defineProperty` method | |
// https://tc39.github.io/ecma262/#sec-object.defineproperty | |
defineProperty: $defineProperty, | |
// `Object.defineProperties` method | |
// https://tc39.github.io/ecma262/#sec-object.defineproperties | |
defineProperties: $defineProperties, | |
// `Object.getOwnPropertyDescriptor` method | |
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors | |
getOwnPropertyDescriptor: $getOwnPropertyDescriptor | |
}); | |
$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, { | |
// `Object.getOwnPropertyNames` method | |
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames | |
getOwnPropertyNames: $getOwnPropertyNames, | |
// `Object.getOwnPropertySymbols` method | |
// https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols | |
getOwnPropertySymbols: $getOwnPropertySymbols | |
}); | |
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives | |
// https://bugs.chromium.org/p/v8/issues/detail?id=3443 | |
$({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, { | |
getOwnPropertySymbols: function getOwnPropertySymbols(it) { | |
return getOwnPropertySymbolsModule.f(toObject(it)); | |
} | |
}); | |
// `JSON.stringify` method behavior with symbols | |
// https://tc39.github.io/ecma262/#sec-json.stringify | |
JSON && $({ target: 'JSON', stat: true, forced: !NATIVE_SYMBOL || fails(function () { | |
var symbol = $Symbol(); | |
// MS Edge converts symbol values to JSON as {} | |
return nativeJSONStringify([symbol]) != '[null]' | |
// WebKit converts symbol values to JSON as null | |
|| nativeJSONStringify({ a: symbol }) != '{}' | |
// V8 throws on boxed symbols | |
|| nativeJSONStringify(Object(symbol)) != '{}'; | |
}) }, { | |
stringify: function stringify(it) { | |
var args = [it]; | |
var index = 1; | |
var replacer, $replacer; | |
while (arguments.length > index) args.push(arguments[index++]); | |
$replacer = replacer = args[1]; | |
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined | |
if (!isArray(replacer)) replacer = function (key, value) { | |
if (typeof $replacer == 'function') value = $replacer.call(this, key, value); | |
if (!isSymbol(value)) return value; | |
}; | |
args[1] = replacer; | |
return nativeJSONStringify.apply(JSON, args); | |
} | |
}); | |
// `Symbol.prototype[@@toPrimitive]` method | |
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive | |
if (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) { | |
createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); | |
} | |
// `Symbol.prototype[@@toStringTag]` property | |
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag | |
setToStringTag($Symbol, SYMBOL); | |
hiddenKeys[HIDDEN] = true; | |
/***/ }), | |
/* 119 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(48); | |
__webpack_require__(15); | |
__webpack_require__(12); | |
__webpack_require__(71); | |
__webpack_require__(9); | |
__webpack_require__(75); | |
__webpack_require__(11); | |
__webpack_require__(13); | |
exports.__esModule = true; | |
exports.sortComparison = sortComparison; | |
exports.toVisualValue = toVisualValue; | |
exports.createArrayAssertion = createArrayAssertion; | |
exports.toEmptyString = toEmptyString; | |
exports.unifyColumnValues = unifyColumnValues; | |
exports.intersectValues = intersectValues; | |
var _feature = __webpack_require__(81); | |
var _array = __webpack_require__(3); | |
var sortCompare = (0, _feature.getComparisonFunction)(); | |
/** | |
* Comparison function for sorting purposes. | |
* | |
* @param {*} a | |
* @param {*} b | |
* @returns {Number} Returns number from -1 to 1. | |
*/ | |
function sortComparison(a, b) { | |
if (typeof a === 'number' && typeof b === 'number') { | |
return a - b; | |
} | |
return sortCompare(a, b); | |
} | |
/** | |
* Convert raw value into visual value. | |
* | |
* @param {*} value | |
* @param {String} defaultEmptyValue Default value for empty cells. | |
* @returns {*} | |
*/ | |
function toVisualValue(value, defaultEmptyValue) { | |
var visualValue = value; | |
if (visualValue === '') { | |
visualValue = "(".concat(defaultEmptyValue, ")"); | |
} | |
return visualValue; | |
} | |
var SUPPORT_SET_CONSTRUCTOR = new Set([1]).has(1); | |
var SUPPORT_FAST_DEDUPE = SUPPORT_SET_CONSTRUCTOR && typeof Array.from === 'function'; | |
/** | |
* Create an array assertion to compare if an element exists in that array (in a more efficient way than .indexOf). | |
* | |
* @param {Array} initialData Values to compare. | |
* @returns {Function} | |
*/ | |
function createArrayAssertion(initialData) { | |
var dataset = initialData; | |
if (SUPPORT_SET_CONSTRUCTOR) { | |
dataset = new Set(dataset); | |
} | |
return function (value) { | |
var result; | |
if (SUPPORT_SET_CONSTRUCTOR) { | |
result = dataset.has(value); | |
} else { | |
/* eslint-disable no-bitwise */ | |
result = !!~dataset.indexOf(value); | |
} | |
return result; | |
}; | |
} | |
/** | |
* Convert empty-ish values like null and undefined to an empty string. | |
* | |
* @param value Value to check. | |
* @returns {String} | |
*/ | |
function toEmptyString(value) { | |
return value === null || value === void 0 ? '' : value; | |
} | |
/** | |
* Unify column values (replace `null` and `undefined` values into empty string, unique values and sort them). | |
* | |
* @param {Array} values An array of values. | |
* @returns {Array} | |
*/ | |
function unifyColumnValues(values) { | |
var unifiedValues = values; | |
if (SUPPORT_FAST_DEDUPE) { | |
unifiedValues = Array.from(new Set(unifiedValues)); | |
} else { | |
unifiedValues = (0, _array.arrayUnique)(unifiedValues); | |
} | |
unifiedValues = unifiedValues.sort(function (a, b) { | |
if (typeof a === 'number' && typeof b === 'number') { | |
return a - b; | |
} | |
if (a === b) { | |
return 0; | |
} | |
return a > b ? 1 : -1; | |
}); | |
return unifiedValues; | |
} | |
/** | |
* Intersect 'base' values with 'selected' values and return an array of object. | |
* | |
* @param {Array} base An array of base values. | |
* @param {Array} selected An array of selected values. | |
* @param {String} defaultEmptyValue Default value for empty cells. | |
* @param {Function} [callback] A callback function which is invoked for every item in an array. | |
* @returns {Array} | |
*/ | |
function intersectValues(base, selected, defaultEmptyValue, callback) { | |
var result = []; | |
var same = base === selected; | |
var selectedItemsAssertion; | |
if (!same) { | |
selectedItemsAssertion = createArrayAssertion(selected); | |
} | |
(0, _array.arrayEach)(base, function (value) { | |
var checked = false; | |
if (same || selectedItemsAssertion(value)) { | |
checked = true; | |
} | |
var item = { | |
checked: checked, | |
value: value, | |
visualValue: toVisualValue(value, defaultEmptyValue) | |
}; | |
if (callback) { | |
callback(item); | |
} | |
result.push(item); | |
}); | |
return result; | |
} | |
/***/ }), | |
/* 120 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
__webpack_require__(59); | |
exports.__esModule = true; | |
exports.getOperationFunc = getOperationFunc; | |
exports.getOperationName = getOperationName; | |
exports.registerOperation = registerOperation; | |
exports.operations = void 0; | |
var operations = {}; | |
/** | |
* Get operation closure with pre-bound arguments. | |
* | |
* @param {String} id Operator `id`. | |
* @returns {Function} | |
*/ | |
exports.operations = operations; | |
function getOperationFunc(id) { | |
if (!operations[id]) { | |
throw Error("Operation with id \"".concat(id, "\" does not exist.")); | |
} | |
var func = operations[id].func; | |
return function (conditions, value) { | |
return func(conditions, value); | |
}; | |
} | |
/** | |
* Return name of operation which is displayed inside UI component, basing on it's `id`. | |
* | |
* @param {String} id `Id` of operation. | |
*/ | |
function getOperationName(id) { | |
return operations[id].name; | |
} | |
/** | |
* Operator registerer. | |
* | |
* @param {String} id Operation `id`. | |
* @param {String} name Operation name which is displayed inside UI component. | |
* @param {Function} func Operation function. | |
*/ | |
function registerOperation(id, name, func) { | |
operations[id] = { | |
name: name, | |
func: func | |
}; | |
} | |
/***/ }), | |
/* 121 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
var _interopRequireWildcard = __webpack_require__(10); | |
var _interopRequireDefault = __webpack_require__(0); | |
__webpack_require__(117); | |
exports.__esModule = true; | |
exports.default = void 0; | |
var _classCallCheck2 = _interopRequireDefault(__webpack_require__(1)); | |
var _createClass2 = _interopRequireDefault(__webpack_require__(2)); | |
var _object = __webpack_require__(4); | |
var _localHooks = _interopRequireDefault(__webpack_require__(50)); | |
var _eventManager = _interopRequireDefault(__webpack_require__(25)); | |
var _element = __webpack_require__(8); | |
var _array = __webpack_require__(3); | |
var C = _interopRequireWildcard(__webpack_require__(14)); | |
var STATE_BUILT = 'built'; | |
var STATE_BUILDING = 'building'; | |
var EVENTS_TO_REGISTER = ['click', 'input', 'keydown', 'keypress', 'keyup', 'focus', 'blur', 'change']; | |
/** | |
* @class | |
* @private | |
*/ | |
var BaseUI = | |
/*#__PURE__*/ | |
function () { | |
(0, _createClass2.default)(BaseUI, null, [{ | |
key: "DEFAULTS", | |
get: function get() { | |
return (0, _object.clone)({ | |
className: '', | |
value: '', | |
tagName: 'div', | |
children: [], | |
wrapIt: true | |
}); | |
} | |
}]); | |
function BaseUI(hotInstance, options) { | |
(0, _classCallCheck2.default)(this, BaseUI); | |
/** | |
* Instance of Handsontable. | |
* | |
* @type {Core} | |
*/ | |
this.hot = hotInstance; | |
/** | |
* Instance of EventManager. | |
* | |
* @type {EventManager} | |
*/ | |
this.eventManager = new _eventManager.default(this); | |
/** | |
* List of element options. | |
* | |
* @type {Object} | |
*/ | |
this.options = (0, _object.extend)(BaseUI.DEFAULTS, options); | |
/** | |
* Build root DOM element. | |
* | |
* @type {Element} | |
* @private | |
*/ | |
this._element = this.hot.rootDocument.createElement(this.options.wrapIt ? 'div' : this.options.tagName); | |
/** | |
* Flag which determines build state of element. | |
* | |
* @type {Boolean} | |
*/ | |
this.buildState = false; | |
} | |
/** | |
* Set the element value. | |
* | |
* @returns {*} | |
*/ | |
(0, _createClass2.default)(BaseUI, [{ | |
key: "setValue", | |
value: function setValue(value) { | |
this.options.value = value; | |
this.update(); | |
} | |
/** | |
* Get the element value. | |
* | |
* @returns {*} | |
*/ | |
}, { | |
key: "getValue", | |
value: function getValue() { | |
return this.options.value; | |
} | |
/** | |
* Get element as a DOM object. | |
* | |
* @returns {Element} | |
*/ | |
}, { | |
key: "isBuilt", | |
/** | |
* Check if element was built (built whole DOM structure). | |
* | |
* @returns {Boolean} | |
*/ | |
value: function isBuilt() { | |
return this.buildState === STATE_BUILT; | |
} | |
/** | |
* Translate value if it is possible. It's checked if value belongs to namespace of translated phrases. | |
* | |
* @param {*} value Value which will may be translated. | |
* @returns {*} Translated value if translation was possible, original value otherwise. | |
*/ | |
}, { | |
key: "translateIfPossible", | |
value: function translateIfPossible(value) { | |
if (typeof value === 'string' && value.startsWith(C.FILTERS_NAMESPACE)) { | |
return this.hot.getTranslatedPhrase(value); | |
} | |
return value; | |
} | |
/** | |
* Build DOM structure. | |
*/ | |
}, { | |
key: "build", | |
value: function build() { | |
var _this = this; | |
var registerEvent = function registerEvent(element, eventName) { | |
_this.eventManager.addEventListener(element, eventName, function (event) { | |
return _this.runLocalHooks(eventName, event, _this); | |
}); | |
}; | |
if (!this.buildState) { | |
this.buildState = STATE_BUILDING; | |
} | |
if (this.options.className) { | |
(0, _element.addClass)(this._element, this.options.className); | |
} | |
if (this.options.children.length) { | |
(0, _array.arrayEach)(this.options.children, function (element) { | |
return _this._element.appendChild(element.element); | |
}); | |
} else if (this.options.wrapIt) { | |
var element = this.hot.rootDocument.createElement(this.options.tagName); | |
(0, _object.objectEach)(this.options, function (value, key) { | |
if (element[key] !== void 0 && key !== 'className' && key !== 'tagName' && key !== 'children') { | |
element[key] = _this.translateIfPossible(value); | |
} | |
}); | |
this._element.appendChild(element); | |
(0, _array.arrayEach)(EVENTS_TO_REGISTER, function (eventName) { | |
return registerEvent(element, eventName); | |
}); | |
} else { | |
(0, _array.arrayEach)(EVENTS_TO_REGISTER, function (eventName) { | |
return registerEvent(_this._element, eventName); | |
}); | |
} | |
} | |
/** | |
* Update DOM structure. | |
*/ | |
}, { | |
key: "update", | |
value: function update() {} | |
/** | |
* Reset to initial state. | |
*/ | |
}, { | |
key: "reset", | |
value: function reset() { | |
this.options.value = ''; | |
this.update(); | |
} | |
/** | |
* Show element. | |
*/ | |
}, { | |
key: "show", | |
value: function show() { | |
this.element.style.display = ''; | |
} | |
/** | |
* Hide element. | |
*/ | |
}, { | |
key: "hide", | |
value: function hide() { | |
this.element.style.display = 'none'; | |
} | |
/** | |
* Focus element. | |
*/ | |
}, { | |
key: "focus", | |
value: function focus() {} | |
}, { | |
key: "destroy", | |
value: function destroy() { | |
this.eventManager.destroy(); | |
this.eventManager = null; | |
this.hot = null; | |
if (this._element.parentNode) { | |
this._element.parentNode.removeChild(this._element); | |
} | |
this._element = null; | |
} | |
}, { | |
key: "element", | |
get: function get() { | |
if (this.buildState === STATE_BUILDING) { | |
return this._element; | |
} | |
if (this.buildState === STATE_BUILT) { | |
this.update(); | |
return this._element; | |
} | |
this.buildState = STATE_BUILDING; | |
this.build(); | |
this.buildState = STATE_BUILT; | |
return this._element; | |
} | |
}]); | |
return BaseUI; | |
}(); | |
(0, _object.mixin)(BaseUI, _localHooks.default); | |
var _default = BaseUI; | |
exports.default = _default; | |
/***/ }), | |
/* 122 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
(function webpackUniversalModuleDefinition(root, factory) { | |
if(true) | |
module.exports = factory(); | |
else {} | |
})(typeof self !== 'undefined' ? self : this, function() { | |
return /******/ (function(modules) { // webpackBootstrap | |
/******/ // The module cache | |
/******/ var installedModules = {}; | |
/******/ | |
/******/ // The require function | |
/******/ function __webpack_require__(moduleId) { | |
/******/ | |
/******/ // Check if module is in cache | |
/******/ if(installedModules[moduleId]) { | |
/******/ return installedModules[moduleId].exports; | |
/******/ } | |
/******/ // Create a new module (and put it into the cache) | |
/******/ var module = installedModules[moduleId] = { | |
/******/ i: moduleId, | |
/******/ l: false, | |
/******/ exports: {} | |
/******/ }; | |
/******/ | |
/******/ // Execute the module function | |
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); | |
/******/ | |
/******/ // Flag the module as loaded | |
/******/ module.l = true; | |
/******/ | |
/******/ // Return the exports of the module | |
/******/ return module.exports; | |
/******/ } | |
/******/ | |
/******/ | |
/******/ // expose the modules object (__webpack_modules__) | |
/******/ __webpack_require__.m = modules; | |
/******/ | |
/******/ // expose the module cache | |
/******/ __webpack_require__.c = installedModules; | |
/******/ | |
/******/ // define getter function for harmony exports | |
/******/ __webpack_require__.d = function(exports, name, getter) { | |
/******/ if(!__webpack_require__.o(exports, name)) { | |
/******/ Object.defineProperty(exports, name, { | |
/******/ configurable: false, | |
/******/ enumerable: true, | |
/******/ get: getter | |
/******/ }); | |
/******/ } | |
/******/ }; | |
/******/ | |
/******/ // getDefaultExport function for compatibility with non-harmony modules | |
/******/ __webpack_require__.n = function(module) { | |
/******/ var getter = module && module.__esModule ? | |
/******/ function getDefault() { return module['default']; } : | |
/******/ function getModuleExports() { return module; }; | |
/******/ __webpack_require__.d(getter, 'a', getter); | |
/******/ return getter; | |
/******/ }; | |
/******/ | |
/******/ // Object.prototype.hasOwnProperty.call | |
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; | |
/******/ | |
/******/ // __webpack_public_path__ | |
/******/ __webpack_require__.p = ""; | |
/******/ | |
/******/ // Load entry module and return exports | |
/******/ return __webpack_require__(__webpack_require__.s = 15); | |
/******/ }) | |
/************************************************************************/ | |
/******/ ([ | |
/* 0 */ | |
/***/ (function(module, exports) { | |
exports.nil = new Error('#NULL!'); | |
exports.div0 = new Error('#DIV/0!'); | |
exports.value = new Error('#VALUE!'); | |
exports.ref = new Error('#REF!'); | |
exports.name = new Error('#NAME?'); | |
exports.num = new Error('#NUM!'); | |
exports.na = new Error('#N/A'); | |
exports.error = new Error('#ERROR!'); | |
exports.data = new Error('#GETTING_DATA'); | |
/***/ }), | |
/* 1 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
exports.flattenShallow = function(array) { | |
if (!array || !array.reduce) { | |
return array; | |
} | |
return array.reduce(function(a, b) { | |
var aIsArray = Array.isArray(a); | |
var bIsArray = Array.isArray(b); | |
if (aIsArray && bIsArray ) { | |
return a.concat(b); | |
} | |
if (aIsArray) { | |
a.push(b); | |
return a; | |
} | |
if (bIsArray) { | |
return [a].concat(b); | |
} | |
return [a, b]; | |
}); | |
}; | |
exports.isFlat = function(array) { | |
if (!array) { | |
return false; | |
} | |
for (var i = 0; i < array.length; ++i) { | |
if (Array.isArray(array[i])) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
exports.flatten = function() { | |
var result = exports.argsToArray.apply(null, arguments); | |
while (!exports.isFlat(result)) { | |
result = exports.flattenShallow(result); | |
} | |
return result; | |
}; | |
exports.argsToArray = function(args) { | |
var result = []; | |
exports.arrayEach(args, function(value) { | |
result.push(value); | |
}); | |
return result; | |
}; | |
exports.numbers = function() { | |
var possibleNumbers = this.flatten.apply(null, arguments); | |
return possibleNumbers.filter(function(el) { | |
return typeof el === 'number'; | |
}); | |
}; | |
exports.cleanFloat = function(number) { | |
var power = 1e14; | |
return Math.round(number * power) / power; | |
}; | |
exports.parseBool = function(bool) { | |
if (typeof bool === 'boolean') { | |
return bool; | |
} | |
if (bool instanceof Error) { | |
return bool; | |
} | |
if (typeof bool === 'number') { | |
return bool !== 0; | |
} | |
if (typeof bool === 'string') { | |
var up = bool.toUpperCase(); | |
if (up === 'TRUE') { | |
return true; | |
} | |
if (up === 'FALSE') { | |
return false; | |
} | |
} | |
if (bool instanceof Date && !isNaN(bool)) { | |
return true; | |
} | |
return error.value; | |
}; | |
exports.parseNumber = function(string) { | |
if (string === undefined || string === '') { | |
return error.value; | |
} | |
if (!isNaN(string)) { | |
return parseFloat(string); | |
} | |
return error.value; | |
}; | |
exports.parseNumberArray = function(arr) { | |
var len; | |
if (!arr || (len = arr.length) === 0) { | |
return error.value; | |
} | |
var parsed; | |
while (len--) { | |
parsed = exports.parseNumber(arr[len]); | |
if (parsed === error.value) { | |
return parsed; | |
} | |
arr[len] = parsed; | |
} | |
return arr; | |
}; | |
exports.parseMatrix = function(matrix) { | |
var n; | |
if (!matrix || (n = matrix.length) === 0) { | |
return error.value; | |
} | |
var pnarr; | |
for (var i = 0; i < matrix.length; i++) { | |
pnarr = exports.parseNumberArray(matrix[i]); | |
matrix[i] = pnarr; | |
if (pnarr instanceof Error) { | |
return pnarr; | |
} | |
} | |
return matrix; | |
}; | |
var d1900 = new Date(Date.UTC(1900, 0, 1)); | |
exports.parseDate = function(date) { | |
if (!isNaN(date)) { | |
if (date instanceof Date) { | |
return new Date(date); | |
} | |
var d = parseInt(date, 10); | |
if (d < 0) { | |
return error.num; | |
} | |
if (d <= 60) { | |
return new Date(d1900.getTime() + (d - 1) * 86400000); | |
} | |
return new Date(d1900.getTime() + (d - 2) * 86400000); | |
} | |
if (typeof date === 'string') { | |
date = new Date(date); | |
if (!isNaN(date)) { | |
return date; | |
} | |
} | |
return error.value; | |
}; | |
exports.parseDateArray = function(arr) { | |
var len = arr.length; | |
var parsed; | |
while (len--) { | |
parsed = this.parseDate(arr[len]); | |
if (parsed === error.value) { | |
return parsed; | |
} | |
arr[len] = parsed; | |
} | |
return arr; | |
}; | |
exports.anyIsError = function() { | |
var n = arguments.length; | |
while (n--) { | |
if (arguments[n] instanceof Error) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
exports.arrayValuesToNumbers = function(arr) { | |
var n = arr.length; | |
var el; | |
while (n--) { | |
el = arr[n]; | |
if (typeof el === 'number') { | |
continue; | |
} | |
if (el === true) { | |
arr[n] = 1; | |
continue; | |
} | |
if (el === false) { | |
arr[n] = 0; | |
continue; | |
} | |
if (typeof el === 'string') { | |
var number = this.parseNumber(el); | |
if (number instanceof Error) { | |
arr[n] = 0; | |
} else { | |
arr[n] = number; | |
} | |
} | |
} | |
return arr; | |
}; | |
exports.rest = function(array, idx) { | |
idx = idx || 1; | |
if (!array || typeof array.slice !== 'function') { | |
return array; | |
} | |
return array.slice(idx); | |
}; | |
exports.initial = function(array, idx) { | |
idx = idx || 1; | |
if (!array || typeof array.slice !== 'function') { | |
return array; | |
} | |
return array.slice(0, array.length - idx); | |
}; | |
exports.arrayEach = function(array, iteratee) { | |
var index = -1, length = array.length; | |
while (++index < length) { | |
if (iteratee(array[index], index, array) === false) { | |
break; | |
} | |
} | |
return array; | |
}; | |
exports.transpose = function(matrix) { | |
if(!matrix) { | |
return error.value; | |
} | |
return matrix[0].map(function(col, i) { | |
return matrix.map(function(row) { | |
return row[i]; | |
}); | |
}); | |
}; | |
/***/ }), | |
/* 2 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
var _errors; | |
exports['default'] = error; | |
exports.isValidStrict = isValidStrict; | |
var ERROR = exports.ERROR = 'ERROR'; | |
var ERROR_DIV_ZERO = exports.ERROR_DIV_ZERO = 'DIV/0'; | |
var ERROR_NAME = exports.ERROR_NAME = 'NAME'; | |
var ERROR_NOT_AVAILABLE = exports.ERROR_NOT_AVAILABLE = 'N/A'; | |
var ERROR_NULL = exports.ERROR_NULL = 'NULL'; | |
var ERROR_NUM = exports.ERROR_NUM = 'NUM'; | |
var ERROR_REF = exports.ERROR_REF = 'REF'; | |
var ERROR_VALUE = exports.ERROR_VALUE = 'VALUE'; | |
var errors = (_errors = {}, _errors[ERROR] = '#ERROR!', _errors[ERROR_DIV_ZERO] = '#DIV/0!', _errors[ERROR_NAME] = '#NAME?', _errors[ERROR_NOT_AVAILABLE] = '#N/A', _errors[ERROR_NULL] = '#NULL!', _errors[ERROR_NUM] = '#NUM!', _errors[ERROR_REF] = '#REF!', _errors[ERROR_VALUE] = '#VALUE!', _errors); | |
/** | |
* Return error type based on provided error id. | |
* | |
* @param {String} type Error type. | |
* @returns {String|null} Returns error id. | |
*/ | |
function error(type) { | |
var result = void 0; | |
type = (type + '').replace(/#|!|\?/g, ''); | |
if (errors[type]) { | |
result = errors[type]; | |
} | |
return result ? result : null; | |
} | |
/** | |
* Check if error type is strict valid with knows errors. | |
* | |
* @param {String} Error type. | |
* @return {Boolean} | |
*/ | |
function isValidStrict(type) { | |
var valid = false; | |
for (var i in errors) { | |
if (Object.prototype.hasOwnProperty.call(errors, i) && errors[i] === type) { | |
valid = true; | |
break; | |
} | |
} | |
return valid; | |
} | |
/***/ }), | |
/* 3 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.toNumber = toNumber; | |
exports.invertNumber = invertNumber; | |
/** | |
* Convert value into number. | |
* | |
* @param {String|Number} number | |
* @returns {*} | |
*/ | |
function toNumber(number) { | |
var result = void 0; | |
if (typeof number === 'number') { | |
result = number; | |
} else if (typeof number === 'string') { | |
result = number.indexOf('.') > -1 ? parseFloat(number) : parseInt(number, 10); | |
} | |
return result; | |
} | |
/** | |
* Invert provided number. | |
* | |
* @param {Number} number | |
* @returns {Number} Returns inverted number. | |
*/ | |
function invertNumber(number) { | |
return -1 * toNumber(number); | |
} | |
/***/ }), | |
/* 4 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var utils = __webpack_require__(1); | |
var error = __webpack_require__(0); | |
var statistical = __webpack_require__(5); | |
var information = __webpack_require__(8); | |
var evalExpression = __webpack_require__(7); | |
exports.ABS = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.abs(number); | |
return result; | |
}; | |
exports.ACOS = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.acos(number); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.ACOSH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.log(number + Math.sqrt(number * number - 1)); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.ACOT = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.atan(1 / number); | |
return result; | |
}; | |
exports.ACOTH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = 0.5 * Math.log((number + 1) / (number - 1)); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
//TODO: use options | |
exports.AGGREGATE = function(function_num, options, ref1, ref2) { | |
function_num = utils.parseNumber(function_num); | |
options = utils.parseNumber(function_num); | |
if (utils.anyIsError(function_num, options)) { | |
return error.value; | |
} | |
switch (function_num) { | |
case 1: | |
return statistical.AVERAGE(ref1); | |
case 2: | |
return statistical.COUNT(ref1); | |
case 3: | |
return statistical.COUNTA(ref1); | |
case 4: | |
return statistical.MAX(ref1); | |
case 5: | |
return statistical.MIN(ref1); | |
case 6: | |
return exports.PRODUCT(ref1); | |
case 7: | |
return statistical.STDEV.S(ref1); | |
case 8: | |
return statistical.STDEV.P(ref1); | |
case 9: | |
return exports.SUM(ref1); | |
case 10: | |
return statistical.VAR.S(ref1); | |
case 11: | |
return statistical.VAR.P(ref1); | |
case 12: | |
return statistical.MEDIAN(ref1); | |
case 13: | |
return statistical.MODE.SNGL(ref1); | |
case 14: | |
return statistical.LARGE(ref1, ref2); | |
case 15: | |
return statistical.SMALL(ref1, ref2); | |
case 16: | |
return statistical.PERCENTILE.INC(ref1, ref2); | |
case 17: | |
return statistical.QUARTILE.INC(ref1, ref2); | |
case 18: | |
return statistical.PERCENTILE.EXC(ref1, ref2); | |
case 19: | |
return statistical.QUARTILE.EXC(ref1, ref2); | |
} | |
}; | |
exports.ARABIC = function(text) { | |
// Credits: Rafa? Kukawski | |
if (!/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/.test(text)) { | |
return error.value; | |
} | |
var r = 0; | |
text.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function(i) { | |
r += { | |
M: 1000, | |
CM: 900, | |
D: 500, | |
CD: 400, | |
C: 100, | |
XC: 90, | |
L: 50, | |
XL: 40, | |
X: 10, | |
IX: 9, | |
V: 5, | |
IV: 4, | |
I: 1 | |
}[i]; | |
}); | |
return r; | |
}; | |
exports.ASIN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.asin(number); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.ASINH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.log(number + Math.sqrt(number * number + 1)); | |
}; | |
exports.ATAN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.atan(number); | |
}; | |
exports.ATAN2 = function(number_x, number_y) { | |
number_x = utils.parseNumber(number_x); | |
number_y = utils.parseNumber(number_y); | |
if (utils.anyIsError(number_x, number_y)) { | |
return error.value; | |
} | |
return Math.atan2(number_x, number_y); | |
}; | |
exports.ATANH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var result = Math.log((1 + number) / (1 - number)) / 2; | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.BASE = function(number, radix, min_length) { | |
min_length = min_length || 0; | |
number = utils.parseNumber(number); | |
radix = utils.parseNumber(radix); | |
min_length = utils.parseNumber(min_length); | |
if (utils.anyIsError(number, radix, min_length)) { | |
return error.value; | |
} | |
min_length = (min_length === undefined) ? 0 : min_length; | |
var result = number.toString(radix); | |
return new Array(Math.max(min_length + 1 - result.length, 0)).join('0') + result; | |
}; | |
exports.CEILING = function(number, significance, mode) { | |
significance = (significance === undefined) ? 1 : Math.abs(significance); | |
mode = mode || 0; | |
number = utils.parseNumber(number); | |
significance = utils.parseNumber(significance); | |
mode = utils.parseNumber(mode); | |
if (utils.anyIsError(number, significance, mode)) { | |
return error.value; | |
} | |
if (significance === 0) { | |
return 0; | |
} | |
var precision = -Math.floor(Math.log(significance) / Math.log(10)); | |
if (number >= 0) { | |
return exports.ROUND(Math.ceil(number / significance) * significance, precision); | |
} else { | |
if (mode === 0) { | |
return -exports.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); | |
} else { | |
return -exports.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); | |
} | |
} | |
}; | |
exports.CEILING.MATH = exports.CEILING; | |
exports.CEILING.PRECISE = exports.CEILING; | |
exports.COMBIN = function(number, number_chosen) { | |
number = utils.parseNumber(number); | |
number_chosen = utils.parseNumber(number_chosen); | |
if (utils.anyIsError(number, number_chosen)) { | |
return error.value; | |
} | |
return exports.FACT(number) / (exports.FACT(number_chosen) * exports.FACT(number - number_chosen)); | |
}; | |
exports.COMBINA = function(number, number_chosen) { | |
number = utils.parseNumber(number); | |
number_chosen = utils.parseNumber(number_chosen); | |
if (utils.anyIsError(number, number_chosen)) { | |
return error.value; | |
} | |
return (number === 0 && number_chosen === 0) ? 1 : exports.COMBIN(number + number_chosen - 1, number - 1); | |
}; | |
exports.COS = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.cos(number); | |
}; | |
exports.COSH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return (Math.exp(number) + Math.exp(-number)) / 2; | |
}; | |
exports.COT = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return 1 / Math.tan(number); | |
}; | |
exports.COTH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var e2 = Math.exp(2 * number); | |
return (e2 + 1) / (e2 - 1); | |
}; | |
exports.CSC = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return 1 / Math.sin(number); | |
}; | |
exports.CSCH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return 2 / (Math.exp(number) - Math.exp(-number)); | |
}; | |
exports.DECIMAL = function(number, radix) { | |
if (arguments.length < 1) { | |
return error.value; | |
} | |
return parseInt(number, radix); | |
}; | |
exports.DEGREES = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return number * 180 / Math.PI; | |
}; | |
exports.EVEN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return exports.CEILING(number, -2, -1); | |
}; | |
exports.EXP = function(number) { | |
if (arguments.length < 1) { | |
return error.na; | |
} | |
if (typeof number !== 'number' || arguments.length > 1) { | |
return error.error; | |
} | |
number = Math.exp(number); | |
return number; | |
}; | |
var MEMOIZED_FACT = []; | |
exports.FACT = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var n = Math.floor(number); | |
if (n === 0 || n === 1) { | |
return 1; | |
} else if (MEMOIZED_FACT[n] > 0) { | |
return MEMOIZED_FACT[n]; | |
} else { | |
MEMOIZED_FACT[n] = exports.FACT(n - 1) * n; | |
return MEMOIZED_FACT[n]; | |
} | |
}; | |
exports.FACTDOUBLE = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var n = Math.floor(number); | |
if (n <= 0) { | |
return 1; | |
} else { | |
return n * exports.FACTDOUBLE(n - 2); | |
} | |
}; | |
exports.FLOOR = function(number, significance) { | |
number = utils.parseNumber(number); | |
significance = utils.parseNumber(significance); | |
if (utils.anyIsError(number, significance)) { | |
return error.value; | |
} | |
if (significance === 0) { | |
return 0; | |
} | |
if (!(number > 0 && significance > 0) && !(number < 0 && significance < 0)) { | |
return error.num; | |
} | |
significance = Math.abs(significance); | |
var precision = -Math.floor(Math.log(significance) / Math.log(10)); | |
if (number >= 0) { | |
return exports.ROUND(Math.floor(number / significance) * significance, precision); | |
} else { | |
return -exports.ROUND(Math.ceil(Math.abs(number) / significance), precision); | |
} | |
}; | |
//TODO: Verify | |
exports.FLOOR.MATH = function(number, significance, mode) { | |
significance = (significance === undefined) ? 1 : significance; | |
mode = (mode === undefined) ? 0 : mode; | |
number = utils.parseNumber(number); | |
significance = utils.parseNumber(significance); | |
mode = utils.parseNumber(mode); | |
if (utils.anyIsError(number, significance, mode)) { | |
return error.value; | |
} | |
if (significance === 0) { | |
return 0; | |
} | |
significance = significance ? Math.abs(significance) : 1; | |
var precision = -Math.floor(Math.log(significance) / Math.log(10)); | |
if (number >= 0) { | |
return exports.ROUND(Math.floor(number / significance) * significance, precision); | |
} else if (mode === 0 || mode === undefined) { | |
return -exports.ROUND(Math.ceil(Math.abs(number) / significance) * significance, precision); | |
} | |
return -exports.ROUND(Math.floor(Math.abs(number) / significance) * significance, precision); | |
}; | |
// Deprecated | |
exports.FLOOR.PRECISE = exports.FLOOR.MATH; | |
// adapted http://rosettacode.org/wiki/Greatest_common_divisor#JavaScript | |
exports.GCD = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var n = range.length; | |
var r0 = range[0]; | |
var x = r0 < 0 ? -r0 : r0; | |
for (var i = 1; i < n; i++) { | |
var ri = range[i]; | |
var y = ri < 0 ? -ri : ri; | |
while (x && y) { | |
if (x > y) { | |
x %= y; | |
} else { | |
y %= x; | |
} | |
} | |
x += y; | |
} | |
return x; | |
}; | |
exports.INT = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.floor(number); | |
}; | |
//TODO: verify | |
exports.ISO = { | |
CEILING: exports.CEILING | |
}; | |
exports.LCM = function() { | |
// Credits: Jonas Raoni Soares Silva | |
var o = utils.parseNumberArray(utils.flatten(arguments)); | |
if (o instanceof Error) { | |
return o; | |
} | |
for (var i, j, n, d, r = 1; | |
(n = o.pop()) !== undefined;) { | |
while (n > 1) { | |
if (n % 2) { | |
for (i = 3, j = Math.floor(Math.sqrt(n)); i <= j && n % i; i += 2) { | |
//empty | |
} | |
d = (i <= j) ? i : n; | |
} else { | |
d = 2; | |
} | |
for (n /= d, r *= d, i = o.length; i; | |
(o[--i] % d) === 0 && (o[i] /= d) === 1 && o.splice(i, 1)) { | |
//empty | |
} | |
} | |
} | |
return r; | |
}; | |
exports.LN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.log(number); | |
}; | |
exports.LN10 = function() { | |
return Math.log(10); | |
}; | |
exports.LN2 = function() { | |
return Math.log(2); | |
}; | |
exports.LOG10E = function() { | |
return Math.LOG10E; | |
}; | |
exports.LOG2E = function() { | |
return Math.LOG2E; | |
}; | |
exports.LOG = function(number, base) { | |
number = utils.parseNumber(number); | |
base = utils.parseNumber(base); | |
if (utils.anyIsError(number, base)) { | |
return error.value; | |
} | |
base = (base === undefined) ? 10 : base; | |
return Math.log(number) / Math.log(base); | |
}; | |
exports.LOG10 = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.log(number) / Math.log(10); | |
}; | |
exports.MOD = function(dividend, divisor) { | |
dividend = utils.parseNumber(dividend); | |
divisor = utils.parseNumber(divisor); | |
if (utils.anyIsError(dividend, divisor)) { | |
return error.value; | |
} | |
if (divisor === 0) { | |
return error.div0; | |
} | |
var modulus = Math.abs(dividend % divisor); | |
return (divisor > 0) ? modulus : -modulus; | |
}; | |
exports.MROUND = function(number, multiple) { | |
number = utils.parseNumber(number); | |
multiple = utils.parseNumber(multiple); | |
if (utils.anyIsError(number, multiple)) { | |
return error.value; | |
} | |
if (number * multiple < 0) { | |
return error.num; | |
} | |
return Math.round(number / multiple) * multiple; | |
}; | |
exports.MULTINOMIAL = function() { | |
var args = utils.parseNumberArray(utils.flatten(arguments)); | |
if (args instanceof Error) { | |
return args; | |
} | |
var sum = 0; | |
var divisor = 1; | |
for (var i = 0; i < args.length; i++) { | |
sum += args[i]; | |
divisor *= exports.FACT(args[i]); | |
} | |
return exports.FACT(sum) / divisor; | |
}; | |
exports.ODD = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var temp = Math.ceil(Math.abs(number)); | |
temp = (temp & 1) ? temp : temp + 1; | |
return (number > 0) ? temp : -temp; | |
}; | |
exports.PI = function() { | |
return Math.PI; | |
}; | |
exports.E = function() { | |
return Math.E; | |
}; | |
exports.POWER = function(number, power) { | |
number = utils.parseNumber(number); | |
power = utils.parseNumber(power); | |
if (utils.anyIsError(number, power)) { | |
return error.value; | |
} | |
var result = Math.pow(number, power); | |
if (isNaN(result)) { | |
return error.num; | |
} | |
return result; | |
}; | |
exports.PRODUCT = function() { | |
var args = utils.parseNumberArray(utils.flatten(arguments)); | |
if (args instanceof Error) { | |
return args; | |
} | |
var result = 1; | |
for (var i = 0; i < args.length; i++) { | |
result *= args[i]; | |
} | |
return result; | |
}; | |
exports.QUOTIENT = function(numerator, denominator) { | |
numerator = utils.parseNumber(numerator); | |
denominator = utils.parseNumber(denominator); | |
if (utils.anyIsError(numerator, denominator)) { | |
return error.value; | |
} | |
return parseInt(numerator / denominator, 10); | |
}; | |
exports.RADIANS = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return number * Math.PI / 180; | |
}; | |
exports.RAND = function() { | |
return Math.random(); | |
}; | |
exports.RANDBETWEEN = function(bottom, top) { | |
bottom = utils.parseNumber(bottom); | |
top = utils.parseNumber(top); | |
if (utils.anyIsError(bottom, top)) { | |
return error.value; | |
} | |
// Creative Commons Attribution 3.0 License | |
// Copyright (c) 2012 eqcode | |
return bottom + Math.ceil((top - bottom + 1) * Math.random()) - 1; | |
}; | |
// TODO | |
exports.ROMAN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
// The MIT License | |
// Copyright (c) 2008 Steven Levithan | |
var digits = String(number).split(''); | |
var key = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']; | |
var roman = ''; | |
var i = 3; | |
while (i--) { | |
roman = (key[+digits.pop() + (i * 10)] || '') + roman; | |
} | |
return new Array(+digits.join('') + 1).join('M') + roman; | |
}; | |
exports.ROUND = function(number, digits) { | |
number = utils.parseNumber(number); | |
digits = utils.parseNumber(digits); | |
if (utils.anyIsError(number, digits)) { | |
return error.value; | |
} | |
return Math.round(number * Math.pow(10, digits)) / Math.pow(10, digits); | |
}; | |
exports.ROUNDDOWN = function(number, digits) { | |
number = utils.parseNumber(number); | |
digits = utils.parseNumber(digits); | |
if (utils.anyIsError(number, digits)) { | |
return error.value; | |
} | |
var sign = (number > 0) ? 1 : -1; | |
return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); | |
}; | |
exports.ROUNDUP = function(number, digits) { | |
number = utils.parseNumber(number); | |
digits = utils.parseNumber(digits); | |
if (utils.anyIsError(number, digits)) { | |
return error.value; | |
} | |
var sign = (number > 0) ? 1 : -1; | |
return sign * (Math.ceil(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); | |
}; | |
exports.SEC = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return 1 / Math.cos(number); | |
}; | |
exports.SECH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return 2 / (Math.exp(number) + Math.exp(-number)); | |
}; | |
exports.SERIESSUM = function(x, n, m, coefficients) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
m = utils.parseNumber(m); | |
coefficients = utils.parseNumberArray(coefficients); | |
if (utils.anyIsError(x, n, m, coefficients)) { | |
return error.value; | |
} | |
var result = coefficients[0] * Math.pow(x, n); | |
for (var i = 1; i < coefficients.length; i++) { | |
result += coefficients[i] * Math.pow(x, n + i * m); | |
} | |
return result; | |
}; | |
exports.SIGN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
if (number < 0) { | |
return -1; | |
} else if (number === 0) { | |
return 0; | |
} else { | |
return 1; | |
} | |
}; | |
exports.SIN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.sin(number); | |
}; | |
exports.SINH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return (Math.exp(number) - Math.exp(-number)) / 2; | |
}; | |
exports.SQRT = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
if (number < 0) { | |
return error.num; | |
} | |
return Math.sqrt(number); | |
}; | |
exports.SQRTPI = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.sqrt(number * Math.PI); | |
}; | |
exports.SQRT1_2 = function() { | |
return 1 / Math.sqrt(2); | |
}; | |
exports.SQRT2 = function() { | |
return Math.sqrt(2); | |
}; | |
exports.SUBTOTAL = function(function_code, ref1) { | |
function_code = utils.parseNumber(function_code); | |
if (function_code instanceof Error) { | |
return function_code; | |
} | |
switch (function_code) { | |
case 1: | |
return statistical.AVERAGE(ref1); | |
case 2: | |
return statistical.COUNT(ref1); | |
case 3: | |
return statistical.COUNTA(ref1); | |
case 4: | |
return statistical.MAX(ref1); | |
case 5: | |
return statistical.MIN(ref1); | |
case 6: | |
return exports.PRODUCT(ref1); | |
case 7: | |
return statistical.STDEV.S(ref1); | |
case 8: | |
return statistical.STDEV.P(ref1); | |
case 9: | |
return exports.SUM(ref1); | |
case 10: | |
return statistical.VAR.S(ref1); | |
case 11: | |
return statistical.VAR.P(ref1); | |
// no hidden values for us | |
case 101: | |
return statistical.AVERAGE(ref1); | |
case 102: | |
return statistical.COUNT(ref1); | |
case 103: | |
return statistical.COUNTA(ref1); | |
case 104: | |
return statistical.MAX(ref1); | |
case 105: | |
return statistical.MIN(ref1); | |
case 106: | |
return exports.PRODUCT(ref1); | |
case 107: | |
return statistical.STDEV.S(ref1); | |
case 108: | |
return statistical.STDEV.P(ref1); | |
case 109: | |
return exports.SUM(ref1); | |
case 110: | |
return statistical.VAR.S(ref1); | |
case 111: | |
return statistical.VAR.P(ref1); | |
} | |
}; | |
exports.ADD = function (num1, num2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
num1 = utils.parseNumber(num1); | |
num2 = utils.parseNumber(num2); | |
if (utils.anyIsError(num1, num2)) { | |
return error.value; | |
} | |
return num1 + num2; | |
}; | |
exports.MINUS = function (num1, num2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
num1 = utils.parseNumber(num1); | |
num2 = utils.parseNumber(num2); | |
if (utils.anyIsError(num1, num2)) { | |
return error.value; | |
} | |
return num1 - num2; | |
}; | |
exports.DIVIDE = function (dividend, divisor) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
dividend = utils.parseNumber(dividend); | |
divisor = utils.parseNumber(divisor); | |
if (utils.anyIsError(dividend, divisor)) { | |
return error.value; | |
} | |
if (divisor === 0) { | |
return error.div0; | |
} | |
return dividend / divisor; | |
}; | |
exports.MULTIPLY = function (factor1, factor2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
factor1 = utils.parseNumber(factor1); | |
factor2 = utils.parseNumber(factor2); | |
if (utils.anyIsError(factor1, factor2)) { | |
return error.value; | |
} | |
return factor1 * factor2; | |
}; | |
exports.GTE = function (num1, num2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
num1 = utils.parseNumber(num1); | |
num2 = utils.parseNumber(num2); | |
if (utils.anyIsError(num1, num2)) { | |
return error.error; | |
} | |
return num1 >= num2; | |
}; | |
exports.LT = function (num1, num2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
num1 = utils.parseNumber(num1); | |
num2 = utils.parseNumber(num2); | |
if (utils.anyIsError(num1, num2)) { | |
return error.error; | |
} | |
return num1 < num2; | |
}; | |
exports.LTE = function (num1, num2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
num1 = utils.parseNumber(num1); | |
num2 = utils.parseNumber(num2); | |
if (utils.anyIsError(num1, num2)) { | |
return error.error; | |
} | |
return num1 <= num2; | |
}; | |
exports.EQ = function (value1, value2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
return value1 === value2; | |
}; | |
exports.NE = function (value1, value2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
return value1 !== value2; | |
}; | |
exports.POW = function (base, exponent) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
base = utils.parseNumber(base); | |
exponent = utils.parseNumber(exponent); | |
if (utils.anyIsError(base, exponent)) { | |
return error.error; | |
} | |
return exports.POWER(base, exponent); | |
}; | |
exports.SUM = function() { | |
var result = 0; | |
utils.arrayEach(utils.argsToArray(arguments), function(value) { | |
if (typeof value === 'number') { | |
result += value; | |
} else if (typeof value === 'string') { | |
var parsed = parseFloat(value); | |
!isNaN(parsed) && (result += parsed); | |
} else if (Array.isArray(value)) { | |
result += exports.SUM.apply(null, value); | |
} | |
}); | |
return result; | |
}; | |
exports.SUMIF = function(range, criteria) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var result = 0; | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
var tokenizedCriteria = isWildcard ? null : evalExpression.parse(criteria + ''); | |
for (var i = 0; i < range.length; i++) { | |
var value = range[i]; | |
if (isWildcard) { | |
result += value; | |
} else { | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
result += (evalExpression.compute(tokens) ? value : 0); | |
} | |
} | |
return result; | |
}; | |
exports.SUMIFS = function() { | |
var args = utils.argsToArray(arguments); | |
var range = utils.parseNumberArray(utils.flatten(args.shift())); | |
if (range instanceof Error) { | |
return range; | |
} | |
var criterias = args; | |
var n_range_elements = range.length; | |
var criteriaLength = criterias.length; | |
var result = 0; | |
for (var i = 0; i < n_range_elements; i++) { | |
var value = range[i]; | |
var isMeetCondition = false; | |
for (var j = 0; j < criteriaLength; j++) { | |
var criteria = criterias[j]; | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
var computedResult = false; | |
if (isWildcard) { | |
computedResult = true; | |
} else { | |
var tokenizedCriteria = evalExpression.parse(criteria + ''); | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
computedResult = evalExpression.compute(tokens); | |
} | |
// Criterias are calculated as AND so any `false` breakes the loop as unmeet condition | |
if (!computedResult) { | |
isMeetCondition = false; | |
break; | |
} | |
isMeetCondition = true; | |
} | |
if (isMeetCondition) { | |
result += value; | |
} | |
} | |
return result; | |
}; | |
exports.SUMPRODUCT = function() { | |
if (!arguments || arguments.length === 0) { | |
return error.value; | |
} | |
var arrays = arguments.length + 1; | |
var result = 0; | |
var product; | |
var k; | |
var _i; | |
var _ij; | |
for (var i = 0; i < arguments[0].length; i++) { | |
if (!(arguments[0][i] instanceof Array)) { | |
product = 1; | |
for (k = 1; k < arrays; k++) { | |
_i = utils.parseNumber(arguments[k - 1][i]); | |
if (_i instanceof Error) { | |
return _i; | |
} | |
product *= _i; | |
} | |
result += product; | |
} else { | |
for (var j = 0; j < arguments[0][i].length; j++) { | |
product = 1; | |
for (k = 1; k < arrays; k++) { | |
_ij = utils.parseNumber(arguments[k - 1][i][j]); | |
if (_ij instanceof Error) { | |
return _ij; | |
} | |
product *= _ij; | |
} | |
result += product; | |
} | |
} | |
} | |
return result; | |
}; | |
exports.SUMSQ = function() { | |
var numbers = utils.parseNumberArray(utils.flatten(arguments)); | |
if (numbers instanceof Error) { | |
return numbers; | |
} | |
var result = 0; | |
var length = numbers.length; | |
for (var i = 0; i < length; i++) { | |
result += (information.ISNUMBER(numbers[i])) ? numbers[i] * numbers[i] : 0; | |
} | |
return result; | |
}; | |
exports.SUMX2MY2 = function(array_x, array_y) { | |
array_x = utils.parseNumberArray(utils.flatten(array_x)); | |
array_y = utils.parseNumberArray(utils.flatten(array_y)); | |
if (utils.anyIsError(array_x, array_y)) { | |
return error.value; | |
} | |
var result = 0; | |
for (var i = 0; i < array_x.length; i++) { | |
result += array_x[i] * array_x[i] - array_y[i] * array_y[i]; | |
} | |
return result; | |
}; | |
exports.SUMX2PY2 = function(array_x, array_y) { | |
array_x = utils.parseNumberArray(utils.flatten(array_x)); | |
array_y = utils.parseNumberArray(utils.flatten(array_y)); | |
if (utils.anyIsError(array_x, array_y)) { | |
return error.value; | |
} | |
var result = 0; | |
array_x = utils.parseNumberArray(utils.flatten(array_x)); | |
array_y = utils.parseNumberArray(utils.flatten(array_y)); | |
for (var i = 0; i < array_x.length; i++) { | |
result += array_x[i] * array_x[i] + array_y[i] * array_y[i]; | |
} | |
return result; | |
}; | |
exports.SUMXMY2 = function(array_x, array_y) { | |
array_x = utils.parseNumberArray(utils.flatten(array_x)); | |
array_y = utils.parseNumberArray(utils.flatten(array_y)); | |
if (utils.anyIsError(array_x, array_y)) { | |
return error.value; | |
} | |
var result = 0; | |
array_x = utils.flatten(array_x); | |
array_y = utils.flatten(array_y); | |
for (var i = 0; i < array_x.length; i++) { | |
result += Math.pow(array_x[i] - array_y[i], 2); | |
} | |
return result; | |
}; | |
exports.TAN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return Math.tan(number); | |
}; | |
exports.TANH = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
var e2 = Math.exp(2 * number); | |
return (e2 - 1) / (e2 + 1); | |
}; | |
exports.TRUNC = function(number, digits) { | |
digits = (digits === undefined) ? 0 : digits; | |
number = utils.parseNumber(number); | |
digits = utils.parseNumber(digits); | |
if (utils.anyIsError(number, digits)) { | |
return error.value; | |
} | |
var sign = (number > 0) ? 1 : -1; | |
return sign * (Math.floor(Math.abs(number) * Math.pow(10, digits))) / Math.pow(10, digits); | |
}; | |
/***/ }), | |
/* 5 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var mathTrig = __webpack_require__(4); | |
var text = __webpack_require__(6); | |
var jStat = __webpack_require__(10); | |
var utils = __webpack_require__(1); | |
var evalExpression = __webpack_require__(7); | |
var error = __webpack_require__(0); | |
var misc = __webpack_require__(11); | |
var SQRT2PI = 2.5066282746310002; | |
exports.AVEDEV = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
return jStat.sum(jStat(range).subtract(jStat.mean(range)).abs()[0]) / range.length; | |
}; | |
exports.AVERAGE = function() { | |
var range = utils.numbers(utils.flatten(arguments)); | |
var n = range.length; | |
var sum = 0; | |
var count = 0; | |
var result; | |
for (var i = 0; i < n; i++) { | |
sum += range[i]; | |
count += 1; | |
} | |
result = sum / count; | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.AVERAGEA = function() { | |
var range = utils.flatten(arguments); | |
var n = range.length; | |
var sum = 0; | |
var count = 0; | |
var result; | |
for (var i = 0; i < n; i++) { | |
var el = range[i]; | |
if (typeof el === 'number') { | |
sum += el; | |
} | |
if (el === true) { | |
sum++; | |
} | |
if (el !== null) { | |
count++; | |
} | |
} | |
result = sum / count; | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.AVERAGEIF = function(range, criteria, average_range) { | |
if (arguments.length <= 1) { | |
return error.na; | |
} | |
average_range = average_range || range; | |
range = utils.flatten(range); | |
average_range = utils.parseNumberArray(utils.flatten(average_range)); | |
if (average_range instanceof Error) { | |
return average_range; | |
} | |
var average_count = 0; | |
var result = 0; | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
var tokenizedCriteria = isWildcard ? null : evalExpression.parse(criteria + ''); | |
for (var i = 0; i < range.length; i++) { | |
var value = range[i]; | |
if (isWildcard) { | |
result += average_range[i]; | |
average_count++; | |
} else { | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
if (evalExpression.compute(tokens)) { | |
result += average_range[i]; | |
average_count++; | |
} | |
} | |
} | |
return result / average_count; | |
}; | |
exports.AVERAGEIFS = function() { | |
// Does not work with multi dimensional ranges yet! | |
//http://office.microsoft.com/en-001/excel-help/averageifs-function-HA010047493.aspx | |
var args = utils.argsToArray(arguments); | |
var criteriaLength = (args.length - 1) / 2; | |
var range = utils.flatten(args[0]); | |
var count = 0; | |
var result = 0; | |
for (var i = 0; i < range.length; i++) { | |
var isMeetCondition = false; | |
for (var j = 0; j < criteriaLength; j++) { | |
var value = args[2 * j + 1][i]; | |
var criteria = args[2 * j + 2]; | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
var computedResult = false; | |
if (isWildcard) { | |
computedResult = true; | |
} else { | |
var tokenizedCriteria = evalExpression.parse(criteria + ''); | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
computedResult = evalExpression.compute(tokens); | |
} | |
// Criterias are calculated as AND so any `false` breakes the loop as unmeet condition | |
if (!computedResult) { | |
isMeetCondition = false; | |
break; | |
} | |
isMeetCondition = true; | |
} | |
if (isMeetCondition) { | |
result += range[i]; | |
count++; | |
} | |
} | |
var average = result / count; | |
if (isNaN(average)) { | |
return 0; | |
} else { | |
return average; | |
} | |
}; | |
exports.BETA = {}; | |
exports.BETA.DIST = function(x, alpha, beta, cumulative, A, B) { | |
if (arguments.length < 4) { | |
return error.value; | |
} | |
A = (A === undefined) ? 0 : A; | |
B = (B === undefined) ? 1 : B; | |
x = utils.parseNumber(x); | |
alpha = utils.parseNumber(alpha); | |
beta = utils.parseNumber(beta); | |
A = utils.parseNumber(A); | |
B = utils.parseNumber(B); | |
if (utils.anyIsError(x, alpha, beta, A, B)) { | |
return error.value; | |
} | |
x = (x - A) / (B - A); | |
return (cumulative) ? jStat.beta.cdf(x, alpha, beta) : jStat.beta.pdf(x, alpha, beta); | |
}; | |
exports.BETA.INV = function(probability, alpha, beta, A, B) { | |
A = (A === undefined) ? 0 : A; | |
B = (B === undefined) ? 1 : B; | |
probability = utils.parseNumber(probability); | |
alpha = utils.parseNumber(alpha); | |
beta = utils.parseNumber(beta); | |
A = utils.parseNumber(A); | |
B = utils.parseNumber(B); | |
if (utils.anyIsError(probability, alpha, beta, A, B)) { | |
return error.value; | |
} | |
return jStat.beta.inv(probability, alpha, beta) * (B - A) + A; | |
}; | |
exports.BINOM = {}; | |
exports.BINOM.DIST = function(successes, trials, probability, cumulative) { | |
successes = utils.parseNumber(successes); | |
trials = utils.parseNumber(trials); | |
probability = utils.parseNumber(probability); | |
cumulative = utils.parseNumber(cumulative); | |
if (utils.anyIsError(successes, trials, probability, cumulative)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.binomial.cdf(successes, trials, probability) : jStat.binomial.pdf(successes, trials, probability); | |
}; | |
exports.BINOM.DIST.RANGE = function(trials, probability, successes, successes2) { | |
successes2 = (successes2 === undefined) ? successes : successes2; | |
trials = utils.parseNumber(trials); | |
probability = utils.parseNumber(probability); | |
successes = utils.parseNumber(successes); | |
successes2 = utils.parseNumber(successes2); | |
if (utils.anyIsError(trials, probability, successes, successes2)) { | |
return error.value; | |
} | |
var result = 0; | |
for (var i = successes; i <= successes2; i++) { | |
result += mathTrig.COMBIN(trials, i) * Math.pow(probability, i) * Math.pow(1 - probability, trials - i); | |
} | |
return result; | |
}; | |
exports.BINOM.INV = function(trials, probability, alpha) { | |
trials = utils.parseNumber(trials); | |
probability = utils.parseNumber(probability); | |
alpha = utils.parseNumber(alpha); | |
if (utils.anyIsError(trials, probability, alpha)) { | |
return error.value; | |
} | |
var x = 0; | |
while (x <= trials) { | |
if (jStat.binomial.cdf(x, trials, probability) >= alpha) { | |
return x; | |
} | |
x++; | |
} | |
}; | |
exports.CHISQ = {}; | |
exports.CHISQ.DIST = function(x, k, cumulative) { | |
x = utils.parseNumber(x); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(x, k)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.chisquare.cdf(x, k) : jStat.chisquare.pdf(x, k); | |
}; | |
exports.CHISQ.DIST.RT = function(x, k) { | |
if (!x | !k) { | |
return error.na; | |
} | |
if (x < 1 || k > Math.pow(10, 10)) { | |
return error.num; | |
} | |
if ((typeof x !== 'number') || (typeof k !== 'number')) { | |
return error.value; | |
} | |
return 1 - jStat.chisquare.cdf(x, k); | |
}; | |
exports.CHISQ.INV = function(probability, k) { | |
probability = utils.parseNumber(probability); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(probability, k)) { | |
return error.value; | |
} | |
return jStat.chisquare.inv(probability, k); | |
}; | |
exports.CHISQ.INV.RT = function(p, k) { | |
if (!p | !k) { | |
return error.na; | |
} | |
if (p < 0 || p > 1 || k < 1 || k > Math.pow(10, 10)) { | |
return error.num; | |
} | |
if ((typeof p !== 'number') || (typeof k !== 'number')) { | |
return error.value; | |
} | |
return jStat.chisquare.inv(1.0 - p, k); | |
}; | |
exports.CHISQ.TEST = function(observed, expected) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
if ((!(observed instanceof Array)) || (!(expected instanceof Array))) { | |
return error.value; | |
} | |
if (observed.length !== expected.length) { | |
return error.value; | |
} | |
if (observed[0] && expected[0] && | |
observed[0].length !== expected[0].length) { | |
return error.value; | |
} | |
var row = observed.length; | |
var tmp, i, j; | |
// Convert single-dimension array into two-dimension array | |
for (i = 0; i < row; i ++) { | |
if (!(observed[i] instanceof Array)) { | |
tmp = observed[i]; | |
observed[i] = []; | |
observed[i].push(tmp); | |
} | |
if (!(expected[i] instanceof Array)) { | |
tmp = expected[i]; | |
expected[i] = []; | |
expected[i].push(tmp); | |
} | |
} | |
var col = observed[0].length; | |
var dof = (col === 1) ? row-1 : (row-1)*(col-1); | |
var xsqr = 0; | |
var Pi =Math.PI; | |
for (i = 0; i < row; i ++) { | |
for (j = 0; j < col; j ++) { | |
xsqr += Math.pow((observed[i][j] - expected[i][j]), 2) / expected[i][j]; | |
} | |
} | |
// Get independency by X square and its degree of freedom | |
function ChiSq(xsqr, dof) { | |
var p = Math.exp(-0.5 * xsqr); | |
if((dof%2) === 1) { | |
p = p * Math.sqrt(2 * xsqr/Pi); | |
} | |
var k = dof; | |
while(k >= 2) { | |
p = p * xsqr/k; | |
k = k - 2; | |
} | |
var t = p; | |
var a = dof; | |
while (t > 0.0000000001*p) { | |
a = a + 2; | |
t = t * xsqr/a; | |
p = p + t; | |
} | |
return 1-p; | |
} | |
return Math.round(ChiSq(xsqr, dof) * 1000000) / 1000000; | |
}; | |
exports.COLUMN = function(matrix, index) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
if (index < 0) { | |
return error.num; | |
} | |
if (!(matrix instanceof Array) || (typeof index !== 'number')) { | |
return error.value; | |
} | |
if (matrix.length === 0) { | |
return undefined; | |
} | |
return jStat.col(matrix, index); | |
}; | |
exports.COLUMNS = function(matrix) { | |
if (arguments.length !== 1) { | |
return error.na; | |
} | |
if (!(matrix instanceof Array)) { | |
return error.value; | |
} | |
if (matrix.length === 0) { | |
return 0; | |
} | |
return jStat.cols(matrix); | |
}; | |
exports.CONFIDENCE = {}; | |
exports.CONFIDENCE.NORM = function(alpha, sd, n) { | |
alpha = utils.parseNumber(alpha); | |
sd = utils.parseNumber(sd); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(alpha, sd, n)) { | |
return error.value; | |
} | |
return jStat.normalci(1, alpha, sd, n)[1] - 1; | |
}; | |
exports.CONFIDENCE.T = function(alpha, sd, n) { | |
alpha = utils.parseNumber(alpha); | |
sd = utils.parseNumber(sd); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(alpha, sd, n)) { | |
return error.value; | |
} | |
return jStat.tci(1, alpha, sd, n)[1] - 1; | |
}; | |
exports.CORREL = function(array1, array2) { | |
array1 = utils.parseNumberArray(utils.flatten(array1)); | |
array2 = utils.parseNumberArray(utils.flatten(array2)); | |
if (utils.anyIsError(array1, array2)) { | |
return error.value; | |
} | |
return jStat.corrcoeff(array1, array2); | |
}; | |
exports.COUNT = function() { | |
return utils.numbers(utils.flatten(arguments)).length; | |
}; | |
exports.COUNTA = function() { | |
var range = utils.flatten(arguments); | |
return range.length - exports.COUNTBLANK(range); | |
}; | |
exports.COUNTIN = function (range, value) { | |
var result = 0; | |
range = utils.flatten(range); | |
for (var i = 0; i < range.length; i++) { | |
if (range[i] === value) { | |
result++; | |
} | |
} | |
return result; | |
}; | |
exports.COUNTBLANK = function() { | |
var range = utils.flatten(arguments); | |
var blanks = 0; | |
var element; | |
for (var i = 0; i < range.length; i++) { | |
element = range[i]; | |
if (element === null || element === '') { | |
blanks++; | |
} | |
} | |
return blanks; | |
}; | |
exports.COUNTIF = function(range, criteria) { | |
range = utils.flatten(range); | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
if (isWildcard) { | |
return range.length; | |
} | |
var matches = 0; | |
var tokenizedCriteria = evalExpression.parse(criteria + ''); | |
for (var i = 0; i < range.length; i++) { | |
var value = range[i]; | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
if (evalExpression.compute(tokens)) { | |
matches++; | |
} | |
} | |
return matches; | |
}; | |
exports.COUNTIFS = function() { | |
var args = utils.argsToArray(arguments); | |
var results = new Array(utils.flatten(args[0]).length); | |
for (var i = 0; i < results.length; i++) { | |
results[i] = true; | |
} | |
for (i = 0; i < args.length; i += 2) { | |
var range = utils.flatten(args[i]); | |
var criteria = args[i + 1]; | |
var isWildcard = criteria === void 0 || criteria === '*'; | |
if (!isWildcard) { | |
var tokenizedCriteria = evalExpression.parse(criteria + ''); | |
for (var j = 0; j < range.length; j++) { | |
var value = range[j]; | |
var tokens = [evalExpression.createToken(value, evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
results[j] = results[j] && evalExpression.compute(tokens); | |
} | |
} | |
} | |
var result = 0; | |
for (i = 0; i < results.length; i++) { | |
if (results[i]) { | |
result++; | |
} | |
} | |
return result; | |
}; | |
exports.COUNTUNIQUE = function () { | |
return misc.UNIQUE.apply(null, utils.flatten(arguments)).length; | |
}; | |
exports.COVARIANCE = {}; | |
exports.COVARIANCE.P = function(array1, array2) { | |
array1 = utils.parseNumberArray(utils.flatten(array1)); | |
array2 = utils.parseNumberArray(utils.flatten(array2)); | |
if (utils.anyIsError(array1, array2)) { | |
return error.value; | |
} | |
var mean1 = jStat.mean(array1); | |
var mean2 = jStat.mean(array2); | |
var result = 0; | |
var n = array1.length; | |
for (var i = 0; i < n; i++) { | |
result += (array1[i] - mean1) * (array2[i] - mean2); | |
} | |
return result / n; | |
}; | |
exports.COVARIANCE.S = function(array1, array2) { | |
array1 = utils.parseNumberArray(utils.flatten(array1)); | |
array2 = utils.parseNumberArray(utils.flatten(array2)); | |
if (utils.anyIsError(array1, array2)) { | |
return error.value; | |
} | |
return jStat.covariance(array1, array2); | |
}; | |
exports.DEVSQ = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var mean = jStat.mean(range); | |
var result = 0; | |
for (var i = 0; i < range.length; i++) { | |
result += Math.pow((range[i] - mean), 2); | |
} | |
return result; | |
}; | |
exports.EXPON = {}; | |
exports.EXPON.DIST = function(x, lambda, cumulative) { | |
x = utils.parseNumber(x); | |
lambda = utils.parseNumber(lambda); | |
if (utils.anyIsError(x, lambda)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.exponential.cdf(x, lambda) : jStat.exponential.pdf(x, lambda); | |
}; | |
exports.F = {}; | |
exports.F.DIST = function(x, d1, d2, cumulative) { | |
x = utils.parseNumber(x); | |
d1 = utils.parseNumber(d1); | |
d2 = utils.parseNumber(d2); | |
if (utils.anyIsError(x, d1, d2)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.centralF.cdf(x, d1, d2) : jStat.centralF.pdf(x, d1, d2); | |
}; | |
exports.F.DIST.RT = function(x, d1, d2) { | |
if (arguments.length !== 3) { | |
return error.na; | |
} | |
if (x < 0 || d1 < 1 || d2 < 1) { | |
return error.num; | |
} | |
if ((typeof x !== 'number') || (typeof d1 !== 'number') || (typeof d2 !== 'number')) { | |
return error.value; | |
} | |
return 1 - jStat.centralF.cdf(x, d1, d2); | |
}; | |
exports.F.INV = function(probability, d1, d2) { | |
probability = utils.parseNumber(probability); | |
d1 = utils.parseNumber(d1); | |
d2 = utils.parseNumber(d2); | |
if (utils.anyIsError(probability, d1, d2)) { | |
return error.value; | |
} | |
if (probability <= 0.0 || probability > 1.0) { | |
return error.num; | |
} | |
return jStat.centralF.inv(probability, d1, d2); | |
}; | |
exports.F.INV.RT = function(p, d1, d2) { | |
if (arguments.length !== 3) { | |
return error.na; | |
} | |
if (p < 0 || p > 1 || d1 < 1 || d1 > Math.pow(10, 10) || d2 < 1 || d2 > Math.pow(10, 10)) { | |
return error.num; | |
} | |
if ((typeof p !== 'number') || (typeof d1 !== 'number') || (typeof d2 !== 'number')) { | |
return error.value; | |
} | |
return jStat.centralF.inv(1.0 - p, d1, d2); | |
}; | |
exports.F.TEST = function(array1, array2) { | |
if (!array1 || !array2) { | |
return error.na; | |
} | |
if (!(array1 instanceof Array) || !(array2 instanceof Array)) { | |
return error.na; | |
} | |
if (array1.length < 2 || array2.length < 2) { | |
return error.div0; | |
} | |
var sumOfSquares = function(values, x1) { | |
var sum = 0; | |
for (var i = 0; i < values.length; i++) { | |
sum +=Math.pow((values[i] - x1), 2); | |
} | |
return sum; | |
}; | |
var x1 = mathTrig.SUM(array1) / array1.length; | |
var x2 = mathTrig.SUM(array2) / array2.length; | |
var sum1 = sumOfSquares(array1, x1) / (array1.length - 1); | |
var sum2 = sumOfSquares(array2, x2) / (array2.length - 1); | |
return sum1 / sum2; | |
}; | |
exports.FISHER = function(x) { | |
x = utils.parseNumber(x); | |
if (x instanceof Error) { | |
return x; | |
} | |
return Math.log((1 + x) / (1 - x)) / 2; | |
}; | |
exports.FISHERINV = function(y) { | |
y = utils.parseNumber(y); | |
if (y instanceof Error) { | |
return y; | |
} | |
var e2y = Math.exp(2 * y); | |
return (e2y - 1) / (e2y + 1); | |
}; | |
exports.FORECAST = function(x, data_y, data_x) { | |
x = utils.parseNumber(x); | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(x, data_y, data_x)) { | |
return error.value; | |
} | |
var xmean = jStat.mean(data_x); | |
var ymean = jStat.mean(data_y); | |
var n = data_x.length; | |
var num = 0; | |
var den = 0; | |
for (var i = 0; i < n; i++) { | |
num += (data_x[i] - xmean) * (data_y[i] - ymean); | |
den += Math.pow(data_x[i] - xmean, 2); | |
} | |
var b = num / den; | |
var a = ymean - b * xmean; | |
return a + b * x; | |
}; | |
exports.FREQUENCY = function(data, bins) { | |
data = utils.parseNumberArray(utils.flatten(data)); | |
bins = utils.parseNumberArray(utils.flatten(bins)); | |
if (utils.anyIsError(data, bins)) { | |
return error.value; | |
} | |
var n = data.length; | |
var b = bins.length; | |
var r = []; | |
for (var i = 0; i <= b; i++) { | |
r[i] = 0; | |
for (var j = 0; j < n; j++) { | |
if (i === 0) { | |
if (data[j] <= bins[0]) { | |
r[0] += 1; | |
} | |
} else if (i < b) { | |
if (data[j] > bins[i - 1] && data[j] <= bins[i]) { | |
r[i] += 1; | |
} | |
} else if (i === b) { | |
if (data[j] > bins[b - 1]) { | |
r[b] += 1; | |
} | |
} | |
} | |
} | |
return r; | |
}; | |
exports.GAMMA = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
if (number === 0) { | |
return error.num; | |
} | |
if (parseInt(number, 10) === number && number < 0) { | |
return error.num; | |
} | |
return jStat.gammafn(number); | |
}; | |
exports.GAMMA.DIST = function(value, alpha, beta, cumulative) { | |
if (arguments.length !== 4) { | |
return error.na; | |
} | |
if (value < 0 || alpha <= 0 || beta <= 0) { | |
return error.value; | |
} | |
if ((typeof value !== 'number') || (typeof alpha !== 'number') || (typeof beta !== 'number')) { | |
return error.value; | |
} | |
return cumulative ? jStat.gamma.cdf(value, alpha, beta, true) : jStat.gamma.pdf(value, alpha, beta, false); | |
}; | |
exports.GAMMA.INV = function(probability, alpha, beta) { | |
if (arguments.length !== 3) { | |
return error.na; | |
} | |
if (probability < 0 || probability > 1 || alpha <= 0 || beta <= 0) { | |
return error.num; | |
} | |
if ((typeof probability !== 'number') || (typeof alpha !== 'number') || (typeof beta !== 'number')) { | |
return error.value; | |
} | |
return jStat.gamma.inv(probability, alpha, beta); | |
}; | |
exports.GAMMALN = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return jStat.gammaln(number); | |
}; | |
exports.GAMMALN.PRECISE = function(x) { | |
if (arguments.length !== 1) { | |
return error.na; | |
} | |
if (x <= 0) { | |
return error.num; | |
} | |
if (typeof x !== 'number') { | |
return error.value; | |
} | |
return jStat.gammaln(x); | |
}; | |
exports.GAUSS = function(z) { | |
z = utils.parseNumber(z); | |
if (z instanceof Error) { | |
return z; | |
} | |
return jStat.normal.cdf(z, 0, 1) - 0.5; | |
}; | |
exports.GEOMEAN = function() { | |
var args = utils.parseNumberArray(utils.flatten(arguments)); | |
if (args instanceof Error) { | |
return args; | |
} | |
return jStat.geomean(args); | |
}; | |
exports.GROWTH = function(known_y, known_x, new_x, use_const) { | |
// Credits: Ilmari Karonen (http://stackoverflow.com/questions/14161990/how-to-implement-growth-function-in-javascript) | |
known_y = utils.parseNumberArray(known_y); | |
if (known_y instanceof Error) { | |
return known_y; | |
} | |
// Default values for optional parameters: | |
var i; | |
if (known_x === undefined) { | |
known_x = []; | |
for (i = 1; i <= known_y.length; i++) { | |
known_x.push(i); | |
} | |
} | |
if (new_x === undefined) { | |
new_x = []; | |
for (i = 1; i <= known_y.length; i++) { | |
new_x.push(i); | |
} | |
} | |
known_x = utils.parseNumberArray(known_x); | |
new_x = utils.parseNumberArray(new_x); | |
if (utils.anyIsError(known_x, new_x)) { | |
return error.value; | |
} | |
if (use_const === undefined) { | |
use_const = true; | |
} | |
// Calculate sums over the data: | |
var n = known_y.length; | |
var avg_x = 0; | |
var avg_y = 0; | |
var avg_xy = 0; | |
var avg_xx = 0; | |
for (i = 0; i < n; i++) { | |
var x = known_x[i]; | |
var y = Math.log(known_y[i]); | |
avg_x += x; | |
avg_y += y; | |
avg_xy += x * y; | |
avg_xx += x * x; | |
} | |
avg_x /= n; | |
avg_y /= n; | |
avg_xy /= n; | |
avg_xx /= n; | |
// Compute linear regression coefficients: | |
var beta; | |
var alpha; | |
if (use_const) { | |
beta = (avg_xy - avg_x * avg_y) / (avg_xx - avg_x * avg_x); | |
alpha = avg_y - beta * avg_x; | |
} else { | |
beta = avg_xy / avg_xx; | |
alpha = 0; | |
} | |
// Compute and return result array: | |
var new_y = []; | |
for (i = 0; i < new_x.length; i++) { | |
new_y.push(Math.exp(alpha + beta * new_x[i])); | |
} | |
return new_y; | |
}; | |
exports.HARMEAN = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var n = range.length; | |
var den = 0; | |
for (var i = 0; i < n; i++) { | |
den += 1 / range[i]; | |
} | |
return n / den; | |
}; | |
exports.HYPGEOM = {}; | |
exports.HYPGEOM.DIST = function(x, n, M, N, cumulative) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
M = utils.parseNumber(M); | |
N = utils.parseNumber(N); | |
if (utils.anyIsError(x, n, M, N)) { | |
return error.value; | |
} | |
function pdf(x, n, M, N) { | |
return mathTrig.COMBIN(M, x) * mathTrig.COMBIN(N - M, n - x) / mathTrig.COMBIN(N, n); | |
} | |
function cdf(x, n, M, N) { | |
var result = 0; | |
for (var i = 0; i <= x; i++) { | |
result += pdf(i, n, M, N); | |
} | |
return result; | |
} | |
return (cumulative) ? cdf(x, n, M, N) : pdf(x, n, M, N); | |
}; | |
exports.INTERCEPT = function(known_y, known_x) { | |
known_y = utils.parseNumberArray(known_y); | |
known_x = utils.parseNumberArray(known_x); | |
if (utils.anyIsError(known_y, known_x)) { | |
return error.value; | |
} | |
if (known_y.length !== known_x.length) { | |
return error.na; | |
} | |
return exports.FORECAST(0, known_y, known_x); | |
}; | |
exports.KURT = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var mean = jStat.mean(range); | |
var n = range.length; | |
var sigma = 0; | |
for (var i = 0; i < n; i++) { | |
sigma += Math.pow(range[i] - mean, 4); | |
} | |
sigma = sigma / Math.pow(jStat.stdev(range, true), 4); | |
return ((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * sigma - 3 * (n - 1) * (n - 1) / ((n - 2) * (n - 3)); | |
}; | |
exports.LARGE = function(range, k) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(range, k)) { | |
return range; | |
} | |
return range.sort(function(a, b) { | |
return b - a; | |
})[k - 1]; | |
}; | |
exports.LINEST = function(data_y, data_x) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(data_y, data_x)) { | |
return error.value; | |
} | |
var ymean = jStat.mean(data_y); | |
var xmean = jStat.mean(data_x); | |
var n = data_x.length; | |
var num = 0; | |
var den = 0; | |
for (var i = 0; i < n; i++) { | |
num += (data_x[i] - xmean) * (data_y[i] - ymean); | |
den += Math.pow(data_x[i] - xmean, 2); | |
} | |
var m = num / den; | |
var b = ymean - m * xmean; | |
return [m, b]; | |
}; | |
// According to Microsoft: | |
// http://office.microsoft.com/en-us/starter-help/logest-function-HP010342665.aspx | |
// LOGEST returns are based on the following linear model: | |
// ln y = x1 ln m1 + ... + xn ln mn + ln b | |
exports.LOGEST = function(data_y, data_x) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(data_y, data_x)) { | |
return error.value; | |
} | |
for (var i = 0; i < data_y.length; i ++) { | |
data_y[i] = Math.log(data_y[i]); | |
} | |
var result = exports.LINEST(data_y, data_x); | |
result[0] = Math.round(Math.exp(result[0])*1000000)/1000000; | |
result[1] = Math.round(Math.exp(result[1])*1000000)/1000000; | |
return result; | |
}; | |
exports.LOGNORM = {}; | |
exports.LOGNORM.DIST = function(x, mean, sd, cumulative) { | |
x = utils.parseNumber(x); | |
mean = utils.parseNumber(mean); | |
sd = utils.parseNumber(sd); | |
if (utils.anyIsError(x, mean, sd)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.lognormal.cdf(x, mean, sd) : jStat.lognormal.pdf(x, mean, sd); | |
}; | |
exports.LOGNORM.INV = function(probability, mean, sd) { | |
probability = utils.parseNumber(probability); | |
mean = utils.parseNumber(mean); | |
sd = utils.parseNumber(sd); | |
if (utils.anyIsError(probability, mean, sd)) { | |
return error.value; | |
} | |
return jStat.lognormal.inv(probability, mean, sd); | |
}; | |
exports.MAX = function() { | |
var range = utils.numbers(utils.flatten(arguments)); | |
return (range.length === 0) ? 0 : Math.max.apply(Math, range); | |
}; | |
exports.MAXA = function() { | |
var range = utils.arrayValuesToNumbers(utils.flatten(arguments)); | |
return (range.length === 0) ? 0 : Math.max.apply(Math, range); | |
}; | |
exports.MEDIAN = function() { | |
var range = utils.arrayValuesToNumbers(utils.flatten(arguments)); | |
var result = jStat.median(range); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.MIN = function() { | |
var range = utils.numbers(utils.flatten(arguments)); | |
return (range.length === 0) ? 0 : Math.min.apply(Math, range); | |
}; | |
exports.MINA = function() { | |
var range = utils.arrayValuesToNumbers(utils.flatten(arguments)); | |
return (range.length === 0) ? 0 : Math.min.apply(Math, range); | |
}; | |
exports.MODE = {}; | |
exports.MODE.MULT = function() { | |
// Credits: Roönaän | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var n = range.length; | |
var count = {}; | |
var maxItems = []; | |
var max = 0; | |
var currentItem; | |
for (var i = 0; i < n; i++) { | |
currentItem = range[i]; | |
count[currentItem] = count[currentItem] ? count[currentItem] + 1 : 1; | |
if (count[currentItem] > max) { | |
max = count[currentItem]; | |
maxItems = []; | |
} | |
if (count[currentItem] === max) { | |
maxItems[maxItems.length] = currentItem; | |
} | |
} | |
return maxItems; | |
}; | |
exports.MODE.SNGL = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
return exports.MODE.MULT(range).sort(function(a, b) { | |
return a - b; | |
})[0]; | |
}; | |
exports.NEGBINOM = {}; | |
exports.NEGBINOM.DIST = function(k, r, p, cumulative) { | |
k = utils.parseNumber(k); | |
r = utils.parseNumber(r); | |
p = utils.parseNumber(p); | |
if (utils.anyIsError(k, r, p)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.negbin.cdf(k, r, p) : jStat.negbin.pdf(k, r, p); | |
}; | |
exports.NORM = {}; | |
exports.NORM.DIST = function(x, mean, sd, cumulative) { | |
x = utils.parseNumber(x); | |
mean = utils.parseNumber(mean); | |
sd = utils.parseNumber(sd); | |
if (utils.anyIsError(x, mean, sd)) { | |
return error.value; | |
} | |
if (sd <= 0) { | |
return error.num; | |
} | |
// Return normal distribution computed by jStat [http://jstat.org] | |
return (cumulative) ? jStat.normal.cdf(x, mean, sd) : jStat.normal.pdf(x, mean, sd); | |
}; | |
exports.NORM.INV = function(probability, mean, sd) { | |
probability = utils.parseNumber(probability); | |
mean = utils.parseNumber(mean); | |
sd = utils.parseNumber(sd); | |
if (utils.anyIsError(probability, mean, sd)) { | |
return error.value; | |
} | |
return jStat.normal.inv(probability, mean, sd); | |
}; | |
exports.NORM.S = {}; | |
exports.NORM.S.DIST = function(z, cumulative) { | |
z = utils.parseNumber(z); | |
if (z instanceof Error) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.normal.cdf(z, 0, 1) : jStat.normal.pdf(z, 0, 1); | |
}; | |
exports.NORM.S.INV = function(probability) { | |
probability = utils.parseNumber(probability); | |
if (probability instanceof Error) { | |
return error.value; | |
} | |
return jStat.normal.inv(probability, 0, 1); | |
}; | |
exports.PEARSON = function(data_x, data_y) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(data_y, data_x)) { | |
return error.value; | |
} | |
var xmean = jStat.mean(data_x); | |
var ymean = jStat.mean(data_y); | |
var n = data_x.length; | |
var num = 0; | |
var den1 = 0; | |
var den2 = 0; | |
for (var i = 0; i < n; i++) { | |
num += (data_x[i] - xmean) * (data_y[i] - ymean); | |
den1 += Math.pow(data_x[i] - xmean, 2); | |
den2 += Math.pow(data_y[i] - ymean, 2); | |
} | |
return num / Math.sqrt(den1 * den2); | |
}; | |
exports.PERCENTILE = {}; | |
exports.PERCENTILE.EXC = function(array, k) { | |
array = utils.parseNumberArray(utils.flatten(array)); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(array, k)) { | |
return error.value; | |
} | |
array = array.sort(function(a, b) { | |
{ | |
return a - b; | |
} | |
}); | |
var n = array.length; | |
if (k < 1 / (n + 1) || k > 1 - 1 / (n + 1)) { | |
return error.num; | |
} | |
var l = k * (n + 1) - 1; | |
var fl = Math.floor(l); | |
return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); | |
}; | |
exports.PERCENTILE.INC = function(array, k) { | |
array = utils.parseNumberArray(utils.flatten(array)); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(array, k)) { | |
return error.value; | |
} | |
array = array.sort(function(a, b) { | |
return a - b; | |
}); | |
var n = array.length; | |
var l = k * (n - 1); | |
var fl = Math.floor(l); | |
return utils.cleanFloat((l === fl) ? array[l] : array[fl] + (l - fl) * (array[fl + 1] - array[fl])); | |
}; | |
exports.PERCENTRANK = {}; | |
exports.PERCENTRANK.EXC = function(array, x, significance) { | |
significance = (significance === undefined) ? 3 : significance; | |
array = utils.parseNumberArray(utils.flatten(array)); | |
x = utils.parseNumber(x); | |
significance = utils.parseNumber(significance); | |
if (utils.anyIsError(array, x, significance)) { | |
return error.value; | |
} | |
array = array.sort(function(a, b) { | |
return a - b; | |
}); | |
var uniques = misc.UNIQUE.apply(null, array); | |
var n = array.length; | |
var m = uniques.length; | |
var power = Math.pow(10, significance); | |
var result = 0; | |
var match = false; | |
var i = 0; | |
while (!match && i < m) { | |
if (x === uniques[i]) { | |
result = (array.indexOf(uniques[i]) + 1) / (n + 1); | |
match = true; | |
} else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { | |
result = (array.indexOf(uniques[i]) + 1 + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n + 1); | |
match = true; | |
} | |
i++; | |
} | |
return Math.floor(result * power) / power; | |
}; | |
exports.PERCENTRANK.INC = function(array, x, significance) { | |
significance = (significance === undefined) ? 3 : significance; | |
array = utils.parseNumberArray(utils.flatten(array)); | |
x = utils.parseNumber(x); | |
significance = utils.parseNumber(significance); | |
if (utils.anyIsError(array, x, significance)) { | |
return error.value; | |
} | |
array = array.sort(function(a, b) { | |
return a - b; | |
}); | |
var uniques = misc.UNIQUE.apply(null, array); | |
var n = array.length; | |
var m = uniques.length; | |
var power = Math.pow(10, significance); | |
var result = 0; | |
var match = false; | |
var i = 0; | |
while (!match && i < m) { | |
if (x === uniques[i]) { | |
result = array.indexOf(uniques[i]) / (n - 1); | |
match = true; | |
} else if (x >= uniques[i] && (x < uniques[i + 1] || i === m - 1)) { | |
result = (array.indexOf(uniques[i]) + (x - uniques[i]) / (uniques[i + 1] - uniques[i])) / (n - 1); | |
match = true; | |
} | |
i++; | |
} | |
return Math.floor(result * power) / power; | |
}; | |
exports.PERMUT = function(number, number_chosen) { | |
number = utils.parseNumber(number); | |
number_chosen = utils.parseNumber(number_chosen); | |
if (utils.anyIsError(number, number_chosen)) { | |
return error.value; | |
} | |
return mathTrig.FACT(number) / mathTrig.FACT(number - number_chosen); | |
}; | |
exports.PERMUTATIONA = function(number, number_chosen) { | |
number = utils.parseNumber(number); | |
number_chosen = utils.parseNumber(number_chosen); | |
if (utils.anyIsError(number, number_chosen)) { | |
return error.value; | |
} | |
return Math.pow(number, number_chosen); | |
}; | |
exports.PHI = function(x) { | |
x = utils.parseNumber(x); | |
if (x instanceof Error) { | |
return error.value; | |
} | |
return Math.exp(-0.5 * x * x) / SQRT2PI; | |
}; | |
exports.POISSON = {}; | |
exports.POISSON.DIST = function(x, mean, cumulative) { | |
x = utils.parseNumber(x); | |
mean = utils.parseNumber(mean); | |
if (utils.anyIsError(x, mean)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.poisson.cdf(x, mean) : jStat.poisson.pdf(x, mean); | |
}; | |
exports.PROB = function(range, probability, lower, upper) { | |
if (lower === undefined) { | |
return 0; | |
} | |
upper = (upper === undefined) ? lower : upper; | |
range = utils.parseNumberArray(utils.flatten(range)); | |
probability = utils.parseNumberArray(utils.flatten(probability)); | |
lower = utils.parseNumber(lower); | |
upper = utils.parseNumber(upper); | |
if (utils.anyIsError(range, probability, lower, upper)) { | |
return error.value; | |
} | |
if (lower === upper) { | |
return (range.indexOf(lower) >= 0) ? probability[range.indexOf(lower)] : 0; | |
} | |
var sorted = range.sort(function(a, b) { | |
return a - b; | |
}); | |
var n = sorted.length; | |
var result = 0; | |
for (var i = 0; i < n; i++) { | |
if (sorted[i] >= lower && sorted[i] <= upper) { | |
result += probability[range.indexOf(sorted[i])]; | |
} | |
} | |
return result; | |
}; | |
exports.QUARTILE = {}; | |
exports.QUARTILE.EXC = function(range, quart) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
quart = utils.parseNumber(quart); | |
if (utils.anyIsError(range, quart)) { | |
return error.value; | |
} | |
switch (quart) { | |
case 1: | |
return exports.PERCENTILE.EXC(range, 0.25); | |
case 2: | |
return exports.PERCENTILE.EXC(range, 0.5); | |
case 3: | |
return exports.PERCENTILE.EXC(range, 0.75); | |
default: | |
return error.num; | |
} | |
}; | |
exports.QUARTILE.INC = function(range, quart) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
quart = utils.parseNumber(quart); | |
if (utils.anyIsError(range, quart)) { | |
return error.value; | |
} | |
switch (quart) { | |
case 1: | |
return exports.PERCENTILE.INC(range, 0.25); | |
case 2: | |
return exports.PERCENTILE.INC(range, 0.5); | |
case 3: | |
return exports.PERCENTILE.INC(range, 0.75); | |
default: | |
return error.num; | |
} | |
}; | |
exports.RANK = {}; | |
exports.RANK.AVG = function(number, range, order) { | |
number = utils.parseNumber(number); | |
range = utils.parseNumberArray(utils.flatten(range)); | |
if (utils.anyIsError(number, range)) { | |
return error.value; | |
} | |
range = utils.flatten(range); | |
order = order || false; | |
var sort = (order) ? function(a, b) { | |
return a - b; | |
} : function(a, b) { | |
return b - a; | |
}; | |
range = range.sort(sort); | |
var length = range.length; | |
var count = 0; | |
for (var i = 0; i < length; i++) { | |
if (range[i] === number) { | |
count++; | |
} | |
} | |
return (count > 1) ? (2 * range.indexOf(number) + count + 1) / 2 : range.indexOf(number) + 1; | |
}; | |
exports.RANK.EQ = function(number, range, order) { | |
number = utils.parseNumber(number); | |
range = utils.parseNumberArray(utils.flatten(range)); | |
if (utils.anyIsError(number, range)) { | |
return error.value; | |
} | |
order = order || false; | |
var sort = (order) ? function(a, b) { | |
return a - b; | |
} : function(a, b) { | |
return b - a; | |
}; | |
range = range.sort(sort); | |
return range.indexOf(number) + 1; | |
}; | |
exports.ROW = function(matrix, index) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
if (index < 0) { | |
return error.num; | |
} | |
if (!(matrix instanceof Array) || (typeof index !== 'number')) { | |
return error.value; | |
} | |
if (matrix.length === 0) { | |
return undefined; | |
} | |
return jStat.row(matrix, index); | |
}; | |
exports.ROWS = function(matrix) { | |
if (arguments.length !== 1) { | |
return error.na; | |
} | |
if (!(matrix instanceof Array)) { | |
return error.value; | |
} | |
if (matrix.length === 0) { | |
return 0; | |
} | |
return jStat.rows(matrix); | |
}; | |
exports.RSQ = function(data_x, data_y) { // no need to flatten here, PEARSON will take care of that | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
if (utils.anyIsError(data_x, data_y)) { | |
return error.value; | |
} | |
return Math.pow(exports.PEARSON(data_x, data_y), 2); | |
}; | |
exports.SKEW = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var mean = jStat.mean(range); | |
var n = range.length; | |
var sigma = 0; | |
for (var i = 0; i < n; i++) { | |
sigma += Math.pow(range[i] - mean, 3); | |
} | |
return n * sigma / ((n - 1) * (n - 2) * Math.pow(jStat.stdev(range, true), 3)); | |
}; | |
exports.SKEW.P = function() { | |
var range = utils.parseNumberArray(utils.flatten(arguments)); | |
if (range instanceof Error) { | |
return range; | |
} | |
var mean = jStat.mean(range); | |
var n = range.length; | |
var m2 = 0; | |
var m3 = 0; | |
for (var i = 0; i < n; i++) { | |
m3 += Math.pow(range[i] - mean, 3); | |
m2 += Math.pow(range[i] - mean, 2); | |
} | |
m3 = m3 / n; | |
m2 = m2 / n; | |
return m3 / Math.pow(m2, 3 / 2); | |
}; | |
exports.SLOPE = function(data_y, data_x) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(data_y, data_x)) { | |
return error.value; | |
} | |
var xmean = jStat.mean(data_x); | |
var ymean = jStat.mean(data_y); | |
var n = data_x.length; | |
var num = 0; | |
var den = 0; | |
for (var i = 0; i < n; i++) { | |
num += (data_x[i] - xmean) * (data_y[i] - ymean); | |
den += Math.pow(data_x[i] - xmean, 2); | |
} | |
return num / den; | |
}; | |
exports.SMALL = function(range, k) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
k = utils.parseNumber(k); | |
if (utils.anyIsError(range, k)) { | |
return range; | |
} | |
return range.sort(function(a, b) { | |
return a - b; | |
})[k - 1]; | |
}; | |
exports.STANDARDIZE = function(x, mean, sd) { | |
x = utils.parseNumber(x); | |
mean = utils.parseNumber(mean); | |
sd = utils.parseNumber(sd); | |
if (utils.anyIsError(x, mean, sd)) { | |
return error.value; | |
} | |
return (x - mean) / sd; | |
}; | |
exports.STDEV = {}; | |
exports.STDEV.P = function() { | |
var v = exports.VAR.P.apply(this, arguments); | |
var result = Math.sqrt(v); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.STDEV.S = function() { | |
var v = exports.VAR.S.apply(this, arguments); | |
var result = Math.sqrt(v); | |
return result; | |
}; | |
exports.STDEVA = function() { | |
var v = exports.VARA.apply(this, arguments); | |
var result = Math.sqrt(v); | |
return result; | |
}; | |
exports.STDEVPA = function() { | |
var v = exports.VARPA.apply(this, arguments); | |
var result = Math.sqrt(v); | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.STEYX = function(data_y, data_x) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
if (utils.anyIsError(data_y, data_x)) { | |
return error.value; | |
} | |
var xmean = jStat.mean(data_x); | |
var ymean = jStat.mean(data_y); | |
var n = data_x.length; | |
var lft = 0; | |
var num = 0; | |
var den = 0; | |
for (var i = 0; i < n; i++) { | |
lft += Math.pow(data_y[i] - ymean, 2); | |
num += (data_x[i] - xmean) * (data_y[i] - ymean); | |
den += Math.pow(data_x[i] - xmean, 2); | |
} | |
return Math.sqrt((lft - num * num / den) / (n - 2)); | |
}; | |
exports.TRANSPOSE = function(matrix) { | |
if (!matrix) { | |
return error.na; | |
} | |
return jStat.transpose(matrix); | |
}; | |
exports.T = text.T; | |
exports.T.DIST = function(x, df, cumulative) { | |
x = utils.parseNumber(x); | |
df = utils.parseNumber(df); | |
if (utils.anyIsError(x, df)) { | |
return error.value; | |
} | |
return (cumulative) ? jStat.studentt.cdf(x, df) : jStat.studentt.pdf(x, df); | |
}; | |
exports.T.DIST['2T'] = function(x, df) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
if (x < 0 || df < 1) { | |
return error.num; | |
} | |
if ((typeof x !== 'number') || (typeof df !== 'number')) { | |
return error.value; | |
} | |
return (1 - jStat.studentt.cdf(x , df)) * 2; | |
}; | |
exports.T.DIST.RT = function(x, df) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
if (x < 0 || df < 1) { | |
return error.num; | |
} | |
if ((typeof x !== 'number') || (typeof df !== 'number')) { | |
return error.value; | |
} | |
return 1 - jStat.studentt.cdf(x , df); | |
}; | |
exports.T.INV = function(probability, df) { | |
probability = utils.parseNumber(probability); | |
df = utils.parseNumber(df); | |
if (utils.anyIsError(probability, df)) { | |
return error.value; | |
} | |
return jStat.studentt.inv(probability, df); | |
}; | |
exports.T.INV['2T'] = function(probability, df) { | |
probability = utils.parseNumber(probability); | |
df = utils.parseNumber(df); | |
if (probability <= 0 || probability > 1 || df < 1) { | |
return error.num; | |
} | |
if (utils.anyIsError(probability, df)) { | |
return error.value; | |
} | |
return Math.abs(jStat.studentt.inv(probability/2, df)); | |
}; | |
// The algorithm can be found here: | |
// http://www.chem.uoa.gr/applets/AppletTtest/Appl_Ttest2.html | |
exports.T.TEST = function(data_x, data_y) { | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
if (utils.anyIsError(data_x, data_y)) { | |
return error.value; | |
} | |
var mean_x = jStat.mean(data_x); | |
var mean_y = jStat.mean(data_y); | |
var s_x = 0; | |
var s_y = 0; | |
var i; | |
for (i = 0; i < data_x.length; i++) { | |
s_x += Math.pow(data_x[i] - mean_x, 2); | |
} | |
for (i = 0; i < data_y.length; i++) { | |
s_y += Math.pow(data_y[i] - mean_y, 2); | |
} | |
s_x = s_x / (data_x.length-1); | |
s_y = s_y / (data_y.length-1); | |
var t = Math.abs(mean_x - mean_y) / Math.sqrt(s_x/data_x.length + s_y/data_y.length); | |
return exports.T.DIST['2T'](t, data_x.length+data_y.length-2); | |
}; | |
exports.TREND = function(data_y, data_x, new_data_x) { | |
data_y = utils.parseNumberArray(utils.flatten(data_y)); | |
data_x = utils.parseNumberArray(utils.flatten(data_x)); | |
new_data_x = utils.parseNumberArray(utils.flatten(new_data_x)); | |
if (utils.anyIsError(data_y, data_x, new_data_x)) { | |
return error.value; | |
} | |
var linest = exports.LINEST(data_y, data_x); | |
var m = linest[0]; | |
var b = linest[1]; | |
var result = []; | |
new_data_x.forEach(function(x) { | |
result.push(m * x + b); | |
}); | |
return result; | |
}; | |
exports.TRIMMEAN = function(range, percent) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
percent = utils.parseNumber(percent); | |
if (utils.anyIsError(range, percent)) { | |
return error.value; | |
} | |
var trim = mathTrig.FLOOR(range.length * percent, 2) / 2; | |
return jStat.mean(utils.initial(utils.rest(range.sort(function(a, b) { | |
return a - b; | |
}), trim), trim)); | |
}; | |
exports.VAR = {}; | |
exports.VAR.P = function() { | |
var range = utils.numbers(utils.flatten(arguments)); | |
var n = range.length; | |
var sigma = 0; | |
var mean = exports.AVERAGE(range); | |
var result; | |
for (var i = 0; i < n; i++) { | |
sigma += Math.pow(range[i] - mean, 2); | |
} | |
result = sigma / n; | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.VAR.S = function() { | |
var range = utils.numbers(utils.flatten(arguments)); | |
var n = range.length; | |
var sigma = 0; | |
var mean = exports.AVERAGE(range); | |
for (var i = 0; i < n; i++) { | |
sigma += Math.pow(range[i] - mean, 2); | |
} | |
return sigma / (n - 1); | |
}; | |
exports.VARA = function() { | |
var range = utils.flatten(arguments); | |
var n = range.length; | |
var sigma = 0; | |
var count = 0; | |
var mean = exports.AVERAGEA(range); | |
for (var i = 0; i < n; i++) { | |
var el = range[i]; | |
if (typeof el === 'number') { | |
sigma += Math.pow(el - mean, 2); | |
} else if (el === true) { | |
sigma += Math.pow(1 - mean, 2); | |
} else { | |
sigma += Math.pow(0 - mean, 2); | |
} | |
if (el !== null) { | |
count++; | |
} | |
} | |
return sigma / (count - 1); | |
}; | |
exports.VARPA = function() { | |
var range = utils.flatten(arguments); | |
var n = range.length; | |
var sigma = 0; | |
var count = 0; | |
var mean = exports.AVERAGEA(range); | |
var result; | |
for (var i = 0; i < n; i++) { | |
var el = range[i]; | |
if (typeof el === 'number') { | |
sigma += Math.pow(el - mean, 2); | |
} else if (el === true) { | |
sigma += Math.pow(1 - mean, 2); | |
} else { | |
sigma += Math.pow(0 - mean, 2); | |
} | |
if (el !== null) { | |
count++; | |
} | |
} | |
result = sigma / count; | |
if (isNaN(result)) { | |
result = error.num; | |
} | |
return result; | |
}; | |
exports.WEIBULL = {}; | |
exports.WEIBULL.DIST = function(x, alpha, beta, cumulative) { | |
x = utils.parseNumber(x); | |
alpha = utils.parseNumber(alpha); | |
beta = utils.parseNumber(beta); | |
if (utils.anyIsError(x, alpha, beta)) { | |
return error.value; | |
} | |
return (cumulative) ? 1 - Math.exp(-Math.pow(x / beta, alpha)) : Math.pow(x, alpha - 1) * Math.exp(-Math.pow(x / beta, alpha)) * alpha / Math.pow(beta, alpha); | |
}; | |
exports.Z = {}; | |
exports.Z.TEST = function(range, x, sd) { | |
range = utils.parseNumberArray(utils.flatten(range)); | |
x = utils.parseNumber(x); | |
if (utils.anyIsError(range, x)) { | |
return error.value; | |
} | |
sd = sd || exports.STDEV.S(range); | |
var n = range.length; | |
return 1 - exports.NORM.S.DIST((exports.AVERAGE(range) - x) / (sd / Math.sqrt(n)), true); | |
}; | |
/***/ }), | |
/* 6 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var utils = __webpack_require__(1); | |
var error = __webpack_require__(0); | |
//TODO | |
exports.ASC = function() { | |
throw new Error('ASC is not implemented'); | |
}; | |
//TODO | |
exports.BAHTTEXT = function() { | |
throw new Error('BAHTTEXT is not implemented'); | |
}; | |
exports.CHAR = function(number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return String.fromCharCode(number); | |
}; | |
exports.CLEAN = function(text) { | |
text = text || ''; | |
var re = /[\0-\x1F]/g; | |
return text.replace(re, ""); | |
}; | |
exports.CODE = function(text) { | |
text = text || ''; | |
var result = text.charCodeAt(0); | |
if (isNaN(result)) { | |
result = error.na; | |
} | |
return result; | |
}; | |
exports.CONCATENATE = function() { | |
var args = utils.flatten(arguments); | |
var trueFound = 0; | |
while ((trueFound = args.indexOf(true)) > -1) { | |
args[trueFound] = 'TRUE'; | |
} | |
var falseFound = 0; | |
while ((falseFound = args.indexOf(false)) > -1) { | |
args[falseFound] = 'FALSE'; | |
} | |
return args.join(''); | |
}; | |
//TODO | |
exports.DBCS = function() { | |
throw new Error('DBCS is not implemented'); | |
}; | |
//TODO | |
exports.DOLLAR = function() { | |
throw new Error('DOLLAR is not implemented'); | |
}; | |
exports.EXACT = function(text1, text2) { | |
if (arguments.length !== 2) { | |
return error.na; | |
} | |
return text1 === text2; | |
}; | |
exports.FIND = function(find_text, within_text, position) { | |
if (arguments.length < 2) { | |
return error.na; | |
} | |
position = (position === undefined) ? 0 : position; | |
return within_text ? within_text.indexOf(find_text, position - 1) + 1 : null; | |
}; | |
//TODO | |
exports.FIXED = function() { | |
throw new Error('FIXED is not implemented'); | |
}; | |
exports.HTML2TEXT = function (value) { | |
var result = ''; | |
if (value) { | |
if (value instanceof Array) { | |
value.forEach(function (line) { | |
if (result !== '') { | |
result += '\n'; | |
} | |
result += (line.replace(/<(?:.|\n)*?>/gm, '')); | |
}); | |
} else { | |
result = value.replace(/<(?:.|\n)*?>/gm, ''); | |
} | |
} | |
return result; | |
}; | |
exports.LEFT = function(text, number) { | |
number = (number === undefined) ? 1 : number; | |
number = utils.parseNumber(number); | |
if (number instanceof Error || typeof text !== 'string') { | |
return error.value; | |
} | |
return text ? text.substring(0, number) : null; | |
}; | |
exports.LEN = function(text) { | |
if (arguments.length === 0) { | |
return error.error; | |
} | |
if (typeof text === 'string') { | |
return text ? text.length : 0; | |
} | |
if (text.length) { | |
return text.length; | |
} | |
return error.value; | |
}; | |
exports.LOWER = function(text) { | |
if (typeof text !== 'string') { | |
return error.value; | |
} | |
return text ? text.toLowerCase() : text; | |
}; | |
exports.MID = function(text, start, number) { | |
start = utils.parseNumber(start); | |
number = utils.parseNumber(number); | |
if (utils.anyIsError(start, number) || typeof text !== 'string') { | |
return number; | |
} | |
var begin = start - 1; | |
var end = begin + number; | |
return text.substring(begin, end); | |
}; | |
// TODO | |
exports.NUMBERVALUE = function (text, decimal_separator, group_separator) { | |
decimal_separator = (typeof decimal_separator === 'undefined') ? '.' : decimal_separator; | |
group_separator = (typeof group_separator === 'undefined') ? ',' : group_separator; | |
return Number(text.replace(decimal_separator, '.').replace(group_separator, '')); | |
}; | |
// TODO | |
exports.PRONETIC = function() { | |
throw new Error('PRONETIC is not implemented'); | |
}; | |
exports.PROPER = function(text) { | |
if (text === undefined || text.length === 0) { | |
return error.value; | |
} | |
if (text === true) { | |
text = 'TRUE'; | |
} | |
if (text === false) { | |
text = 'FALSE'; | |
} | |
if (isNaN(text) && typeof text === 'number') { | |
return error.value; | |
} | |
if (typeof text === 'number') { | |
text = '' + text; | |
} | |
return text.replace(/\w\S*/g, function(txt) { | |
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); | |
}); | |
}; | |
exports.REGEXEXTRACT = function (text, regular_expression) { | |
if (arguments.length < 2) { | |
return error.na; | |
} | |
var match = text.match(new RegExp(regular_expression)); | |
return match ? (match[match.length > 1 ? match.length - 1 : 0]) : null; | |
}; | |
exports.REGEXMATCH = function (text, regular_expression, full) { | |
if (arguments.length < 2) { | |
return error.na; | |
} | |
var match = text.match(new RegExp(regular_expression)); | |
return full ? match : !!match; | |
}; | |
exports.REGEXREPLACE = function (text, regular_expression, replacement) { | |
if (arguments.length < 3) { | |
return error.na; | |
} | |
return text.replace(new RegExp(regular_expression), replacement); | |
}; | |
exports.REPLACE = function(text, position, length, new_text) { | |
position = utils.parseNumber(position); | |
length = utils.parseNumber(length); | |
if (utils.anyIsError(position, length) || | |
typeof text !== 'string' || | |
typeof new_text !== 'string') { | |
return error.value; | |
} | |
return text.substr(0, position - 1) + new_text + text.substr(position - 1 + length); | |
}; | |
exports.REPT = function(text, number) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return new Array(number + 1).join(text); | |
}; | |
exports.RIGHT = function(text, number) { | |
number = (number === undefined) ? 1 : number; | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
return text ? text.substring(text.length - number) : error.na; | |
}; | |
exports.SEARCH = function(find_text, within_text, position) { | |
var foundAt; | |
if (typeof find_text !== 'string' || typeof within_text !== 'string') { | |
return error.value; | |
} | |
position = (position === undefined) ? 0 : position; | |
foundAt = within_text.toLowerCase().indexOf(find_text.toLowerCase(), position - 1)+1; | |
return (foundAt === 0)?error.value:foundAt; | |
}; | |
exports.SPLIT = function (text, separator) { | |
return text.split(separator); | |
}; | |
exports.SUBSTITUTE = function(text, old_text, new_text, occurrence) { | |
if (arguments.length < 2) { | |
return error.na; | |
} | |
if (!text || !old_text || !new_text) { | |
return text; | |
} else if (occurrence === undefined) { | |
return text.replace(new RegExp(old_text, 'g'), new_text); | |
} else { | |
var index = 0; | |
var i = 0; | |
while (text.indexOf(old_text, index) > 0) { | |
index = text.indexOf(old_text, index + 1); | |
i++; | |
if (i === occurrence) { | |
return text.substring(0, index) + new_text + text.substring(index + old_text.length); | |
} | |
} | |
} | |
}; | |
exports.T = function(value) { | |
return (typeof value === "string") ? value : ''; | |
}; | |
// TODO incomplete implementation | |
exports.TEXT = function() { | |
throw new Error('TEXT is not implemented'); | |
}; | |
exports.TRIM = function(text) { | |
if (typeof text !== 'string') { | |
return error.value; | |
} | |
return text.replace(/ +/g, ' ').trim(); | |
}; | |
exports.UNICHAR = exports.CHAR; | |
exports.UNICODE = exports.CODE; | |
exports.UPPER = function(text) { | |
if (typeof text !== 'string') { | |
return error.value; | |
} | |
return text.toUpperCase(); | |
}; | |
//TODO | |
exports.VALUE = function() { | |
throw new Error('VALUE is not implemented'); | |
}; | |
/***/ }), | |
/* 7 */ | |
/***/ (function(module, exports) { | |
var defaultOperator = '='; | |
var validSymbols = ['>', '>=', '<', '<=', '=', '<>']; | |
var TOKEN_TYPE_OPERATOR = 'operator'; | |
var TOKEN_TYPE_LITERAL = 'literal'; | |
var SUPPORTED_TOKENS = [TOKEN_TYPE_OPERATOR, TOKEN_TYPE_LITERAL]; | |
exports.TOKEN_TYPE_OPERATOR = TOKEN_TYPE_OPERATOR; | |
exports.TOKEN_TYPE_LITERAL = TOKEN_TYPE_LITERAL; | |
/** | |
* Create token which describe passed symbol/value. | |
* | |
* @param {String} value Value/Symbol to describe. | |
* @param {String} type Type of the token 'operator' or 'literal'. | |
* @return {Object} | |
*/ | |
function createToken(value, type) { | |
if (SUPPORTED_TOKENS.indexOf(type) === -1) { | |
throw new Error('Unsupported token type: ' + type); | |
} | |
return { | |
value: value, | |
type: type, | |
}; | |
} | |
/** | |
* Tries to cast numeric values to their type passed as a string. | |
* | |
* @param {*} value | |
* @return {*} | |
*/ | |
function castValueToCorrectType(value) { | |
if (typeof value !== 'string') { | |
return value; | |
} | |
if (/^\d+(\.\d+)?$/.test(value)) { | |
value = value.indexOf('.') === -1 ? parseInt(value, 10) : parseFloat(value); | |
} | |
return value; | |
} | |
/** | |
* Generate stream of tokens from passed expression. | |
* | |
* @param {String} expression | |
* @return {String[]} | |
*/ | |
function tokenizeExpression(expression) { | |
var expressionLength = expression.length; | |
var tokens = []; | |
var cursorIndex = 0; | |
var processedValue = ''; | |
var processedSymbol = ''; | |
while (cursorIndex < expressionLength) { | |
var char = expression.charAt(cursorIndex); | |
switch (char) { | |
case '>': | |
case '<': | |
case '=': | |
processedSymbol = processedSymbol + char; | |
if (processedValue.length > 0) { | |
tokens.push(processedValue); | |
processedValue = ''; | |
} | |
break; | |
default: | |
if (processedSymbol.length > 0) { | |
tokens.push(processedSymbol); | |
processedSymbol = ''; | |
} | |
processedValue = processedValue + char; | |
break; | |
} | |
cursorIndex++; | |
} | |
if (processedValue.length > 0) { | |
tokens.push(processedValue); | |
} | |
if (processedSymbol.length > 0) { | |
tokens.push(processedSymbol); | |
} | |
return tokens; | |
}; | |
/** | |
* Analyze and convert tokens to an object which describes their meaning. | |
* | |
* @param {String[]} tokens | |
* @return {Object[]} | |
*/ | |
function analyzeTokens(tokens) { | |
var literalValue = ''; | |
var analyzedTokens = []; | |
for (var i = 0; i < tokens.length; i++) { | |
var token = tokens[i]; | |
if (i === 0 && validSymbols.indexOf(token) >= 0) { | |
analyzedTokens.push(createToken(token, TOKEN_TYPE_OPERATOR)); | |
} else { | |
literalValue += token; | |
} | |
} | |
if (literalValue.length > 0) { | |
analyzedTokens.push(createToken(castValueToCorrectType(literalValue), TOKEN_TYPE_LITERAL)); | |
} | |
if (analyzedTokens.length > 0 && analyzedTokens[0].type !== TOKEN_TYPE_OPERATOR) { | |
analyzedTokens.unshift(createToken(defaultOperator, TOKEN_TYPE_OPERATOR)); | |
} | |
return analyzedTokens; | |
}; | |
/** | |
* Compute/Evaluate an expression passed as an array of tokens. | |
* | |
* @param {Object[]} tokens | |
* @return {Boolean} | |
*/ | |
function computeExpression(tokens) { | |
var values = []; | |
var operator; | |
for (var i = 0; i < tokens.length; i++) { | |
var token = tokens[i]; | |
switch (token.type) { | |
case TOKEN_TYPE_OPERATOR: | |
operator = token.value; | |
break; | |
case TOKEN_TYPE_LITERAL: | |
values.push(token.value); | |
break; | |
} | |
} | |
return evaluate(values, operator); | |
}; | |
/** | |
* Evaluate values based on passed math operator. | |
* | |
* @param {*} values | |
* @param {String} operator | |
* @return {Boolean} | |
*/ | |
function evaluate(values, operator) { | |
var result = false; | |
switch (operator) { | |
case '>': | |
result = values[0] > values[1]; | |
break; | |
case '>=': | |
result = values[0] >= values[1]; | |
break; | |
case '<': | |
result = values[0] < values[1]; | |
break; | |
case '<=': | |
result = values[0] <= values[1]; | |
break; | |
case '=': | |
result = values[0] == values[1]; | |
break; | |
case '<>': | |
result = values[0] != values[1]; | |
break; | |
} | |
return result; | |
} | |
exports.parse = function(expression) { | |
return analyzeTokens(tokenizeExpression(expression)); | |
}; | |
exports.createToken = createToken; | |
exports.compute = computeExpression; | |
/***/ }), | |
/* 8 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
// TODO | |
exports.CELL = function() { | |
throw new Error('CELL is not implemented'); | |
}; | |
exports.ERROR = {}; | |
exports.ERROR.TYPE = function(error_val) { | |
switch (error_val) { | |
case error.nil: return 1; | |
case error.div0: return 2; | |
case error.value: return 3; | |
case error.ref: return 4; | |
case error.name: return 5; | |
case error.num: return 6; | |
case error.na: return 7; | |
case error.data: return 8; | |
} | |
return error.na; | |
}; | |
// TODO | |
exports.INFO = function() { | |
throw new Error('INFO is not implemented'); | |
}; | |
exports.ISBLANK = function(value) { | |
return value === null; | |
}; | |
exports.ISBINARY = function (number) { | |
return (/^[01]{1,10}$/).test(number); | |
}; | |
exports.ISERR = function(value) { | |
return ([error.value, error.ref, error.div0, error.num, error.name, error.nil]).indexOf(value) >= 0 || | |
(typeof value === 'number' && (isNaN(value) || !isFinite(value))); | |
}; | |
exports.ISERROR = function(value) { | |
return exports.ISERR(value) || value === error.na; | |
}; | |
exports.ISEVEN = function(number) { | |
return (Math.floor(Math.abs(number)) & 1) ? false : true; | |
}; | |
// TODO | |
exports.ISFORMULA = function() { | |
throw new Error('ISFORMULA is not implemented'); | |
}; | |
exports.ISLOGICAL = function(value) { | |
return value === true || value === false; | |
}; | |
exports.ISNA = function(value) { | |
return value === error.na; | |
}; | |
exports.ISNONTEXT = function(value) { | |
return typeof(value) !== 'string'; | |
}; | |
exports.ISNUMBER = function(value) { | |
return typeof(value) === 'number' && !isNaN(value) && isFinite(value); | |
}; | |
exports.ISODD = function(number) { | |
return (Math.floor(Math.abs(number)) & 1) ? true : false; | |
}; | |
// TODO | |
exports.ISREF = function() { | |
throw new Error('ISREF is not implemented'); | |
}; | |
exports.ISTEXT = function(value) { | |
return typeof(value) === 'string'; | |
}; | |
exports.N = function(value) { | |
if (this.ISNUMBER(value)) { | |
return value; | |
} | |
if (value instanceof Date) { | |
return value.getTime(); | |
} | |
if (value === true) { | |
return 1; | |
} | |
if (value === false) { | |
return 0; | |
} | |
if (this.ISERROR(value)) { | |
return value; | |
} | |
return 0; | |
}; | |
exports.NA = function() { | |
return error.na; | |
}; | |
// TODO | |
exports.SHEET = function() { | |
throw new Error('SHEET is not implemented'); | |
}; | |
// TODO | |
exports.SHEETS = function() { | |
throw new Error('SHEETS is not implemented'); | |
}; | |
exports.TYPE = function(value) { | |
if (this.ISNUMBER(value)) { | |
return 1; | |
} | |
if (this.ISTEXT(value)) { | |
return 2; | |
} | |
if (this.ISLOGICAL(value)) { | |
return 4; | |
} | |
if (this.ISERROR(value)) { | |
return 16; | |
} | |
if (Array.isArray(value)) { | |
return 64; | |
} | |
}; | |
/***/ }), | |
/* 9 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
var utils = __webpack_require__(1); | |
var d1900 = new Date(Date.UTC(1900, 0, 1)); | |
var WEEK_STARTS = [ | |
undefined, | |
0, | |
1, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
undefined, | |
1, | |
2, | |
3, | |
4, | |
5, | |
6, | |
0 | |
]; | |
var WEEK_TYPES = [ | |
[], | |
[1, 2, 3, 4, 5, 6, 7], | |
[7, 1, 2, 3, 4, 5, 6], | |
[6, 0, 1, 2, 3, 4, 5], | |
[], | |
[], | |
[], | |
[], | |
[], | |
[], | |
[], | |
[7, 1, 2, 3, 4, 5, 6], | |
[6, 7, 1, 2, 3, 4, 5], | |
[5, 6, 7, 1, 2, 3, 4], | |
[4, 5, 6, 7, 1, 2, 3], | |
[3, 4, 5, 6, 7, 1, 2], | |
[2, 3, 4, 5, 6, 7, 1], | |
[1, 2, 3, 4, 5, 6, 7] | |
]; | |
var WEEKEND_TYPES = [ | |
[], | |
[6, 0], | |
[0, 1], | |
[1, 2], | |
[2, 3], | |
[3, 4], | |
[4, 5], | |
[5, 6], | |
undefined, | |
undefined, | |
undefined, [0, 0], | |
[1, 1], | |
[2, 2], | |
[3, 3], | |
[4, 4], | |
[5, 5], | |
[6, 6] | |
]; | |
exports.DATE = function(year, month, day) { | |
var result; | |
year = utils.parseNumber(year); | |
month = utils.parseNumber(month); | |
day = utils.parseNumber(day); | |
if (utils.anyIsError(year, month, day)) { | |
result = error.value; | |
} else if (year < 0 || month < 0 || day < 0) { | |
result = error.num; | |
} else { | |
result = new Date(year, month - 1, day); | |
} | |
return result; | |
}; | |
exports.DATEVALUE = function(date_text) { | |
var modifier = 2; | |
var date; | |
if (typeof date_text !== 'string') { | |
return error.value; | |
} | |
date = Date.parse(date_text); | |
if (isNaN(date)) { | |
return error.value; | |
} | |
if (date <= -2203891200000) { | |
modifier = 1; | |
} | |
return Math.ceil((date - d1900) / 86400000) + modifier; | |
}; | |
exports.DAY = function(serial_number) { | |
var date = utils.parseDate(serial_number); | |
if (date instanceof Error) { | |
return date; | |
} | |
return date.getDate(); | |
}; | |
exports.DAYS = function(end_date, start_date) { | |
end_date = utils.parseDate(end_date); | |
start_date = utils.parseDate(start_date); | |
if (end_date instanceof Error) { | |
return end_date; | |
} | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
return serial(end_date) - serial(start_date); | |
}; | |
exports.DAYS360 = function(start_date, end_date, method) { | |
method = utils.parseBool(method); | |
start_date = utils.parseDate(start_date); | |
end_date = utils.parseDate(end_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
if (end_date instanceof Error) { | |
return end_date; | |
} | |
if (method instanceof Error) { | |
return method; | |
} | |
var sm = start_date.getMonth(); | |
var em = end_date.getMonth(); | |
var sd, ed; | |
if (method) { | |
sd = start_date.getDate() === 31 ? 30 : start_date.getDate(); | |
ed = end_date.getDate() === 31 ? 30 : end_date.getDate(); | |
} else { | |
var smd = new Date(start_date.getFullYear(), sm + 1, 0).getDate(); | |
var emd = new Date(end_date.getFullYear(), em + 1, 0).getDate(); | |
sd = start_date.getDate() === smd ? 30 : start_date.getDate(); | |
if (end_date.getDate() === emd) { | |
if (sd < 30) { | |
em++; | |
ed = 1; | |
} else { | |
ed = 30; | |
} | |
} else { | |
ed = end_date.getDate(); | |
} | |
} | |
return 360 * (end_date.getFullYear() - start_date.getFullYear()) + | |
30 * (em - sm) + (ed - sd); | |
}; | |
exports.EDATE = function(start_date, months) { | |
start_date = utils.parseDate(start_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
if (isNaN(months)) { | |
return error.value; | |
} | |
months = parseInt(months, 10); | |
start_date.setMonth(start_date.getMonth() + months); | |
return serial(start_date); | |
}; | |
exports.EOMONTH = function(start_date, months) { | |
start_date = utils.parseDate(start_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
if (isNaN(months)) { | |
return error.value; | |
} | |
months = parseInt(months, 10); | |
return serial(new Date(start_date.getFullYear(), start_date.getMonth() + months + 1, 0)); | |
}; | |
exports.HOUR = function(serial_number) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
return serial_number.getHours(); | |
}; | |
exports.INTERVAL = function (second) { | |
if (typeof second !== 'number' && typeof second !== 'string') { | |
return error.value; | |
} else { | |
second = parseInt(second, 10); | |
} | |
var year = Math.floor(second/946080000); | |
second = second%946080000; | |
var month = Math.floor(second/2592000); | |
second = second%2592000; | |
var day = Math.floor(second/86400); | |
second = second%86400; | |
var hour = Math.floor(second/3600); | |
second = second%3600; | |
var min = Math.floor(second/60); | |
second = second%60; | |
var sec = second; | |
year = (year > 0) ? year + 'Y' : ''; | |
month = (month > 0) ? month + 'M' : ''; | |
day = (day > 0) ? day + 'D' : ''; | |
hour = (hour > 0) ? hour + 'H' : ''; | |
min = (min > 0) ? min + 'M' : ''; | |
sec = (sec > 0) ? sec + 'S' : ''; | |
return 'P' + year + month + day + 'T' + hour + min + sec; | |
}; | |
exports.ISOWEEKNUM = function(date) { | |
date = utils.parseDate(date); | |
if (date instanceof Error) { | |
return date; | |
} | |
date.setHours(0, 0, 0); | |
date.setDate(date.getDate() + 4 - (date.getDay() || 7)); | |
var yearStart = new Date(date.getFullYear(), 0, 1); | |
return Math.ceil((((date - yearStart) / 86400000) + 1) / 7); | |
}; | |
exports.MINUTE = function(serial_number) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
return serial_number.getMinutes(); | |
}; | |
exports.MONTH = function(serial_number) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
return serial_number.getMonth() + 1; | |
}; | |
exports.NETWORKDAYS = function(start_date, end_date, holidays) { | |
return this.NETWORKDAYS.INTL(start_date, end_date, 1, holidays); | |
}; | |
exports.NETWORKDAYS.INTL = function(start_date, end_date, weekend, holidays) { | |
start_date = utils.parseDate(start_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
end_date = utils.parseDate(end_date); | |
if (end_date instanceof Error) { | |
return end_date; | |
} | |
if (weekend === undefined) { | |
weekend = WEEKEND_TYPES[1]; | |
} else { | |
weekend = WEEKEND_TYPES[weekend]; | |
} | |
if (!(weekend instanceof Array)) { | |
return error.value; | |
} | |
if (holidays === undefined) { | |
holidays = []; | |
} else if (!(holidays instanceof Array)) { | |
holidays = [holidays]; | |
} | |
for (var i = 0; i < holidays.length; i++) { | |
var h = utils.parseDate(holidays[i]); | |
if (h instanceof Error) { | |
return h; | |
} | |
holidays[i] = h; | |
} | |
var days = (end_date - start_date) / (1000 * 60 * 60 * 24) + 1; | |
var total = days; | |
var day = start_date; | |
for (i = 0; i < days; i++) { | |
var d = (new Date().getTimezoneOffset() > 0) ? day.getUTCDay() : day.getDay(); | |
var dec = false; | |
if (d === weekend[0] || d === weekend[1]) { | |
dec = true; | |
} | |
for (var j = 0; j < holidays.length; j++) { | |
var holiday = holidays[j]; | |
if (holiday.getDate() === day.getDate() && | |
holiday.getMonth() === day.getMonth() && | |
holiday.getFullYear() === day.getFullYear()) { | |
dec = true; | |
break; | |
} | |
} | |
if (dec) { | |
total--; | |
} | |
day.setDate(day.getDate() + 1); | |
} | |
return total; | |
}; | |
exports.NOW = function() { | |
return new Date(); | |
}; | |
exports.SECOND = function(serial_number) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
return serial_number.getSeconds(); | |
}; | |
exports.TIME = function(hour, minute, second) { | |
hour = utils.parseNumber(hour); | |
minute = utils.parseNumber(minute); | |
second = utils.parseNumber(second); | |
if (utils.anyIsError(hour, minute, second)) { | |
return error.value; | |
} | |
if (hour < 0 || minute < 0 || second < 0) { | |
return error.num; | |
} | |
return (3600 * hour + 60 * minute + second) / 86400; | |
}; | |
exports.TIMEVALUE = function(time_text) { | |
time_text = utils.parseDate(time_text); | |
if (time_text instanceof Error) { | |
return time_text; | |
} | |
return (3600 * time_text.getHours() + 60 * time_text.getMinutes() + time_text.getSeconds()) / 86400; | |
}; | |
exports.TODAY = function() { | |
return new Date(); | |
}; | |
exports.WEEKDAY = function(serial_number, return_type) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
if (return_type === undefined) { | |
return_type = 1; | |
} | |
var day = serial_number.getDay(); | |
return WEEK_TYPES[return_type][day]; | |
}; | |
exports.WEEKNUM = function(serial_number, return_type) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
if (return_type === undefined) { | |
return_type = 1; | |
} | |
if (return_type === 21) { | |
return this.ISOWEEKNUM(serial_number); | |
} | |
var week_start = WEEK_STARTS[return_type]; | |
var jan = new Date(serial_number.getFullYear(), 0, 1); | |
var inc = jan.getDay() < week_start ? 1 : 0; | |
jan -= Math.abs(jan.getDay() - week_start) * 24 * 60 * 60 * 1000; | |
return Math.floor(((serial_number - jan) / (1000 * 60 * 60 * 24)) / 7 + 1) + inc; | |
}; | |
exports.WORKDAY = function(start_date, days, holidays) { | |
return this.WORKDAY.INTL(start_date, days, 1, holidays); | |
}; | |
exports.WORKDAY.INTL = function(start_date, days, weekend, holidays) { | |
start_date = utils.parseDate(start_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
days = utils.parseNumber(days); | |
if (days instanceof Error) { | |
return days; | |
} | |
if (days < 0) { | |
return error.num; | |
} | |
if (weekend === undefined) { | |
weekend = WEEKEND_TYPES[1]; | |
} else { | |
weekend = WEEKEND_TYPES[weekend]; | |
} | |
if (!(weekend instanceof Array)) { | |
return error.value; | |
} | |
if (holidays === undefined) { | |
holidays = []; | |
} else if (!(holidays instanceof Array)) { | |
holidays = [holidays]; | |
} | |
for (var i = 0; i < holidays.length; i++) { | |
var h = utils.parseDate(holidays[i]); | |
if (h instanceof Error) { | |
return h; | |
} | |
holidays[i] = h; | |
} | |
var d = 0; | |
while (d < days) { | |
start_date.setDate(start_date.getDate() + 1); | |
var day = start_date.getDay(); | |
if (day === weekend[0] || day === weekend[1]) { | |
continue; | |
} | |
for (var j = 0; j < holidays.length; j++) { | |
var holiday = holidays[j]; | |
if (holiday.getDate() === start_date.getDate() && | |
holiday.getMonth() === start_date.getMonth() && | |
holiday.getFullYear() === start_date.getFullYear()) { | |
d--; | |
break; | |
} | |
} | |
d++; | |
} | |
return start_date; | |
}; | |
exports.YEAR = function(serial_number) { | |
serial_number = utils.parseDate(serial_number); | |
if (serial_number instanceof Error) { | |
return serial_number; | |
} | |
return serial_number.getFullYear(); | |
}; | |
function isLeapYear(year) { | |
return new Date(year, 1, 29).getMonth() === 1; | |
} | |
// TODO : Use DAYS ? | |
function daysBetween(start_date, end_date) { | |
return Math.ceil((end_date - start_date) / 1000 / 60 / 60 / 24); | |
} | |
exports.YEARFRAC = function(start_date, end_date, basis) { | |
start_date = utils.parseDate(start_date); | |
if (start_date instanceof Error) { | |
return start_date; | |
} | |
end_date = utils.parseDate(end_date); | |
if (end_date instanceof Error) { | |
return end_date; | |
} | |
basis = basis || 0; | |
var sd = start_date.getDate(); | |
var sm = start_date.getMonth() + 1; | |
var sy = start_date.getFullYear(); | |
var ed = end_date.getDate(); | |
var em = end_date.getMonth() + 1; | |
var ey = end_date.getFullYear(); | |
switch (basis) { | |
case 0: | |
// US (NASD) 30/360 | |
if (sd === 31 && ed === 31) { | |
sd = 30; | |
ed = 30; | |
} else if (sd === 31) { | |
sd = 30; | |
} else if (sd === 30 && ed === 31) { | |
ed = 30; | |
} | |
return ((ed + em * 30 + ey * 360) - (sd + sm * 30 + sy * 360)) / 360; | |
case 1: | |
// Actual/actual | |
var feb29Between = function(date1, date2) { | |
var year1 = date1.getFullYear(); | |
var mar1year1 = new Date(year1, 2, 1); | |
if (isLeapYear(year1) && date1 < mar1year1 && date2 >= mar1year1) { | |
return true; | |
} | |
var year2 = date2.getFullYear(); | |
var mar1year2 = new Date(year2, 2, 1); | |
return (isLeapYear(year2) && date2 >= mar1year2 && date1 < mar1year2); | |
}; | |
var ylength = 365; | |
if (sy === ey || ((sy + 1) === ey) && ((sm > em) || ((sm === em) && (sd >= ed)))) { | |
if ((sy === ey && isLeapYear(sy)) || | |
feb29Between(start_date, end_date) || | |
(em === 1 && ed === 29)) { | |
ylength = 366; | |
} | |
return daysBetween(start_date, end_date) / ylength; | |
} | |
var years = (ey - sy) + 1; | |
var days = (new Date(ey + 1, 0, 1) - new Date(sy, 0, 1)) / 1000 / 60 / 60 / 24; | |
var average = days / years; | |
return daysBetween(start_date, end_date) / average; | |
case 2: | |
// Actual/360 | |
return daysBetween(start_date, end_date) / 360; | |
case 3: | |
// Actual/365 | |
return daysBetween(start_date, end_date) / 365; | |
case 4: | |
// European 30/360 | |
return ((ed + em * 30 + ey * 360) - (sd + sm * 30 + sy * 360)) / 360; | |
} | |
}; | |
function serial(date) { | |
var addOn = (date > -2203891200000) ? 2 : 1; | |
return Math.ceil((date - d1900) / 86400000) + addOn; | |
} | |
/***/ }), | |
/* 10 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
(function (window, factory) { | |
if (true) { | |
module.exports = factory(); | |
} else {} | |
})(typeof self !== 'undefined' ? self : this, function () { | |
var jStat = (function(Math, undefined) { | |
// For quick reference. | |
var concat = Array.prototype.concat; | |
var slice = Array.prototype.slice; | |
var toString = Object.prototype.toString; | |
// Calculate correction for IEEE error | |
// TODO: This calculation can be improved. | |
function calcRdx(n, m) { | |
var val = n > m ? n : m; | |
return Math.pow(10, | |
17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E)); | |
} | |
var isArray = Array.isArray || function isArray(arg) { | |
return toString.call(arg) === '[object Array]'; | |
}; | |
function isFunction(arg) { | |
return toString.call(arg) === '[object Function]'; | |
} | |
function isNumber(arg) { | |
return typeof arg === 'number' && arg === arg; | |
} | |
// Converts the jStat matrix to vector. | |
function toVector(arr) { | |
return concat.apply([], arr); | |
} | |
// The one and only jStat constructor. | |
function jStat() { | |
return new jStat._init(arguments); | |
} | |
// TODO: Remove after all references in src files have been removed. | |
jStat.fn = jStat.prototype; | |
// By separating the initializer from the constructor it's easier to handle | |
// always returning a new instance whether "new" was used or not. | |
jStat._init = function _init(args) { | |
var i; | |
// If first argument is an array, must be vector or matrix. | |
if (isArray(args[0])) { | |
// Check if matrix. | |
if (isArray(args[0][0])) { | |
// See if a mapping function was also passed. | |
if (isFunction(args[1])) | |
args[0] = jStat.map(args[0], args[1]); | |
// Iterate over each is faster than this.push.apply(this, args[0]. | |
for (var i = 0; i < args[0].length; i++) | |
this[i] = args[0][i]; | |
this.length = args[0].length; | |
// Otherwise must be a vector. | |
} else { | |
this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0]; | |
this.length = 1; | |
} | |
// If first argument is number, assume creation of sequence. | |
} else if (isNumber(args[0])) { | |
this[0] = jStat.seq.apply(null, args); | |
this.length = 1; | |
// Handle case when jStat object is passed to jStat. | |
} else if (args[0] instanceof jStat) { | |
// Duplicate the object and pass it back. | |
return jStat(args[0].toArray()); | |
// Unexpected argument value, return empty jStat object. | |
// TODO: This is strange behavior. Shouldn't this throw or some such to let | |
// the user know they had bad arguments? | |
} else { | |
this[0] = []; | |
this.length = 1; | |
} | |
return this; | |
}; | |
jStat._init.prototype = jStat.prototype; | |
jStat._init.constructor = jStat; | |
// Utility functions. | |
// TODO: for internal use only? | |
jStat.utils = { | |
calcRdx: calcRdx, | |
isArray: isArray, | |
isFunction: isFunction, | |
isNumber: isNumber, | |
toVector: toVector | |
}; | |
// Easily extend the jStat object. | |
// TODO: is this seriously necessary? | |
jStat.extend = function extend(obj) { | |
var i, j; | |
if (arguments.length === 1) { | |
for (j in obj) | |
jStat[j] = obj[j]; | |
return this; | |
} | |
for (var i = 1; i < arguments.length; i++) { | |
for (j in arguments[i]) | |
obj[j] = arguments[i][j]; | |
} | |
return obj; | |
}; | |
// Returns the number of rows in the matrix. | |
jStat.rows = function rows(arr) { | |
return arr.length || 1; | |
}; | |
// Returns the number of columns in the matrix. | |
jStat.cols = function cols(arr) { | |
return arr[0].length || 1; | |
}; | |
// Returns the dimensions of the object { rows: i, cols: j } | |
jStat.dimensions = function dimensions(arr) { | |
return { | |
rows: jStat.rows(arr), | |
cols: jStat.cols(arr) | |
}; | |
}; | |
// Returns a specified row as a vector or return a sub matrix by pick some rows | |
jStat.row = function row(arr, index) { | |
if (isArray(index)) { | |
return index.map(function(i) { | |
return jStat.row(arr, i); | |
}) | |
} | |
return arr[index]; | |
}; | |
// return row as array | |
// rowa([[1,2],[3,4]],0) -> [1,2] | |
jStat.rowa = function rowa(arr, i) { | |
return jStat.row(arr, i); | |
}; | |
// Returns the specified column as a vector or return a sub matrix by pick some | |
// columns | |
jStat.col = function col(arr, index) { | |
if (isArray(index)) { | |
var submat = jStat.arange(arr.length).map(function(i) { | |
return new Array(index.length); | |
}); | |
index.forEach(function(ind, i){ | |
jStat.arange(arr.length).forEach(function(j) { | |
submat[j][i] = arr[j][ind]; | |
}); | |
}); | |
return submat; | |
} | |
var column = new Array(arr.length); | |
for (var i = 0; i < arr.length; i++) | |
column[i] = [arr[i][index]]; | |
return column; | |
}; | |
// return column as array | |
// cola([[1,2],[3,4]],0) -> [1,3] | |
jStat.cola = function cola(arr, i) { | |
return jStat.col(arr, i).map(function(a){ return a[0] }); | |
}; | |
// Returns the diagonal of the matrix | |
jStat.diag = function diag(arr) { | |
var nrow = jStat.rows(arr); | |
var res = new Array(nrow); | |
for (var row = 0; row < nrow; row++) | |
res[row] = [arr[row][row]]; | |
return res; | |
}; | |
// Returns the anti-diagonal of the matrix | |
jStat.antidiag = function antidiag(arr) { | |
var nrow = jStat.rows(arr) - 1; | |
var res = new Array(nrow); | |
for (var i = 0; nrow >= 0; nrow--, i++) | |
res[i] = [arr[i][nrow]]; | |
return res; | |
}; | |
// Transpose a matrix or array. | |
jStat.transpose = function transpose(arr) { | |
var obj = []; | |
var objArr, rows, cols, j, i; | |
// Make sure arr is in matrix format. | |
if (!isArray(arr[0])) | |
arr = [arr]; | |
rows = arr.length; | |
cols = arr[0].length; | |
for (var i = 0; i < cols; i++) { | |
objArr = new Array(rows); | |
for (j = 0; j < rows; j++) | |
objArr[j] = arr[j][i]; | |
obj.push(objArr); | |
} | |
// If obj is vector, return only single array. | |
return obj.length === 1 ? obj[0] : obj; | |
}; | |
// Map a function to an array or array of arrays. | |
// "toAlter" is an internal variable. | |
jStat.map = function map(arr, func, toAlter) { | |
var row, nrow, ncol, res, col; | |
if (!isArray(arr[0])) | |
arr = [arr]; | |
nrow = arr.length; | |
ncol = arr[0].length; | |
res = toAlter ? arr : new Array(nrow); | |
for (row = 0; row < nrow; row++) { | |
// if the row doesn't exist, create it | |
if (!res[row]) | |
res[row] = new Array(ncol); | |
for (col = 0; col < ncol; col++) | |
res[row][col] = func(arr[row][col], row, col); | |
} | |
return res.length === 1 ? res[0] : res; | |
}; | |
// Cumulatively combine the elements of an array or array of arrays using a function. | |
jStat.cumreduce = function cumreduce(arr, func, toAlter) { | |
var row, nrow, ncol, res, col; | |
if (!isArray(arr[0])) | |
arr = [arr]; | |
nrow = arr.length; | |
ncol = arr[0].length; | |
res = toAlter ? arr : new Array(nrow); | |
for (row = 0; row < nrow; row++) { | |
// if the row doesn't exist, create it | |
if (!res[row]) | |
res[row] = new Array(ncol); | |
if (ncol > 0) | |
res[row][0] = arr[row][0]; | |
for (col = 1; col < ncol; col++) | |
res[row][col] = func(res[row][col-1], arr[row][col]); | |
} | |
return res.length === 1 ? res[0] : res; | |
}; | |
// Destructively alter an array. | |
jStat.alter = function alter(arr, func) { | |
return jStat.map(arr, func, true); | |
}; | |
// Generate a rows x cols matrix according to the supplied function. | |
jStat.create = function create(rows, cols, func) { | |
var res = new Array(rows); | |
var i, j; | |
if (isFunction(cols)) { | |
func = cols; | |
cols = rows; | |
} | |
for (var i = 0; i < rows; i++) { | |
res[i] = new Array(cols); | |
for (j = 0; j < cols; j++) | |
res[i][j] = func(i, j); | |
} | |
return res; | |
}; | |
function retZero() { return 0; } | |
// Generate a rows x cols matrix of zeros. | |
jStat.zeros = function zeros(rows, cols) { | |
if (!isNumber(cols)) | |
cols = rows; | |
return jStat.create(rows, cols, retZero); | |
}; | |
function retOne() { return 1; } | |
// Generate a rows x cols matrix of ones. | |
jStat.ones = function ones(rows, cols) { | |
if (!isNumber(cols)) | |
cols = rows; | |
return jStat.create(rows, cols, retOne); | |
}; | |
// Generate a rows x cols matrix of uniformly random numbers. | |
jStat.rand = function rand(rows, cols) { | |
if (!isNumber(cols)) | |
cols = rows; | |
return jStat.create(rows, cols, Math.random); | |
}; | |
function retIdent(i, j) { return i === j ? 1 : 0; } | |
// Generate an identity matrix of size row x cols. | |
jStat.identity = function identity(rows, cols) { | |
if (!isNumber(cols)) | |
cols = rows; | |
return jStat.create(rows, cols, retIdent); | |
}; | |
// Tests whether a matrix is symmetric | |
jStat.symmetric = function symmetric(arr) { | |
var issymmetric = true; | |
var size = arr.length; | |
var row, col; | |
if (arr.length !== arr[0].length) | |
return false; | |
for (row = 0; row < size; row++) { | |
for (col = 0; col < size; col++) | |
if (arr[col][row] !== arr[row][col]) | |
return false; | |
} | |
return true; | |
}; | |
// Set all values to zero. | |
jStat.clear = function clear(arr) { | |
return jStat.alter(arr, retZero); | |
}; | |
// Generate sequence. | |
jStat.seq = function seq(min, max, length, func) { | |
if (!isFunction(func)) | |
func = false; | |
var arr = []; | |
var hival = calcRdx(min, max); | |
var step = (max * hival - min * hival) / ((length - 1) * hival); | |
var current = min; | |
var cnt; | |
// Current is assigned using a technique to compensate for IEEE error. | |
// TODO: Needs better implementation. | |
for (cnt = 0; | |
current <= max && cnt < length; | |
cnt++, current = (min * hival + step * hival * cnt) / hival) { | |
arr.push((func ? func(current, cnt) : current)); | |
} | |
return arr; | |
}; | |
// arange(5) -> [0,1,2,3,4] | |
// arange(1,5) -> [1,2,3,4] | |
// arange(5,1,-1) -> [5,4,3,2] | |
jStat.arange = function arange(start, end, step) { | |
var rl = []; | |
step = step || 1; | |
if (end === undefined) { | |
end = start; | |
start = 0; | |
} | |
if (start === end || step === 0) { | |
return []; | |
} | |
if (start < end && step < 0) { | |
return []; | |
} | |
if (start > end && step > 0) { | |
return []; | |
} | |
if (step > 0) { | |
for (i = start; i < end; i += step) { | |
rl.push(i); | |
} | |
} else { | |
for (i = start; i > end; i += step) { | |
rl.push(i); | |
} | |
} | |
return rl; | |
}; | |
// A=[[1,2,3],[4,5,6],[7,8,9]] | |
// slice(A,{row:{end:2},col:{start:1}}) -> [[2,3],[5,6]] | |
// slice(A,1,{start:1}) -> [5,6] | |
// as numpy code A[:2,1:] | |
jStat.slice = (function(){ | |
function _slice(list, start, end, step) { | |
// note it's not equal to range.map mode it's a bug | |
var i; | |
var rl = []; | |
var length = list.length; | |
if (start === undefined && end === undefined && step === undefined) { | |
return jStat.copy(list); | |
} | |
start = start || 0; | |
end = end || list.length; | |
start = start >= 0 ? start : length + start; | |
end = end >= 0 ? end : length + end; | |
step = step || 1; | |
if (start === end || step === 0) { | |
return []; | |
} | |
if (start < end && step < 0) { | |
return []; | |
} | |
if (start > end && step > 0) { | |
return []; | |
} | |
if (step > 0) { | |
for (i = start; i < end; i += step) { | |
rl.push(list[i]); | |
} | |
} else { | |
for (i = start; i > end;i += step) { | |
rl.push(list[i]); | |
} | |
} | |
return rl; | |
} | |
function slice(list, rcSlice) { | |
rcSlice = rcSlice || {}; | |
if (isNumber(rcSlice.row)) { | |
if (isNumber(rcSlice.col)) | |
return list[rcSlice.row][rcSlice.col]; | |
var row = jStat.rowa(list, rcSlice.row); | |
var colSlice = rcSlice.col || {}; | |
return _slice(row, colSlice.start, colSlice.end, colSlice.step); | |
} | |
if (isNumber(rcSlice.col)) { | |
var col = jStat.cola(list, rcSlice.col); | |
var rowSlice = rcSlice.row || {}; | |
return _slice(col, rowSlice.start, rowSlice.end, rowSlice.step); | |
} | |
var rowSlice = rcSlice.row || {}; | |
var colSlice = rcSlice.col || {}; | |
var rows = _slice(list, rowSlice.start, rowSlice.end, rowSlice.step); | |
return rows.map(function(row) { | |
return _slice(row, colSlice.start, colSlice.end, colSlice.step); | |
}); | |
} | |
return slice; | |
}()); | |
// A=[[1,2,3],[4,5,6],[7,8,9]] | |
// sliceAssign(A,{row:{start:1},col:{start:1}},[[0,0],[0,0]]) | |
// A=[[1,2,3],[4,0,0],[7,0,0]] | |
jStat.sliceAssign = function sliceAssign(A, rcSlice, B) { | |
if (isNumber(rcSlice.row)) { | |
if (isNumber(rcSlice.col)) | |
return A[rcSlice.row][rcSlice.col] = B; | |
rcSlice.col = rcSlice.col || {}; | |
rcSlice.col.start = rcSlice.col.start || 0; | |
rcSlice.col.end = rcSlice.col.end || A[0].length; | |
rcSlice.col.step = rcSlice.col.step || 1; | |
var nl = jStat.arange(rcSlice.col.start, | |
Math.min(A.length, rcSlice.col.end), | |
rcSlice.col.step); | |
var m = rcSlice.row; | |
nl.forEach(function(n, i) { | |
A[m][n] = B[i]; | |
}); | |
return A; | |
} | |
if (isNumber(rcSlice.col)) { | |
rcSlice.row = rcSlice.row || {}; | |
rcSlice.row.start = rcSlice.row.start || 0; | |
rcSlice.row.end = rcSlice.row.end || A.length; | |
rcSlice.row.step = rcSlice.row.step || 1; | |
var ml = jStat.arange(rcSlice.row.start, | |
Math.min(A[0].length, rcSlice.row.end), | |
rcSlice.row.step); | |
var n = rcSlice.col; | |
ml.forEach(function(m, j) { | |
A[m][n] = B[j]; | |
}); | |
return A; | |
} | |
if (B[0].length === undefined) { | |
B = [B]; | |
} | |
rcSlice.row.start = rcSlice.row.start || 0; | |
rcSlice.row.end = rcSlice.row.end || A.length; | |
rcSlice.row.step = rcSlice.row.step || 1; | |
rcSlice.col.start = rcSlice.col.start || 0; | |
rcSlice.col.end = rcSlice.col.end || A[0].length; | |
rcSlice.col.step = rcSlice.col.step || 1; | |
var ml = jStat.arange(rcSlice.row.start, | |
Math.min(A.length, rcSlice.row.end), | |
rcSlice.row.step); | |
var nl = jStat.arange(rcSlice.col.start, | |
Math.min(A[0].length, rcSlice.col.end), | |
rcSlice.col.step); | |
ml.forEach(function(m, i) { | |
nl.forEach(function(n, j) { | |
A[m][n] = B[i][j]; | |
}); | |
}); | |
return A; | |
}; | |
// [1,2,3] -> | |
// [[1,0,0],[0,2,0],[0,0,3]] | |
jStat.diagonal = function diagonal(diagArray) { | |
var mat = jStat.zeros(diagArray.length, diagArray.length); | |
diagArray.forEach(function(t, i) { | |
mat[i][i] = t; | |
}); | |
return mat; | |
}; | |
// return copy of A | |
jStat.copy = function copy(A) { | |
return A.map(function(row) { | |
if (isNumber(row)) | |
return row; | |
return row.map(function(t) { | |
return t; | |
}); | |
}); | |
}; | |
// TODO: Go over this entire implementation. Seems a tragic waste of resources | |
// doing all this work. Instead, and while ugly, use new Function() to generate | |
// a custom function for each static method. | |
// Quick reference. | |
var jProto = jStat.prototype; | |
// Default length. | |
jProto.length = 0; | |
// For internal use only. | |
// TODO: Check if they're actually used, and if they are then rename them | |
// to _* | |
jProto.push = Array.prototype.push; | |
jProto.sort = Array.prototype.sort; | |
jProto.splice = Array.prototype.splice; | |
jProto.slice = Array.prototype.slice; | |
// Return a clean array. | |
jProto.toArray = function toArray() { | |
return this.length > 1 ? slice.call(this) : slice.call(this)[0]; | |
}; | |
// Map a function to a matrix or vector. | |
jProto.map = function map(func, toAlter) { | |
return jStat(jStat.map(this, func, toAlter)); | |
}; | |
// Cumulatively combine the elements of a matrix or vector using a function. | |
jProto.cumreduce = function cumreduce(func, toAlter) { | |
return jStat(jStat.cumreduce(this, func, toAlter)); | |
}; | |
// Destructively alter an array. | |
jProto.alter = function alter(func) { | |
jStat.alter(this, func); | |
return this; | |
}; | |
// Extend prototype with methods that have no argument. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jProto[passfunc] = function(func) { | |
var self = this, | |
results; | |
// Check for callback. | |
if (func) { | |
setTimeout(function() { | |
func.call(self, jProto[passfunc].call(self)); | |
}); | |
return this; | |
} | |
results = jStat[passfunc](this); | |
return isArray(results) ? jStat(results) : results; | |
}; | |
})(funcs[i]); | |
})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' ')); | |
// Extend prototype with methods that have one argument. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jProto[passfunc] = function(index, func) { | |
var self = this; | |
// check for callback | |
if (func) { | |
setTimeout(function() { | |
func.call(self, jProto[passfunc].call(self, index)); | |
}); | |
return this; | |
} | |
return jStat(jStat[passfunc](this, index)); | |
}; | |
})(funcs[i]); | |
})('row col'.split(' ')); | |
// Extend prototype with simple shortcut methods. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jProto[passfunc] = function() { | |
return jStat(jStat[passfunc].apply(null, arguments)); | |
}; | |
})(funcs[i]); | |
})('create zeros ones rand identity'.split(' ')); | |
// Exposing jStat. | |
return jStat; | |
}(Math)); | |
(function(jStat, Math) { | |
var isFunction = jStat.utils.isFunction; | |
// Ascending functions for sort | |
function ascNum(a, b) { return a - b; } | |
function clip(arg, min, max) { | |
return Math.max(min, Math.min(arg, max)); | |
} | |
// sum of an array | |
jStat.sum = function sum(arr) { | |
var sum = 0; | |
var i = arr.length; | |
while (--i >= 0) | |
sum += arr[i]; | |
return sum; | |
}; | |
// sum squared | |
jStat.sumsqrd = function sumsqrd(arr) { | |
var sum = 0; | |
var i = arr.length; | |
while (--i >= 0) | |
sum += arr[i] * arr[i]; | |
return sum; | |
}; | |
// sum of squared errors of prediction (SSE) | |
jStat.sumsqerr = function sumsqerr(arr) { | |
var mean = jStat.mean(arr); | |
var sum = 0; | |
var i = arr.length; | |
var tmp; | |
while (--i >= 0) { | |
tmp = arr[i] - mean; | |
sum += tmp * tmp; | |
} | |
return sum; | |
}; | |
// sum of an array in each row | |
jStat.sumrow = function sumrow(arr) { | |
var sum = 0; | |
var i = arr.length; | |
while (--i >= 0) | |
sum += arr[i]; | |
return sum; | |
}; | |
// product of an array | |
jStat.product = function product(arr) { | |
var prod = 1; | |
var i = arr.length; | |
while (--i >= 0) | |
prod *= arr[i]; | |
return prod; | |
}; | |
// minimum value of an array | |
jStat.min = function min(arr) { | |
var low = arr[0]; | |
var i = 0; | |
while (++i < arr.length) | |
if (arr[i] < low) | |
low = arr[i]; | |
return low; | |
}; | |
// maximum value of an array | |
jStat.max = function max(arr) { | |
var high = arr[0]; | |
var i = 0; | |
while (++i < arr.length) | |
if (arr[i] > high) | |
high = arr[i]; | |
return high; | |
}; | |
// unique values of an array | |
jStat.unique = function unique(arr) { | |
var hash = {}, _arr = []; | |
for(var i = 0; i < arr.length; i++) { | |
if (!hash[arr[i]]) { | |
hash[arr[i]] = true; | |
_arr.push(arr[i]); | |
} | |
} | |
return _arr; | |
}; | |
// mean value of an array | |
jStat.mean = function mean(arr) { | |
return jStat.sum(arr) / arr.length; | |
}; | |
// mean squared error (MSE) | |
jStat.meansqerr = function meansqerr(arr) { | |
return jStat.sumsqerr(arr) / arr.length; | |
}; | |
// geometric mean of an array | |
jStat.geomean = function geomean(arr) { | |
return Math.pow(jStat.product(arr), 1 / arr.length); | |
}; | |
// median of an array | |
jStat.median = function median(arr) { | |
var arrlen = arr.length; | |
var _arr = arr.slice().sort(ascNum); | |
// check if array is even or odd, then return the appropriate | |
return !(arrlen & 1) | |
? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2 | |
: _arr[(arrlen / 2) | 0 ]; | |
}; | |
// cumulative sum of an array | |
jStat.cumsum = function cumsum(arr) { | |
return jStat.cumreduce(arr, function (a, b) { return a + b; }); | |
}; | |
// cumulative product of an array | |
jStat.cumprod = function cumprod(arr) { | |
return jStat.cumreduce(arr, function (a, b) { return a * b; }); | |
}; | |
// successive differences of a sequence | |
jStat.diff = function diff(arr) { | |
var diffs = []; | |
var arrLen = arr.length; | |
var i; | |
for (var i = 1; i < arrLen; i++) | |
diffs.push(arr[i] - arr[i - 1]); | |
return diffs; | |
}; | |
// ranks of an array | |
jStat.rank = function (arr) { | |
var arrlen = arr.length; | |
var sorted = arr.slice().sort(ascNum); | |
var ranks = new Array(arrlen); | |
for (var i = 0; i < arrlen; i++) { | |
var first = sorted.indexOf(arr[i]); | |
var last = sorted.lastIndexOf(arr[i]); | |
if (first === last) { | |
var val = first; | |
} else { | |
var val = (first + last) / 2; | |
} | |
ranks[i] = val + 1; | |
} | |
return ranks; | |
}; | |
// mode of an array | |
// if there are multiple modes of an array, return all of them | |
// is this the appropriate way of handling it? | |
jStat.mode = function mode(arr) { | |
var arrLen = arr.length; | |
var _arr = arr.slice().sort(ascNum); | |
var count = 1; | |
var maxCount = 0; | |
var numMaxCount = 0; | |
var mode_arr = []; | |
var i; | |
for (var i = 0; i < arrLen; i++) { | |
if (_arr[i] === _arr[i + 1]) { | |
count++; | |
} else { | |
if (count > maxCount) { | |
mode_arr = [_arr[i]]; | |
maxCount = count; | |
numMaxCount = 0; | |
} | |
// are there multiple max counts | |
else if (count === maxCount) { | |
mode_arr.push(_arr[i]); | |
numMaxCount++; | |
} | |
// resetting count for new value in array | |
count = 1; | |
} | |
} | |
return numMaxCount === 0 ? mode_arr[0] : mode_arr; | |
}; | |
// range of an array | |
jStat.range = function range(arr) { | |
return jStat.max(arr) - jStat.min(arr); | |
}; | |
// variance of an array | |
// flag = true indicates sample instead of population | |
jStat.variance = function variance(arr, flag) { | |
return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0)); | |
}; | |
// pooled variance of an array of arrays | |
jStat.pooledvariance = function pooledvariance(arr) { | |
var sumsqerr = arr.reduce(function (a, samples) {return a + jStat.sumsqerr(samples);}, 0); | |
var count = arr.reduce(function (a, samples) {return a + samples.length;}, 0); | |
return sumsqerr / (count - arr.length); | |
}; | |
// deviation of an array | |
jStat.deviation = function (arr) { | |
var mean = jStat.mean(arr); | |
var arrlen = arr.length; | |
var dev = new Array(arrlen); | |
for (var i = 0; i < arrlen; i++) { | |
dev[i] = arr[i] - mean; | |
} | |
return dev; | |
}; | |
// standard deviation of an array | |
// flag = true indicates sample instead of population | |
jStat.stdev = function stdev(arr, flag) { | |
return Math.sqrt(jStat.variance(arr, flag)); | |
}; | |
// pooled standard deviation of an array of arrays | |
jStat.pooledstdev = function pooledstdev(arr) { | |
return Math.sqrt(jStat.pooledvariance(arr)); | |
}; | |
// mean deviation (mean absolute deviation) of an array | |
jStat.meandev = function meandev(arr) { | |
var mean = jStat.mean(arr); | |
var a = []; | |
for (var i = arr.length - 1; i >= 0; i--) { | |
a.push(Math.abs(arr[i] - mean)); | |
} | |
return jStat.mean(a); | |
}; | |
// median deviation (median absolute deviation) of an array | |
jStat.meddev = function meddev(arr) { | |
var median = jStat.median(arr); | |
var a = []; | |
for (var i = arr.length - 1; i >= 0; i--) { | |
a.push(Math.abs(arr[i] - median)); | |
} | |
return jStat.median(a); | |
}; | |
// coefficient of variation | |
jStat.coeffvar = function coeffvar(arr) { | |
return jStat.stdev(arr) / jStat.mean(arr); | |
}; | |
// quartiles of an array | |
jStat.quartiles = function quartiles(arr) { | |
var arrlen = arr.length; | |
var _arr = arr.slice().sort(ascNum); | |
return [ | |
_arr[ Math.round((arrlen) / 4) - 1 ], | |
_arr[ Math.round((arrlen) / 2) - 1 ], | |
_arr[ Math.round((arrlen) * 3 / 4) - 1 ] | |
]; | |
}; | |
// Arbitary quantiles of an array. Direct port of the scipy.stats | |
// implementation by Pierre GF Gerard-Marchant. | |
jStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) { | |
var sortedArray = arr.slice().sort(ascNum); | |
var quantileVals = [quantilesArray.length]; | |
var n = arr.length; | |
var i, p, m, aleph, k, gamma; | |
if (typeof alphap === 'undefined') | |
alphap = 3 / 8; | |
if (typeof betap === 'undefined') | |
betap = 3 / 8; | |
for (var i = 0; i < quantilesArray.length; i++) { | |
p = quantilesArray[i]; | |
m = alphap + p * (1 - alphap - betap); | |
aleph = n * p + m; | |
k = Math.floor(clip(aleph, 1, n - 1)); | |
gamma = clip(aleph - k, 0, 1); | |
quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k]; | |
} | |
return quantileVals; | |
}; | |
// Returns the k-th percentile of values in a range, where k is in the | |
// range 0..1, exclusive. | |
jStat.percentile = function percentile(arr, k) { | |
var _arr = arr.slice().sort(ascNum); | |
var realIndex = k * (_arr.length - 1); | |
var index = parseInt(realIndex); | |
var frac = realIndex - index; | |
if (index + 1 < _arr.length) { | |
return _arr[index] * (1 - frac) + _arr[index + 1] * frac; | |
} else { | |
return _arr[index]; | |
} | |
} | |
// The percentile rank of score in a given array. Returns the percentage | |
// of all values in the input array that are less than (kind='strict') or | |
// less or equal than (kind='weak') score. Default is weak. | |
jStat.percentileOfScore = function percentileOfScore(arr, score, kind) { | |
var counter = 0; | |
var len = arr.length; | |
var strict = false; | |
var value, i; | |
if (kind === 'strict') | |
strict = true; | |
for (var i = 0; i < len; i++) { | |
value = arr[i]; | |
if ((strict && value < score) || | |
(!strict && value <= score)) { | |
counter++; | |
} | |
} | |
return counter / len; | |
}; | |
// Histogram (bin count) data | |
jStat.histogram = function histogram(arr, bins) { | |
var first = jStat.min(arr); | |
var binCnt = bins || 4; | |
var binWidth = (jStat.max(arr) - first) / binCnt; | |
var len = arr.length; | |
var bins = []; | |
var i; | |
for (var i = 0; i < binCnt; i++) | |
bins[i] = 0; | |
for (var i = 0; i < len; i++) | |
bins[Math.min(Math.floor(((arr[i] - first) / binWidth)), binCnt - 1)] += 1; | |
return bins; | |
}; | |
// covariance of two arrays | |
jStat.covariance = function covariance(arr1, arr2) { | |
var u = jStat.mean(arr1); | |
var v = jStat.mean(arr2); | |
var arr1Len = arr1.length; | |
var sq_dev = new Array(arr1Len); | |
var i; | |
for (var i = 0; i < arr1Len; i++) | |
sq_dev[i] = (arr1[i] - u) * (arr2[i] - v); | |
return jStat.sum(sq_dev) / (arr1Len - 1); | |
}; | |
// (pearson's) population correlation coefficient, rho | |
jStat.corrcoeff = function corrcoeff(arr1, arr2) { | |
return jStat.covariance(arr1, arr2) / | |
jStat.stdev(arr1, 1) / | |
jStat.stdev(arr2, 1); | |
}; | |
// (spearman's) rank correlation coefficient, sp | |
jStat.spearmancoeff = function (arr1, arr2) { | |
arr1 = jStat.rank(arr1); | |
arr2 = jStat.rank(arr2); | |
//return pearson's correlation of the ranks: | |
return jStat.corrcoeff(arr1, arr2); | |
} | |
// statistical standardized moments (general form of skew/kurt) | |
jStat.stanMoment = function stanMoment(arr, n) { | |
var mu = jStat.mean(arr); | |
var sigma = jStat.stdev(arr); | |
var len = arr.length; | |
var skewSum = 0; | |
for (var i = 0; i < len; i++) | |
skewSum += Math.pow((arr[i] - mu) / sigma, n); | |
return skewSum / arr.length; | |
}; | |
// (pearson's) moment coefficient of skewness | |
jStat.skewness = function skewness(arr) { | |
return jStat.stanMoment(arr, 3); | |
}; | |
// (pearson's) (excess) kurtosis | |
jStat.kurtosis = function kurtosis(arr) { | |
return jStat.stanMoment(arr, 4) - 3; | |
}; | |
var jProto = jStat.prototype; | |
// Extend jProto with method for calculating cumulative sums and products. | |
// This differs from the similar extension below as cumsum and cumprod should | |
// not be run again in the case fullbool === true. | |
// If a matrix is passed, automatically assume operation should be done on the | |
// columns. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
// If a matrix is passed, automatically assume operation should be done on | |
// the columns. | |
jProto[passfunc] = function(fullbool, func) { | |
var arr = []; | |
var i = 0; | |
var tmpthis = this; | |
// Assignment reassignation depending on how parameters were passed in. | |
if (isFunction(fullbool)) { | |
func = fullbool; | |
fullbool = false; | |
} | |
// Check if a callback was passed with the function. | |
if (func) { | |
setTimeout(function() { | |
func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool)); | |
}); | |
return this; | |
} | |
// Check if matrix and run calculations. | |
if (this.length > 1) { | |
tmpthis = fullbool === true ? this : this.transpose(); | |
for (; i < tmpthis.length; i++) | |
arr[i] = jStat[passfunc](tmpthis[i]); | |
return arr; | |
} | |
// Pass fullbool if only vector, not a matrix. for variance and stdev. | |
return jStat[passfunc](this[0], fullbool); | |
}; | |
})(funcs[i]); | |
})(('cumsum cumprod').split(' ')); | |
// Extend jProto with methods which don't require arguments and work on columns. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
// If a matrix is passed, automatically assume operation should be done on | |
// the columns. | |
jProto[passfunc] = function(fullbool, func) { | |
var arr = []; | |
var i = 0; | |
var tmpthis = this; | |
// Assignment reassignation depending on how parameters were passed in. | |
if (isFunction(fullbool)) { | |
func = fullbool; | |
fullbool = false; | |
} | |
// Check if a callback was passed with the function. | |
if (func) { | |
setTimeout(function() { | |
func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool)); | |
}); | |
return this; | |
} | |
// Check if matrix and run calculations. | |
if (this.length > 1) { | |
if (passfunc !== 'sumrow') | |
tmpthis = fullbool === true ? this : this.transpose(); | |
for (; i < tmpthis.length; i++) | |
arr[i] = jStat[passfunc](tmpthis[i]); | |
return fullbool === true | |
? jStat[passfunc](jStat.utils.toVector(arr)) | |
: arr; | |
} | |
// Pass fullbool if only vector, not a matrix. for variance and stdev. | |
return jStat[passfunc](this[0], fullbool); | |
}; | |
})(funcs[i]); | |
})(('sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr ' + | |
'geomean median diff rank mode range variance deviation stdev meandev ' + | |
'meddev coeffvar quartiles histogram skewness kurtosis').split(' ')); | |
// Extend jProto with functions that take arguments. Operations on matrices are | |
// done on columns. | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jProto[passfunc] = function() { | |
var arr = []; | |
var i = 0; | |
var tmpthis = this; | |
var args = Array.prototype.slice.call(arguments); | |
// If the last argument is a function, we assume it's a callback; we | |
// strip the callback out and call the function again. | |
if (isFunction(args[args.length - 1])) { | |
var callbackFunction = args[args.length - 1]; | |
var argsToPass = args.slice(0, args.length - 1); | |
setTimeout(function() { | |
callbackFunction.call(tmpthis, | |
jProto[passfunc].apply(tmpthis, argsToPass)); | |
}); | |
return this; | |
// Otherwise we curry the function args and call normally. | |
} else { | |
var callbackFunction = undefined; | |
var curriedFunction = function curriedFunction(vector) { | |
return jStat[passfunc].apply(tmpthis, [vector].concat(args)); | |
} | |
} | |
// If this is a matrix, run column-by-column. | |
if (this.length > 1) { | |
tmpthis = tmpthis.transpose(); | |
for (; i < tmpthis.length; i++) | |
arr[i] = curriedFunction(tmpthis[i]); | |
return arr; | |
} | |
// Otherwise run on the vector. | |
return curriedFunction(this[0]); | |
}; | |
})(funcs[i]); | |
})('quantiles percentileOfScore'.split(' ')); | |
}(jStat, Math)); | |
// Special functions // | |
(function(jStat, Math) { | |
// Log-gamma function | |
jStat.gammaln = function gammaln(x) { | |
var j = 0; | |
var cof = [ | |
76.18009172947146, -86.50532032941677, 24.01409824083091, | |
-1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5 | |
]; | |
var ser = 1.000000000190015; | |
var xx, y, tmp; | |
tmp = (y = xx = x) + 5.5; | |
tmp -= (xx + 0.5) * Math.log(tmp); | |
for (; j < 6; j++) | |
ser += cof[j] / ++y; | |
return Math.log(2.5066282746310005 * ser / xx) - tmp; | |
}; | |
// gamma of x | |
jStat.gammafn = function gammafn(x) { | |
var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563, | |
629.3311553128184, 866.9662027904133, -31451.272968848367, | |
-36144.413418691176, 66456.14382024054 | |
]; | |
var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192, | |
-3107.771671572311, 22538.118420980151, 4755.8462775278811, | |
-134659.9598649693, -115132.2596755535]; | |
var fact = false; | |
var n = 0; | |
var xden = 0; | |
var xnum = 0; | |
var y = x; | |
var i, z, yi, res, sum, ysq; | |
if (y <= 0) { | |
res = y % 1 + 3.6e-16; | |
if (res) { | |
fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res); | |
y = 1 - y; | |
} else { | |
return Infinity; | |
} | |
} | |
yi = y; | |
if (y < 1) { | |
z = y++; | |
} else { | |
z = (y -= n = (y | 0) - 1) - 1; | |
} | |
for (var i = 0; i < 8; ++i) { | |
xnum = (xnum + p[i]) * z; | |
xden = xden * z + q[i]; | |
} | |
res = xnum / xden + 1; | |
if (yi < y) { | |
res /= yi; | |
} else if (yi > y) { | |
for (var i = 0; i < n; ++i) { | |
res *= y; | |
y++; | |
} | |
} | |
if (fact) { | |
res = fact / res; | |
} | |
return res; | |
}; | |
// lower incomplete gamma function, which is usually typeset with a | |
// lower-case greek gamma as the function symbol | |
jStat.gammap = function gammap(a, x) { | |
return jStat.lowRegGamma(a, x) * jStat.gammafn(a); | |
}; | |
// The lower regularized incomplete gamma function, usually written P(a,x) | |
jStat.lowRegGamma = function lowRegGamma(a, x) { | |
var aln = jStat.gammaln(a); | |
var ap = a; | |
var sum = 1 / a; | |
var del = sum; | |
var b = x + 1 - a; | |
var c = 1 / 1.0e-30; | |
var d = 1 / b; | |
var h = d; | |
var i = 1; | |
// calculate maximum number of itterations required for a | |
var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17); | |
var an, endval; | |
if (x < 0 || a <= 0) { | |
return NaN; | |
} else if (x < a + 1) { | |
for (; i <= ITMAX; i++) { | |
sum += del *= x / ++ap; | |
} | |
return (sum * Math.exp(-x + a * Math.log(x) - (aln))); | |
} | |
for (; i <= ITMAX; i++) { | |
an = -i * (i - a); | |
b += 2; | |
d = an * d + b; | |
c = b + an / c; | |
d = 1 / d; | |
h *= d * c; | |
} | |
return (1 - h * Math.exp(-x + a * Math.log(x) - (aln))); | |
}; | |
// natural log factorial of n | |
jStat.factorialln = function factorialln(n) { | |
return n < 0 ? NaN : jStat.gammaln(n + 1); | |
}; | |
// factorial of n | |
jStat.factorial = function factorial(n) { | |
return n < 0 ? NaN : jStat.gammafn(n + 1); | |
}; | |
// combinations of n, m | |
jStat.combination = function combination(n, m) { | |
// make sure n or m don't exceed the upper limit of usable values | |
return (n > 170 || m > 170) | |
? Math.exp(jStat.combinationln(n, m)) | |
: (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m); | |
}; | |
jStat.combinationln = function combinationln(n, m){ | |
return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m); | |
}; | |
// permutations of n, m | |
jStat.permutation = function permutation(n, m) { | |
return jStat.factorial(n) / jStat.factorial(n - m); | |
}; | |
// beta function | |
jStat.betafn = function betafn(x, y) { | |
// ensure arguments are positive | |
if (x <= 0 || y <= 0) | |
return undefined; | |
// make sure x + y doesn't exceed the upper limit of usable values | |
return (x + y > 170) | |
? Math.exp(jStat.betaln(x, y)) | |
: jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y); | |
}; | |
// natural logarithm of beta function | |
jStat.betaln = function betaln(x, y) { | |
return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y); | |
}; | |
// Evaluates the continued fraction for incomplete beta function by modified | |
// Lentz's method. | |
jStat.betacf = function betacf(x, a, b) { | |
var fpmin = 1e-30; | |
var m = 1; | |
var qab = a + b; | |
var qap = a + 1; | |
var qam = a - 1; | |
var c = 1; | |
var d = 1 - qab * x / qap; | |
var m2, aa, del, h; | |
// These q's will be used in factors that occur in the coefficients | |
if (Math.abs(d) < fpmin) | |
d = fpmin; | |
d = 1 / d; | |
h = d; | |
for (; m <= 100; m++) { | |
m2 = 2 * m; | |
aa = m * (b - m) * x / ((qam + m2) * (a + m2)); | |
// One step (the even one) of the recurrence | |
d = 1 + aa * d; | |
if (Math.abs(d) < fpmin) | |
d = fpmin; | |
c = 1 + aa / c; | |
if (Math.abs(c) < fpmin) | |
c = fpmin; | |
d = 1 / d; | |
h *= d * c; | |
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); | |
// Next step of the recurrence (the odd one) | |
d = 1 + aa * d; | |
if (Math.abs(d) < fpmin) | |
d = fpmin; | |
c = 1 + aa / c; | |
if (Math.abs(c) < fpmin) | |
c = fpmin; | |
d = 1 / d; | |
del = d * c; | |
h *= del; | |
if (Math.abs(del - 1.0) < 3e-7) | |
break; | |
} | |
return h; | |
}; | |
// Returns the inverse of the lower regularized inomplete gamma function | |
jStat.gammapinv = function gammapinv(p, a) { | |
var j = 0; | |
var a1 = a - 1; | |
var EPS = 1e-8; | |
var gln = jStat.gammaln(a); | |
var x, err, t, u, pp, lna1, afac; | |
if (p >= 1) | |
return Math.max(100, a + 100 * Math.sqrt(a)); | |
if (p <= 0) | |
return 0; | |
if (a > 1) { | |
lna1 = Math.log(a1); | |
afac = Math.exp(a1 * (lna1 - 1) - gln); | |
pp = (p < 0.5) ? p : 1 - p; | |
t = Math.sqrt(-2 * Math.log(pp)); | |
x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t; | |
if (p < 0.5) | |
x = -x; | |
x = Math.max(1e-3, | |
a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3)); | |
} else { | |
t = 1 - a * (0.253 + a * 0.12); | |
if (p < t) | |
x = Math.pow(p / t, 1 / a); | |
else | |
x = 1 - Math.log(1 - (p - t) / (1 - t)); | |
} | |
for(; j < 12; j++) { | |
if (x <= 0) | |
return 0; | |
err = jStat.lowRegGamma(a, x) - p; | |
if (a > 1) | |
t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1)); | |
else | |
t = Math.exp(-x + a1 * Math.log(x) - gln); | |
u = err / t; | |
x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1)))); | |
if (x <= 0) | |
x = 0.5 * (x + t); | |
if (Math.abs(t) < EPS * x) | |
break; | |
} | |
return x; | |
}; | |
// Returns the error function erf(x) | |
jStat.erf = function erf(x) { | |
var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2, | |
-9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4, | |
4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6, | |
1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8, | |
6.529054439e-9, 5.059343495e-9, -9.91364156e-10, | |
-2.27365122e-10, 9.6467911e-11, 2.394038e-12, | |
-6.886027e-12, 8.94487e-13, 3.13092e-13, | |
-1.12708e-13, 3.81e-16, 7.106e-15, | |
-1.523e-15, -9.4e-17, 1.21e-16, | |
-2.8e-17]; | |
var j = cof.length - 1; | |
var isneg = false; | |
var d = 0; | |
var dd = 0; | |
var t, ty, tmp, res; | |
if (x < 0) { | |
x = -x; | |
isneg = true; | |
} | |
t = 2 / (2 + x); | |
ty = 4 * t - 2; | |
for(; j > 0; j--) { | |
tmp = d; | |
d = ty * d - dd + cof[j]; | |
dd = tmp; | |
} | |
res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd); | |
return isneg ? res - 1 : 1 - res; | |
}; | |
// Returns the complmentary error function erfc(x) | |
jStat.erfc = function erfc(x) { | |
return 1 - jStat.erf(x); | |
}; | |
// Returns the inverse of the complementary error function | |
jStat.erfcinv = function erfcinv(p) { | |
var j = 0; | |
var x, err, t, pp; | |
if (p >= 2) | |
return -100; | |
if (p <= 0) | |
return 100; | |
pp = (p < 1) ? p : 2 - p; | |
t = Math.sqrt(-2 * Math.log(pp / 2)); | |
x = -0.70711 * ((2.30753 + t * 0.27061) / | |
(1 + t * (0.99229 + t * 0.04481)) - t); | |
for (; j < 2; j++) { | |
err = jStat.erfc(x) - pp; | |
x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err); | |
} | |
return (p < 1) ? x : -x; | |
}; | |
// Returns the inverse of the incomplete beta function | |
jStat.ibetainv = function ibetainv(p, a, b) { | |
var EPS = 1e-8; | |
var a1 = a - 1; | |
var b1 = b - 1; | |
var j = 0; | |
var lna, lnb, pp, t, u, err, x, al, h, w, afac; | |
if (p <= 0) | |
return 0; | |
if (p >= 1) | |
return 1; | |
if (a >= 1 && b >= 1) { | |
pp = (p < 0.5) ? p : 1 - p; | |
t = Math.sqrt(-2 * Math.log(pp)); | |
x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t; | |
if (p < 0.5) | |
x = -x; | |
al = (x * x - 3) / 6; | |
h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1)); | |
w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * | |
(al + 5 / 6 - 2 / (3 * h)); | |
x = a / (a + b * Math.exp(2 * w)); | |
} else { | |
lna = Math.log(a / (a + b)); | |
lnb = Math.log(b / (a + b)); | |
t = Math.exp(a * lna) / a; | |
u = Math.exp(b * lnb) / b; | |
w = t + u; | |
if (p < t / w) | |
x = Math.pow(a * w * p, 1 / a); | |
else | |
x = 1 - Math.pow(b * w * (1 - p), 1 / b); | |
} | |
afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b); | |
for(; j < 10; j++) { | |
if (x === 0 || x === 1) | |
return x; | |
err = jStat.ibeta(x, a, b) - p; | |
t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac); | |
u = err / t; | |
x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x))))); | |
if (x <= 0) | |
x = 0.5 * (x + t); | |
if (x >= 1) | |
x = 0.5 * (x + t + 1); | |
if (Math.abs(t) < EPS * x && j > 0) | |
break; | |
} | |
return x; | |
}; | |
// Returns the incomplete beta function I_x(a,b) | |
jStat.ibeta = function ibeta(x, a, b) { | |
// Factors in front of the continued fraction. | |
var bt = (x === 0 || x === 1) ? 0 : | |
Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) - | |
jStat.gammaln(b) + a * Math.log(x) + b * | |
Math.log(1 - x)); | |
if (x < 0 || x > 1) | |
return false; | |
if (x < (a + 1) / (a + b + 2)) | |
// Use continued fraction directly. | |
return bt * jStat.betacf(x, a, b) / a; | |
// else use continued fraction after making the symmetry transformation. | |
return 1 - bt * jStat.betacf(1 - x, b, a) / b; | |
}; | |
// Returns a normal deviate (mu=0, sigma=1). | |
// If n and m are specified it returns a object of normal deviates. | |
jStat.randn = function randn(n, m) { | |
var u, v, x, y, q, mat; | |
if (!m) | |
m = n; | |
if (n) | |
return jStat.create(n, m, function() { return jStat.randn(); }); | |
do { | |
u = Math.random(); | |
v = 1.7156 * (Math.random() - 0.5); | |
x = u - 0.449871; | |
y = Math.abs(v) + 0.386595; | |
q = x * x + y * (0.19600 * y - 0.25472 * x); | |
} while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u)); | |
return v / u; | |
}; | |
// Returns a gamma deviate by the method of Marsaglia and Tsang. | |
jStat.randg = function randg(shape, n, m) { | |
var oalph = shape; | |
var a1, a2, u, v, x, mat; | |
if (!m) | |
m = n; | |
if (!shape) | |
shape = 1; | |
if (n) { | |
mat = jStat.zeros(n,m); | |
mat.alter(function() { return jStat.randg(shape); }); | |
return mat; | |
} | |
if (shape < 1) | |
shape += 1; | |
a1 = shape - 1 / 3; | |
a2 = 1 / Math.sqrt(9 * a1); | |
do { | |
do { | |
x = jStat.randn(); | |
v = 1 + a2 * x; | |
} while(v <= 0); | |
v = v * v * v; | |
u = Math.random(); | |
} while(u > 1 - 0.331 * Math.pow(x, 4) && | |
Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v))); | |
// alpha > 1 | |
if (shape == oalph) | |
return a1 * v; | |
// alpha < 1 | |
do { | |
u = Math.random(); | |
} while(u === 0); | |
return Math.pow(u, 1 / oalph) * a1 * v; | |
}; | |
// making use of static methods on the instance | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jStat.fn[passfunc] = function() { | |
return jStat( | |
jStat.map(this, function(value) { return jStat[passfunc](value); })); | |
} | |
})(funcs[i]); | |
})('gammaln gammafn factorial factorialln'.split(' ')); | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jStat.fn[passfunc] = function() { | |
return jStat(jStat[passfunc].apply(null, arguments)); | |
}; | |
})(funcs[i]); | |
})('randn'.split(' ')); | |
}(jStat, Math)); | |
(function(jStat, Math) { | |
// generate all distribution instance methods | |
(function(list) { | |
for (var i = 0; i < list.length; i++) (function(func) { | |
// distribution instance method | |
jStat[func] = function(a, b, c) { | |
if (!(this instanceof arguments.callee)) | |
return new arguments.callee(a, b, c); | |
this._a = a; | |
this._b = b; | |
this._c = c; | |
return this; | |
}; | |
// distribution method to be used on a jStat instance | |
jStat.fn[func] = function(a, b, c) { | |
var newthis = jStat[func](a, b, c); | |
newthis.data = this; | |
return newthis; | |
}; | |
// sample instance method | |
jStat[func].prototype.sample = function(arr) { | |
var a = this._a; | |
var b = this._b; | |
var c = this._c; | |
if (arr) | |
return jStat.alter(arr, function() { | |
return jStat[func].sample(a, b, c); | |
}); | |
else | |
return jStat[func].sample(a, b, c); | |
}; | |
// generate the pdf, cdf and inv instance methods | |
(function(vals) { | |
for (var i = 0; i < vals.length; i++) (function(fnfunc) { | |
jStat[func].prototype[fnfunc] = function(x) { | |
var a = this._a; | |
var b = this._b; | |
var c = this._c; | |
if (!x && x !== 0) | |
x = this.data; | |
if (typeof x !== 'number') { | |
return jStat.fn.map.call(x, function(x) { | |
return jStat[func][fnfunc](x, a, b, c); | |
}); | |
} | |
return jStat[func][fnfunc](x, a, b, c); | |
}; | |
})(vals[i]); | |
})('pdf cdf inv'.split(' ')); | |
// generate the mean, median, mode and variance instance methods | |
(function(vals) { | |
for (var i = 0; i < vals.length; i++) (function(fnfunc) { | |
jStat[func].prototype[fnfunc] = function() { | |
return jStat[func][fnfunc](this._a, this._b, this._c); | |
}; | |
})(vals[i]); | |
})('mean median mode variance'.split(' ')); | |
})(list[i]); | |
})(( | |
'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' + | |
'laplace lognormal noncentralt normal pareto studentt weibull uniform ' + | |
'binomial negbin hypgeom poisson triangular tukey arcsine' | |
).split(' ')); | |
// extend beta function with static methods | |
jStat.extend(jStat.beta, { | |
pdf: function pdf(x, alpha, beta) { | |
// PDF is zero outside the support | |
if (x > 1 || x < 0) | |
return 0; | |
// PDF is one for the uniform case | |
if (alpha == 1 && beta == 1) | |
return 1; | |
if (alpha < 512 && beta < 512) { | |
return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) / | |
jStat.betafn(alpha, beta); | |
} else { | |
return Math.exp((alpha - 1) * Math.log(x) + | |
(beta - 1) * Math.log(1 - x) - | |
jStat.betaln(alpha, beta)); | |
} | |
}, | |
cdf: function cdf(x, alpha, beta) { | |
return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta); | |
}, | |
inv: function inv(x, alpha, beta) { | |
return jStat.ibetainv(x, alpha, beta); | |
}, | |
mean: function mean(alpha, beta) { | |
return alpha / (alpha + beta); | |
}, | |
median: function median(alpha, beta) { | |
return jStat.ibetainv(0.5, alpha, beta); | |
}, | |
mode: function mode(alpha, beta) { | |
return (alpha - 1 ) / ( alpha + beta - 2); | |
}, | |
// return a random sample | |
sample: function sample(alpha, beta) { | |
var u = jStat.randg(alpha); | |
return u / (u + jStat.randg(beta)); | |
}, | |
variance: function variance(alpha, beta) { | |
return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1)); | |
} | |
}); | |
// extend F function with static methods | |
jStat.extend(jStat.centralF, { | |
// This implementation of the pdf function avoids float overflow | |
// See the way that R calculates this value: | |
// https://svn.r-project.org/R/trunk/src/nmath/df.c | |
pdf: function pdf(x, df1, df2) { | |
var p, q, f; | |
if (x < 0) | |
return 0; | |
if (df1 <= 2) { | |
if (x === 0 && df1 < 2) { | |
return Infinity; | |
} | |
if (x === 0 && df1 === 2) { | |
return 1; | |
} | |
return (1 / jStat.betafn(df1 / 2, df2 / 2)) * | |
Math.pow(df1 / df2, df1 / 2) * | |
Math.pow(x, (df1/2) - 1) * | |
Math.pow((1 + (df1 / df2) * x), -(df1 + df2) / 2); | |
} | |
p = (df1 * x) / (df2 + x * df1); | |
q = df2 / (df2 + x * df1); | |
f = df1 * q / 2.0; | |
return f * jStat.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p); | |
}, | |
cdf: function cdf(x, df1, df2) { | |
if (x < 0) | |
return 0; | |
return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2); | |
}, | |
inv: function inv(x, df1, df2) { | |
return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1)); | |
}, | |
mean: function mean(df1, df2) { | |
return (df2 > 2) ? df2 / (df2 - 2) : undefined; | |
}, | |
mode: function mode(df1, df2) { | |
return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined; | |
}, | |
// return a random sample | |
sample: function sample(df1, df2) { | |
var x1 = jStat.randg(df1 / 2) * 2; | |
var x2 = jStat.randg(df2 / 2) * 2; | |
return (x1 / df1) / (x2 / df2); | |
}, | |
variance: function variance(df1, df2) { | |
if (df2 <= 4) | |
return undefined; | |
return 2 * df2 * df2 * (df1 + df2 - 2) / | |
(df1 * (df2 - 2) * (df2 - 2) * (df2 - 4)); | |
} | |
}); | |
// extend cauchy function with static methods | |
jStat.extend(jStat.cauchy, { | |
pdf: function pdf(x, local, scale) { | |
if (scale < 0) { return 0; } | |
return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI; | |
}, | |
cdf: function cdf(x, local, scale) { | |
return Math.atan((x - local) / scale) / Math.PI + 0.5; | |
}, | |
inv: function(p, local, scale) { | |
return local + scale * Math.tan(Math.PI * (p - 0.5)); | |
}, | |
median: function median(local, scale) { | |
return local; | |
}, | |
mode: function mode(local, scale) { | |
return local; | |
}, | |
sample: function sample(local, scale) { | |
return jStat.randn() * | |
Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local; | |
} | |
}); | |
// extend chisquare function with static methods | |
jStat.extend(jStat.chisquare, { | |
pdf: function pdf(x, dof) { | |
if (x < 0) | |
return 0; | |
return (x === 0 && dof === 2) ? 0.5 : | |
Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) * | |
Math.log(2) - jStat.gammaln(dof / 2)); | |
}, | |
cdf: function cdf(x, dof) { | |
if (x < 0) | |
return 0; | |
return jStat.lowRegGamma(dof / 2, x / 2); | |
}, | |
inv: function(p, dof) { | |
return 2 * jStat.gammapinv(p, 0.5 * dof); | |
}, | |
mean : function(dof) { | |
return dof; | |
}, | |
// TODO: this is an approximation (is there a better way?) | |
median: function median(dof) { | |
return dof * Math.pow(1 - (2 / (9 * dof)), 3); | |
}, | |
mode: function mode(dof) { | |
return (dof - 2 > 0) ? dof - 2 : 0; | |
}, | |
sample: function sample(dof) { | |
return jStat.randg(dof / 2) * 2; | |
}, | |
variance: function variance(dof) { | |
return 2 * dof; | |
} | |
}); | |
// extend exponential function with static methods | |
jStat.extend(jStat.exponential, { | |
pdf: function pdf(x, rate) { | |
return x < 0 ? 0 : rate * Math.exp(-rate * x); | |
}, | |
cdf: function cdf(x, rate) { | |
return x < 0 ? 0 : 1 - Math.exp(-rate * x); | |
}, | |
inv: function(p, rate) { | |
return -Math.log(1 - p) / rate; | |
}, | |
mean : function(rate) { | |
return 1 / rate; | |
}, | |
median: function (rate) { | |
return (1 / rate) * Math.log(2); | |
}, | |
mode: function mode(rate) { | |
return 0; | |
}, | |
sample: function sample(rate) { | |
return -1 / rate * Math.log(Math.random()); | |
}, | |
variance : function(rate) { | |
return Math.pow(rate, -2); | |
} | |
}); | |
// extend gamma function with static methods | |
jStat.extend(jStat.gamma, { | |
pdf: function pdf(x, shape, scale) { | |
if (x < 0) | |
return 0; | |
return (x === 0 && shape === 1) ? 1 / scale : | |
Math.exp((shape - 1) * Math.log(x) - x / scale - | |
jStat.gammaln(shape) - shape * Math.log(scale)); | |
}, | |
cdf: function cdf(x, shape, scale) { | |
if (x < 0) | |
return 0; | |
return jStat.lowRegGamma(shape, x / scale); | |
}, | |
inv: function(p, shape, scale) { | |
return jStat.gammapinv(p, shape) * scale; | |
}, | |
mean : function(shape, scale) { | |
return shape * scale; | |
}, | |
mode: function mode(shape, scale) { | |
if(shape > 1) return (shape - 1) * scale; | |
return undefined; | |
}, | |
sample: function sample(shape, scale) { | |
return jStat.randg(shape) * scale; | |
}, | |
variance: function variance(shape, scale) { | |
return shape * scale * scale; | |
} | |
}); | |
// extend inverse gamma function with static methods | |
jStat.extend(jStat.invgamma, { | |
pdf: function pdf(x, shape, scale) { | |
if (x <= 0) | |
return 0; | |
return Math.exp(-(shape + 1) * Math.log(x) - scale / x - | |
jStat.gammaln(shape) + shape * Math.log(scale)); | |
}, | |
cdf: function cdf(x, shape, scale) { | |
if (x <= 0) | |
return 0; | |
return 1 - jStat.lowRegGamma(shape, scale / x); | |
}, | |
inv: function(p, shape, scale) { | |
return scale / jStat.gammapinv(1 - p, shape); | |
}, | |
mean : function(shape, scale) { | |
return (shape > 1) ? scale / (shape - 1) : undefined; | |
}, | |
mode: function mode(shape, scale) { | |
return scale / (shape + 1); | |
}, | |
sample: function sample(shape, scale) { | |
return scale / jStat.randg(shape); | |
}, | |
variance: function variance(shape, scale) { | |
if (shape <= 2) | |
return undefined; | |
return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2)); | |
} | |
}); | |
// extend kumaraswamy function with static methods | |
jStat.extend(jStat.kumaraswamy, { | |
pdf: function pdf(x, alpha, beta) { | |
if (x === 0 && alpha === 1) | |
return beta; | |
else if (x === 1 && beta === 1) | |
return alpha; | |
return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) * | |
Math.log(x) + (beta - 1) * | |
Math.log(1 - Math.pow(x, alpha))); | |
}, | |
cdf: function cdf(x, alpha, beta) { | |
if (x < 0) | |
return 0; | |
else if (x > 1) | |
return 1; | |
return (1 - Math.pow(1 - Math.pow(x, alpha), beta)); | |
}, | |
inv: function inv(p, alpha, beta) { | |
return Math.pow(1 - Math.pow(1 - p, 1 / beta), 1 / alpha); | |
}, | |
mean : function(alpha, beta) { | |
return (beta * jStat.gammafn(1 + 1 / alpha) * | |
jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta)); | |
}, | |
median: function median(alpha, beta) { | |
return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha); | |
}, | |
mode: function mode(alpha, beta) { | |
if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1))) | |
return undefined; | |
return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha); | |
}, | |
variance: function variance(alpha, beta) { | |
throw new Error('variance not yet implemented'); | |
// TODO: complete this | |
} | |
}); | |
// extend lognormal function with static methods | |
jStat.extend(jStat.lognormal, { | |
pdf: function pdf(x, mu, sigma) { | |
if (x <= 0) | |
return 0; | |
return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) - | |
Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) / | |
(2 * sigma * sigma)); | |
}, | |
cdf: function cdf(x, mu, sigma) { | |
if (x < 0) | |
return 0; | |
return 0.5 + | |
(0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma))); | |
}, | |
inv: function(p, mu, sigma) { | |
return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu); | |
}, | |
mean: function mean(mu, sigma) { | |
return Math.exp(mu + sigma * sigma / 2); | |
}, | |
median: function median(mu, sigma) { | |
return Math.exp(mu); | |
}, | |
mode: function mode(mu, sigma) { | |
return Math.exp(mu - sigma * sigma); | |
}, | |
sample: function sample(mu, sigma) { | |
return Math.exp(jStat.randn() * sigma + mu); | |
}, | |
variance: function variance(mu, sigma) { | |
return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma); | |
} | |
}); | |
// extend noncentralt function with static methods | |
jStat.extend(jStat.noncentralt, { | |
pdf: function pdf(x, dof, ncp) { | |
var tol = 1e-14; | |
if (Math.abs(ncp) < tol) // ncp approx 0; use student-t | |
return jStat.studentt.pdf(x, dof) | |
if (Math.abs(x) < tol) { // different formula for x == 0 | |
return Math.exp(jStat.gammaln((dof + 1) / 2) - ncp * ncp / 2 - | |
0.5 * Math.log(Math.PI * dof) - jStat.gammaln(dof / 2)); | |
} | |
// formula for x != 0 | |
return dof / x * | |
(jStat.noncentralt.cdf(x * Math.sqrt(1 + 2 / dof), dof+2, ncp) - | |
jStat.noncentralt.cdf(x, dof, ncp)); | |
}, | |
cdf: function cdf(x, dof, ncp) { | |
var tol = 1e-14; | |
var min_iterations = 200; | |
if (Math.abs(ncp) < tol) // ncp approx 0; use student-t | |
return jStat.studentt.cdf(x, dof); | |
// turn negative x into positive and flip result afterwards | |
var flip = false; | |
if (x < 0) { | |
flip = true; | |
ncp = -ncp; | |
} | |
var prob = jStat.normal.cdf(-ncp, 0, 1); | |
var value = tol + 1; | |
// use value at last two steps to determine convergence | |
var lastvalue = value; | |
var y = x * x / (x * x + dof); | |
var j = 0; | |
var p = Math.exp(-ncp * ncp / 2); | |
var q = Math.exp(-ncp * ncp / 2 - 0.5 * Math.log(2) - | |
jStat.gammaln(3 / 2)) * ncp; | |
while (j < min_iterations || lastvalue > tol || value > tol) { | |
lastvalue = value; | |
if (j > 0) { | |
p *= (ncp * ncp) / (2 * j); | |
q *= (ncp * ncp) / (2 * (j + 1 / 2)); | |
} | |
value = p * jStat.beta.cdf(y, j + 0.5, dof / 2) + | |
q * jStat.beta.cdf(y, j+1, dof/2); | |
prob += 0.5 * value; | |
j++; | |
} | |
return flip ? (1 - prob) : prob; | |
} | |
}); | |
// extend normal function with static methods | |
jStat.extend(jStat.normal, { | |
pdf: function pdf(x, mean, std) { | |
return Math.exp(-0.5 * Math.log(2 * Math.PI) - | |
Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std)); | |
}, | |
cdf: function cdf(x, mean, std) { | |
return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std))); | |
}, | |
inv: function(p, mean, std) { | |
return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean; | |
}, | |
mean : function(mean, std) { | |
return mean; | |
}, | |
median: function median(mean, std) { | |
return mean; | |
}, | |
mode: function (mean, std) { | |
return mean; | |
}, | |
sample: function sample(mean, std) { | |
return jStat.randn() * std + mean; | |
}, | |
variance : function(mean, std) { | |
return std * std; | |
} | |
}); | |
// extend pareto function with static methods | |
jStat.extend(jStat.pareto, { | |
pdf: function pdf(x, scale, shape) { | |
if (x < scale) | |
return 0; | |
return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1); | |
}, | |
cdf: function cdf(x, scale, shape) { | |
if (x < scale) | |
return 0; | |
return 1 - Math.pow(scale / x, shape); | |
}, | |
inv: function inv(p, scale, shape) { | |
return scale / Math.pow(1 - p, 1 / shape); | |
}, | |
mean: function mean(scale, shape) { | |
if (shape <= 1) | |
return undefined; | |
return (shape * Math.pow(scale, shape)) / (shape - 1); | |
}, | |
median: function median(scale, shape) { | |
return scale * (shape * Math.SQRT2); | |
}, | |
mode: function mode(scale, shape) { | |
return scale; | |
}, | |
variance : function(scale, shape) { | |
if (shape <= 2) | |
return undefined; | |
return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2)); | |
} | |
}); | |
// extend studentt function with static methods | |
jStat.extend(jStat.studentt, { | |
pdf: function pdf(x, dof) { | |
dof = dof > 1e100 ? 1e100 : dof; | |
return (1/(Math.sqrt(dof) * jStat.betafn(0.5, dof/2))) * | |
Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2)); | |
}, | |
cdf: function cdf(x, dof) { | |
var dof2 = dof / 2; | |
return jStat.ibeta((x + Math.sqrt(x * x + dof)) / | |
(2 * Math.sqrt(x * x + dof)), dof2, dof2); | |
}, | |
inv: function(p, dof) { | |
var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5); | |
x = Math.sqrt(dof * (1 - x) / x); | |
return (p > 0.5) ? x : -x; | |
}, | |
mean: function mean(dof) { | |
return (dof > 1) ? 0 : undefined; | |
}, | |
median: function median(dof) { | |
return 0; | |
}, | |
mode: function mode(dof) { | |
return 0; | |
}, | |
sample: function sample(dof) { | |
return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2))); | |
}, | |
variance: function variance(dof) { | |
return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined; | |
} | |
}); | |
// extend weibull function with static methods | |
jStat.extend(jStat.weibull, { | |
pdf: function pdf(x, scale, shape) { | |
if (x < 0 || scale < 0 || shape < 0) | |
return 0; | |
return (shape / scale) * Math.pow((x / scale), (shape - 1)) * | |
Math.exp(-(Math.pow((x / scale), shape))); | |
}, | |
cdf: function cdf(x, scale, shape) { | |
return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape)); | |
}, | |
inv: function(p, scale, shape) { | |
return scale * Math.pow(-Math.log(1 - p), 1 / shape); | |
}, | |
mean : function(scale, shape) { | |
return scale * jStat.gammafn(1 + 1 / shape); | |
}, | |
median: function median(scale, shape) { | |
return scale * Math.pow(Math.log(2), 1 / shape); | |
}, | |
mode: function mode(scale, shape) { | |
if (shape <= 1) | |
return 0; | |
return scale * Math.pow((shape - 1) / shape, 1 / shape); | |
}, | |
sample: function sample(scale, shape) { | |
return scale * Math.pow(-Math.log(Math.random()), 1 / shape); | |
}, | |
variance: function variance(scale, shape) { | |
return scale * scale * jStat.gammafn(1 + 2 / shape) - | |
Math.pow(jStat.weibull.mean(scale, shape), 2); | |
} | |
}); | |
// extend uniform function with static methods | |
jStat.extend(jStat.uniform, { | |
pdf: function pdf(x, a, b) { | |
return (x < a || x > b) ? 0 : 1 / (b - a); | |
}, | |
cdf: function cdf(x, a, b) { | |
if (x < a) | |
return 0; | |
else if (x < b) | |
return (x - a) / (b - a); | |
return 1; | |
}, | |
inv: function(p, a, b) { | |
return a + (p * (b - a)); | |
}, | |
mean: function mean(a, b) { | |
return 0.5 * (a + b); | |
}, | |
median: function median(a, b) { | |
return jStat.mean(a, b); | |
}, | |
mode: function mode(a, b) { | |
throw new Error('mode is not yet implemented'); | |
}, | |
sample: function sample(a, b) { | |
return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * Math.random() - 1); | |
}, | |
variance: function variance(a, b) { | |
return Math.pow(b - a, 2) / 12; | |
} | |
}); | |
// extend uniform function with static methods | |
jStat.extend(jStat.binomial, { | |
pdf: function pdf(k, n, p) { | |
return (p === 0 || p === 1) ? | |
((n * p) === k ? 1 : 0) : | |
jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k); | |
}, | |
cdf: function cdf(x, n, p) { | |
var binomarr = [], | |
k = 0; | |
if (x < 0) { | |
return 0; | |
} | |
if (x < n) { | |
for (; k <= x; k++) { | |
binomarr[ k ] = jStat.binomial.pdf(k, n, p); | |
} | |
return jStat.sum(binomarr); | |
} | |
return 1; | |
} | |
}); | |
// extend uniform function with static methods | |
jStat.extend(jStat.negbin, { | |
pdf: function pdf(k, r, p) { | |
if (k !== k >>> 0) | |
return false; | |
if (k < 0) | |
return 0; | |
return jStat.combination(k + r - 1, r - 1) * | |
Math.pow(1 - p, k) * Math.pow(p, r); | |
}, | |
cdf: function cdf(x, r, p) { | |
var sum = 0, | |
k = 0; | |
if (x < 0) return 0; | |
for (; k <= x; k++) { | |
sum += jStat.negbin.pdf(k, r, p); | |
} | |
return sum; | |
} | |
}); | |
// extend uniform function with static methods | |
jStat.extend(jStat.hypgeom, { | |
pdf: function pdf(k, N, m, n) { | |
// Hypergeometric PDF. | |
// A simplification of the CDF algorithm below. | |
// k = number of successes drawn | |
// N = population size | |
// m = number of successes in population | |
// n = number of items drawn from population | |
if(k !== k | 0) { | |
return false; | |
} else if(k < 0 || k < m - (N - n)) { | |
// It's impossible to have this few successes drawn. | |
return 0; | |
} else if(k > n || k > m) { | |
// It's impossible to have this many successes drawn. | |
return 0; | |
} else if (m * 2 > N) { | |
// More than half the population is successes. | |
if(n * 2 > N) { | |
// More than half the population is sampled. | |
return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n) | |
} else { | |
// Half or less of the population is sampled. | |
return jStat.hypgeom.pdf(n - k, N, N - m, n); | |
} | |
} else if(n * 2 > N) { | |
// Half or less is successes. | |
return jStat.hypgeom.pdf(m - k, N, m, N - n); | |
} else if(m < n) { | |
// We want to have the number of things sampled to be less than the | |
// successes available. So swap the definitions of successful and sampled. | |
return jStat.hypgeom.pdf(k, N, n, m); | |
} else { | |
// If we get here, half or less of the population was sampled, half or | |
// less of it was successes, and we had fewer sampled things than | |
// successes. Now we can do this complicated iterative algorithm in an | |
// efficient way. | |
// The basic premise of the algorithm is that we partially normalize our | |
// intermediate product to keep it in a numerically good region, and then | |
// finish the normalization at the end. | |
// This variable holds the scaled probability of the current number of | |
// successes. | |
var scaledPDF = 1; | |
// This keeps track of how much we have normalized. | |
var samplesDone = 0; | |
for(var i = 0; i < k; i++) { | |
// For every possible number of successes up to that observed... | |
while(scaledPDF > 1 && samplesDone < n) { | |
// Intermediate result is growing too big. Apply some of the | |
// normalization to shrink everything. | |
scaledPDF *= 1 - (m / (N - samplesDone)); | |
// Say we've normalized by this sample already. | |
samplesDone++; | |
} | |
// Work out the partially-normalized hypergeometric PDF for the next | |
// number of successes | |
scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); | |
} | |
for(; samplesDone < n; samplesDone++) { | |
// Apply all the rest of the normalization | |
scaledPDF *= 1 - (m / (N - samplesDone)); | |
} | |
// Bound answer sanely before returning. | |
return Math.min(1, Math.max(0, scaledPDF)); | |
} | |
}, | |
cdf: function cdf(x, N, m, n) { | |
// Hypergeometric CDF. | |
// This algorithm is due to Prof. Thomas S. Ferguson, <[email protected]>, | |
// and comes from his hypergeometric test calculator at | |
// <http://www.math.ucla.edu/~tom/distributions/Hypergeometric.html>. | |
// x = number of successes drawn | |
// N = population size | |
// m = number of successes in population | |
// n = number of items drawn from population | |
if(x < 0 || x < m - (N - n)) { | |
// It's impossible to have this few successes drawn or fewer. | |
return 0; | |
} else if(x >= n || x >= m) { | |
// We will always have this many successes or fewer. | |
return 1; | |
} else if (m * 2 > N) { | |
// More than half the population is successes. | |
if(n * 2 > N) { | |
// More than half the population is sampled. | |
return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n) | |
} else { | |
// Half or less of the population is sampled. | |
return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n); | |
} | |
} else if(n * 2 > N) { | |
// Half or less is successes. | |
return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n); | |
} else if(m < n) { | |
// We want to have the number of things sampled to be less than the | |
// successes available. So swap the definitions of successful and sampled. | |
return jStat.hypgeom.cdf(x, N, n, m); | |
} else { | |
// If we get here, half or less of the population was sampled, half or | |
// less of it was successes, and we had fewer sampled things than | |
// successes. Now we can do this complicated iterative algorithm in an | |
// efficient way. | |
// The basic premise of the algorithm is that we partially normalize our | |
// intermediate sum to keep it in a numerically good region, and then | |
// finish the normalization at the end. | |
// Holds the intermediate, scaled total CDF. | |
var scaledCDF = 1; | |
// This variable holds the scaled probability of the current number of | |
// successes. | |
var scaledPDF = 1; | |
// This keeps track of how much we have normalized. | |
var samplesDone = 0; | |
for(var i = 0; i < x; i++) { | |
// For every possible number of successes up to that observed... | |
while(scaledCDF > 1 && samplesDone < n) { | |
// Intermediate result is growing too big. Apply some of the | |
// normalization to shrink everything. | |
var factor = 1 - (m / (N - samplesDone)); | |
scaledPDF *= factor; | |
scaledCDF *= factor; | |
// Say we've normalized by this sample already. | |
samplesDone++; | |
} | |
// Work out the partially-normalized hypergeometric PDF for the next | |
// number of successes | |
scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1)); | |
// Add to the CDF answer. | |
scaledCDF += scaledPDF; | |
} | |
for(; samplesDone < n; samplesDone++) { | |
// Apply all the rest of the normalization | |
scaledCDF *= 1 - (m / (N - samplesDone)); | |
} | |
// Bound answer sanely before returning. | |
return Math.min(1, Math.max(0, scaledCDF)); | |
} | |
} | |
}); | |
// extend uniform function with static methods | |
jStat.extend(jStat.poisson, { | |
pdf: function pdf(k, l) { | |
if (l < 0 || (k % 1) !== 0 || k < 0) { | |
return 0; | |
} | |
return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k); | |
}, | |
cdf: function cdf(x, l) { | |
var sumarr = [], | |
k = 0; | |
if (x < 0) return 0; | |
for (; k <= x; k++) { | |
sumarr.push(jStat.poisson.pdf(k, l)); | |
} | |
return jStat.sum(sumarr); | |
}, | |
mean : function(l) { | |
return l; | |
}, | |
variance : function(l) { | |
return l; | |
}, | |
sample: function sample(l) { | |
var p = 1, k = 0, L = Math.exp(-l); | |
do { | |
k++; | |
p *= Math.random(); | |
} while (p > L); | |
return k - 1; | |
} | |
}); | |
// extend triangular function with static methods | |
jStat.extend(jStat.triangular, { | |
pdf: function pdf(x, a, b, c) { | |
if (b <= a || c < a || c > b) { | |
return NaN; | |
} else { | |
if (x < a || x > b) { | |
return 0; | |
} else if (x < c) { | |
return (2 * (x - a)) / ((b - a) * (c - a)); | |
} else if (x === c) { | |
return (2 / (b - a)); | |
} else { // x > c | |
return (2 * (b - x)) / ((b - a) * (b - c)); | |
} | |
} | |
}, | |
cdf: function cdf(x, a, b, c) { | |
if (b <= a || c < a || c > b) | |
return NaN; | |
if (x <= a) | |
return 0; | |
else if (x >= b) | |
return 1; | |
if (x <= c) | |
return Math.pow(x - a, 2) / ((b - a) * (c - a)); | |
else // x > c | |
return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c)); | |
}, | |
inv: function inv(p, a, b, c) { | |
if (b <= a || c < a || c > b) { | |
return NaN; | |
} else { | |
if (p <= ((c - a) / (b - a))) { | |
return a + (b - a) * Math.sqrt(p * ((c - a) / (b - a))); | |
} else { // p > ((c - a) / (b - a)) | |
return a + (b - a) * (1 - Math.sqrt((1 - p) * (1 - ((c - a) / (b - a))))); | |
} | |
} | |
}, | |
mean: function mean(a, b, c) { | |
return (a + b + c) / 3; | |
}, | |
median: function median(a, b, c) { | |
if (c <= (a + b) / 2) { | |
return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2); | |
} else if (c > (a + b) / 2) { | |
return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2); | |
} | |
}, | |
mode: function mode(a, b, c) { | |
return c; | |
}, | |
sample: function sample(a, b, c) { | |
var u = Math.random(); | |
if (u < ((c - a) / (b - a))) | |
return a + Math.sqrt(u * (b - a) * (c - a)) | |
return b - Math.sqrt((1 - u) * (b - a) * (b - c)); | |
}, | |
variance: function variance(a, b, c) { | |
return (a * a + b * b + c * c - a * b - a * c - b * c) / 18; | |
} | |
}); | |
// extend arcsine function with static methods | |
jStat.extend(jStat.arcsine, { | |
pdf: function pdf(x, a, b) { | |
if (b <= a) return NaN; | |
return (x <= a || x >= b) ? 0 : | |
(2 / Math.PI) * | |
Math.pow(Math.pow(b - a, 2) - | |
Math.pow(2 * x - a - b, 2), -0.5); | |
}, | |
cdf: function cdf(x, a, b) { | |
if (x < a) | |
return 0; | |
else if (x < b) | |
return (2 / Math.PI) * Math.asin(Math.sqrt((x - a)/(b - a))); | |
return 1; | |
}, | |
inv: function(p, a, b) { | |
return a + (0.5 - 0.5 * Math.cos(Math.PI * p)) * (b - a); | |
}, | |
mean: function mean(a, b) { | |
if (b <= a) return NaN; | |
return (a + b) / 2; | |
}, | |
median: function median(a, b) { | |
if (b <= a) return NaN; | |
return (a + b) / 2; | |
}, | |
mode: function mode(a, b) { | |
throw new Error('mode is not yet implemented'); | |
}, | |
sample: function sample(a, b) { | |
return ((a + b) / 2) + ((b - a) / 2) * | |
Math.sin(2 * Math.PI * jStat.uniform.sample(0, 1)); | |
}, | |
variance: function variance(a, b) { | |
if (b <= a) return NaN; | |
return Math.pow(b - a, 2) / 8; | |
} | |
}); | |
function laplaceSign(x) { return x / Math.abs(x); } | |
jStat.extend(jStat.laplace, { | |
pdf: function pdf(x, mu, b) { | |
return (b <= 0) ? 0 : (Math.exp(-Math.abs(x - mu) / b)) / (2 * b); | |
}, | |
cdf: function cdf(x, mu, b) { | |
if (b <= 0) { return 0; } | |
if(x < mu) { | |
return 0.5 * Math.exp((x - mu) / b); | |
} else { | |
return 1 - 0.5 * Math.exp(- (x - mu) / b); | |
} | |
}, | |
mean: function(mu, b) { | |
return mu; | |
}, | |
median: function(mu, b) { | |
return mu; | |
}, | |
mode: function(mu, b) { | |
return mu; | |
}, | |
variance: function(mu, b) { | |
return 2 * b * b; | |
}, | |
sample: function sample(mu, b) { | |
var u = Math.random() - 0.5; | |
return mu - (b * laplaceSign(u) * Math.log(1 - (2 * Math.abs(u)))); | |
} | |
}); | |
function tukeyWprob(w, rr, cc) { | |
var nleg = 12; | |
var ihalf = 6; | |
var C1 = -30; | |
var C2 = -50; | |
var C3 = 60; | |
var bb = 8; | |
var wlar = 3; | |
var wincr1 = 2; | |
var wincr2 = 3; | |
var xleg = [ | |
0.981560634246719250690549090149, | |
0.904117256370474856678465866119, | |
0.769902674194304687036893833213, | |
0.587317954286617447296702418941, | |
0.367831498998180193752691536644, | |
0.125233408511468915472441369464 | |
]; | |
var aleg = [ | |
0.047175336386511827194615961485, | |
0.106939325995318430960254718194, | |
0.160078328543346226334652529543, | |
0.203167426723065921749064455810, | |
0.233492536538354808760849898925, | |
0.249147045813402785000562436043 | |
]; | |
var qsqz = w * 0.5; | |
// if w >= 16 then the integral lower bound (occurs for c=20) | |
// is 0.99999999999995 so return a value of 1. | |
if (qsqz >= bb) | |
return 1.0; | |
// find (f(w/2) - 1) ^ cc | |
// (first term in integral of hartley's form). | |
var pr_w = 2 * jStat.normal.cdf(qsqz, 0, 1, 1, 0) - 1; // erf(qsqz / M_SQRT2) | |
// if pr_w ^ cc < 2e-22 then set pr_w = 0 | |
if (pr_w >= Math.exp(C2 / cc)) | |
pr_w = Math.pow(pr_w, cc); | |
else | |
pr_w = 0.0; | |
// if w is large then the second component of the | |
// integral is small, so fewer intervals are needed. | |
var wincr; | |
if (w > wlar) | |
wincr = wincr1; | |
else | |
wincr = wincr2; | |
// find the integral of second term of hartley's form | |
// for the integral of the range for equal-length | |
// intervals using legendre quadrature. limits of | |
// integration are from (w/2, 8). two or three | |
// equal-length intervals are used. | |
// blb and bub are lower and upper limits of integration. | |
var blb = qsqz; | |
var binc = (bb - qsqz) / wincr; | |
var bub = blb + binc; | |
var einsum = 0.0; | |
// integrate over each interval | |
var cc1 = cc - 1.0; | |
for (var wi = 1; wi <= wincr; wi++) { | |
var elsum = 0.0; | |
var a = 0.5 * (bub + blb); | |
// legendre quadrature with order = nleg | |
var b = 0.5 * (bub - blb); | |
for (var jj = 1; jj <= nleg; jj++) { | |
var j, xx; | |
if (ihalf < jj) { | |
j = (nleg - jj) + 1; | |
xx = xleg[j-1]; | |
} else { | |
j = jj; | |
xx = -xleg[j-1]; | |
} | |
var c = b * xx; | |
var ac = a + c; | |
// if exp(-qexpo/2) < 9e-14, | |
// then doesn't contribute to integral | |
var qexpo = ac * ac; | |
if (qexpo > C3) | |
break; | |
var pplus = 2 * jStat.normal.cdf(ac, 0, 1, 1, 0); | |
var pminus= 2 * jStat.normal.cdf(ac, w, 1, 1, 0); | |
// if rinsum ^ (cc-1) < 9e-14, | |
// then doesn't contribute to integral | |
var rinsum = (pplus * 0.5) - (pminus * 0.5); | |
if (rinsum >= Math.exp(C1 / cc1)) { | |
rinsum = (aleg[j-1] * Math.exp(-(0.5 * qexpo))) * Math.pow(rinsum, cc1); | |
elsum += rinsum; | |
} | |
} | |
elsum *= (((2.0 * b) * cc) / Math.sqrt(2 * Math.PI)); | |
einsum += elsum; | |
blb = bub; | |
bub += binc; | |
} | |
// if pr_w ^ rr < 9e-14, then return 0 | |
pr_w += einsum; | |
if (pr_w <= Math.exp(C1 / rr)) | |
return 0; | |
pr_w = Math.pow(pr_w, rr); | |
if (pr_w >= 1) // 1 was iMax was eps | |
return 1; | |
return pr_w; | |
} | |
function tukeyQinv(p, c, v) { | |
var p0 = 0.322232421088; | |
var q0 = 0.993484626060e-01; | |
var p1 = -1.0; | |
var q1 = 0.588581570495; | |
var p2 = -0.342242088547; | |
var q2 = 0.531103462366; | |
var p3 = -0.204231210125; | |
var q3 = 0.103537752850; | |
var p4 = -0.453642210148e-04; | |
var q4 = 0.38560700634e-02; | |
var c1 = 0.8832; | |
var c2 = 0.2368; | |
var c3 = 1.214; | |
var c4 = 1.208; | |
var c5 = 1.4142; | |
var vmax = 120.0; | |
var ps = 0.5 - 0.5 * p; | |
var yi = Math.sqrt(Math.log(1.0 / (ps * ps))); | |
var t = yi + (((( yi * p4 + p3) * yi + p2) * yi + p1) * yi + p0) | |
/ (((( yi * q4 + q3) * yi + q2) * yi + q1) * yi + q0); | |
if (v < vmax) t += (t * t * t + t) / v / 4.0; | |
var q = c1 - c2 * t; | |
if (v < vmax) q += -c3 / v + c4 * t / v; | |
return t * (q * Math.log(c - 1.0) + c5); | |
} | |
jStat.extend(jStat.tukey, { | |
cdf: function cdf(q, nmeans, df) { | |
// Identical implementation as the R ptukey() function as of commit 68947 | |
var rr = 1; | |
var cc = nmeans; | |
var nlegq = 16; | |
var ihalfq = 8; | |
var eps1 = -30.0; | |
var eps2 = 1.0e-14; | |
var dhaf = 100.0; | |
var dquar = 800.0; | |
var deigh = 5000.0; | |
var dlarg = 25000.0; | |
var ulen1 = 1.0; | |
var ulen2 = 0.5; | |
var ulen3 = 0.25; | |
var ulen4 = 0.125; | |
var xlegq = [ | |
0.989400934991649932596154173450, | |
0.944575023073232576077988415535, | |
0.865631202387831743880467897712, | |
0.755404408355003033895101194847, | |
0.617876244402643748446671764049, | |
0.458016777657227386342419442984, | |
0.281603550779258913230460501460, | |
0.950125098376374401853193354250e-1 | |
]; | |
var alegq = [ | |
0.271524594117540948517805724560e-1, | |
0.622535239386478928628438369944e-1, | |
0.951585116824927848099251076022e-1, | |
0.124628971255533872052476282192, | |
0.149595988816576732081501730547, | |
0.169156519395002538189312079030, | |
0.182603415044923588866763667969, | |
0.189450610455068496285396723208 | |
]; | |
if (q <= 0) | |
return 0; | |
// df must be > 1 | |
// there must be at least two values | |
if (df < 2 || rr < 1 || cc < 2) return NaN; | |
if (!Number.isFinite(q)) | |
return 1; | |
if (df > dlarg) | |
return tukeyWprob(q, rr, cc); | |
// calculate leading constant | |
var f2 = df * 0.5; | |
var f2lf = ((f2 * Math.log(df)) - (df * Math.log(2))) - jStat.gammaln(f2); | |
var f21 = f2 - 1.0; | |
// integral is divided into unit, half-unit, quarter-unit, or | |
// eighth-unit length intervals depending on the value of the | |
// degrees of freedom. | |
var ff4 = df * 0.25; | |
var ulen; | |
if (df <= dhaf) ulen = ulen1; | |
else if (df <= dquar) ulen = ulen2; | |
else if (df <= deigh) ulen = ulen3; | |
else ulen = ulen4; | |
f2lf += Math.log(ulen); | |
// integrate over each subinterval | |
var ans = 0.0; | |
for (var i = 1; i <= 50; i++) { | |
var otsum = 0.0; | |
// legendre quadrature with order = nlegq | |
// nodes (stored in xlegq) are symmetric around zero. | |
var twa1 = (2 * i - 1) * ulen; | |
for (var jj = 1; jj <= nlegq; jj++) { | |
var j, t1; | |
if (ihalfq < jj) { | |
j = jj - ihalfq - 1; | |
t1 = (f2lf + (f21 * Math.log(twa1 + (xlegq[j] * ulen)))) | |
- (((xlegq[j] * ulen) + twa1) * ff4); | |
} else { | |
j = jj - 1; | |
t1 = (f2lf + (f21 * Math.log(twa1 - (xlegq[j] * ulen)))) | |
+ (((xlegq[j] * ulen) - twa1) * ff4); | |
} | |
// if exp(t1) < 9e-14, then doesn't contribute to integral | |
var qsqz; | |
if (t1 >= eps1) { | |
if (ihalfq < jj) { | |
qsqz = q * Math.sqrt(((xlegq[j] * ulen) + twa1) * 0.5); | |
} else { | |
qsqz = q * Math.sqrt(((-(xlegq[j] * ulen)) + twa1) * 0.5); | |
} | |
// call wprob to find integral of range portion | |
var wprb = tukeyWprob(qsqz, rr, cc); | |
var rotsum = (wprb * alegq[j]) * Math.exp(t1); | |
otsum += rotsum; | |
} | |
// end legendre integral for interval i | |
// L200: | |
} | |
// if integral for interval i < 1e-14, then stop. | |
// However, in order to avoid small area under left tail, | |
// at least 1 / ulen intervals are calculated. | |
if (i * ulen >= 1.0 && otsum <= eps2) | |
break; | |
// end of interval i | |
// L330: | |
ans += otsum; | |
} | |
if (otsum > eps2) { // not converged | |
throw new Error('tukey.cdf failed to converge'); | |
} | |
if (ans > 1) | |
ans = 1; | |
return ans; | |
}, | |
inv: function(p, nmeans, df) { | |
// Identical implementation as the R qtukey() function as of commit 68947 | |
var rr = 1; | |
var cc = nmeans; | |
var eps = 0.0001; | |
var maxiter = 50; | |
// df must be > 1 ; there must be at least two values | |
if (df < 2 || rr < 1 || cc < 2) return NaN; | |
if (p < 0 || p > 1) return NaN; | |
if (p === 0) return 0; | |
if (p === 1) return Infinity; | |
// Initial value | |
var x0 = tukeyQinv(p, cc, df); | |
// Find prob(value < x0) | |
var valx0 = jStat.tukey.cdf(x0, nmeans, df) - p; | |
// Find the second iterate and prob(value < x1). | |
// If the first iterate has probability value | |
// exceeding p then second iterate is 1 less than | |
// first iterate; otherwise it is 1 greater. | |
var x1; | |
if (valx0 > 0.0) | |
x1 = Math.max(0.0, x0 - 1.0); | |
else | |
x1 = x0 + 1.0; | |
var valx1 = jStat.tukey.cdf(x1, nmeans, df) - p; | |
// Find new iterate | |
var ans; | |
for(var iter = 1; iter < maxiter; iter++) { | |
ans = x1 - ((valx1 * (x1 - x0)) / (valx1 - valx0)); | |
valx0 = valx1; | |
// New iterate must be >= 0 | |
x0 = x1; | |
if (ans < 0.0) { | |
ans = 0.0; | |
valx1 = -p; | |
} | |
// Find prob(value < new iterate) | |
valx1 = jStat.tukey.cdf(ans, nmeans, df) - p; | |
x1 = ans; | |
// If the difference between two successive | |
// iterates is less than eps, stop | |
var xabs = Math.abs(x1 - x0); | |
if (xabs < eps) | |
return ans; | |
} | |
throw new Error('tukey.inv failed to converge'); | |
} | |
}); | |
}(jStat, Math)); | |
/* Provides functions for the solution of linear system of equations, integration, extrapolation, | |
* interpolation, eigenvalue problems, differential equations and PCA analysis. */ | |
(function(jStat, Math) { | |
var push = Array.prototype.push; | |
var isArray = jStat.utils.isArray; | |
function isUsable(arg) { | |
return isArray(arg) || arg instanceof jStat; | |
} | |
jStat.extend({ | |
// add a vector/matrix to a vector/matrix or scalar | |
add: function add(arr, arg) { | |
// check if arg is a vector or scalar | |
if (isUsable(arg)) { | |
if (!isUsable(arg[0])) arg = [ arg ]; | |
return jStat.map(arr, function(value, row, col) { | |
return value + arg[row][col]; | |
}); | |
} | |
return jStat.map(arr, function(value) { return value + arg; }); | |
}, | |
// subtract a vector or scalar from the vector | |
subtract: function subtract(arr, arg) { | |
// check if arg is a vector or scalar | |
if (isUsable(arg)) { | |
if (!isUsable(arg[0])) arg = [ arg ]; | |
return jStat.map(arr, function(value, row, col) { | |
return value - arg[row][col] || 0; | |
}); | |
} | |
return jStat.map(arr, function(value) { return value - arg; }); | |
}, | |
// matrix division | |
divide: function divide(arr, arg) { | |
if (isUsable(arg)) { | |
if (!isUsable(arg[0])) arg = [ arg ]; | |
return jStat.multiply(arr, jStat.inv(arg)); | |
} | |
return jStat.map(arr, function(value) { return value / arg; }); | |
}, | |
// matrix multiplication | |
multiply: function multiply(arr, arg) { | |
var row, col, nrescols, sum, nrow, ncol, res, rescols; | |
// eg: arr = 2 arg = 3 -> 6 for res[0][0] statement closure | |
if (arr.length === undefined && arg.length === undefined) { | |
return arr * arg; | |
} | |
nrow = arr.length, | |
ncol = arr[0].length, | |
res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol), | |
rescols = 0; | |
if (isUsable(arg)) { | |
for (; rescols < nrescols; rescols++) { | |
for (row = 0; row < nrow; row++) { | |
sum = 0; | |
for (col = 0; col < ncol; col++) | |
sum += arr[row][col] * arg[col][rescols]; | |
res[row][rescols] = sum; | |
} | |
} | |
return (nrow === 1 && rescols === 1) ? res[0][0] : res; | |
} | |
return jStat.map(arr, function(value) { return value * arg; }); | |
}, | |
// outer([1,2,3],[4,5,6]) | |
// === | |
// [[1],[2],[3]] times [[4,5,6]] | |
// -> | |
// [[4,5,6],[8,10,12],[12,15,18]] | |
outer:function outer(A, B) { | |
return jStat.multiply(A.map(function(t){ return [t] }), [B]); | |
}, | |
// Returns the dot product of two matricies | |
dot: function dot(arr, arg) { | |
if (!isUsable(arr[0])) arr = [ arr ]; | |
if (!isUsable(arg[0])) arg = [ arg ]; | |
// convert column to row vector | |
var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr, | |
right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg, | |
res = [], | |
row = 0, | |
nrow = left.length, | |
ncol = left[0].length, | |
sum, col; | |
for (; row < nrow; row++) { | |
res[row] = []; | |
sum = 0; | |
for (col = 0; col < ncol; col++) | |
sum += left[row][col] * right[row][col]; | |
res[row] = sum; | |
} | |
return (res.length === 1) ? res[0] : res; | |
}, | |
// raise every element by a scalar | |
pow: function pow(arr, arg) { | |
return jStat.map(arr, function(value) { return Math.pow(value, arg); }); | |
}, | |
// exponentiate every element | |
exp: function exp(arr) { | |
return jStat.map(arr, function(value) { return Math.exp(value); }); | |
}, | |
// generate the natural log of every element | |
log: function exp(arr) { | |
return jStat.map(arr, function(value) { return Math.log(value); }); | |
}, | |
// generate the absolute values of the vector | |
abs: function abs(arr) { | |
return jStat.map(arr, function(value) { return Math.abs(value); }); | |
}, | |
// computes the p-norm of the vector | |
// In the case that a matrix is passed, uses the first row as the vector | |
norm: function norm(arr, p) { | |
var nnorm = 0, | |
i = 0; | |
// check the p-value of the norm, and set for most common case | |
if (isNaN(p)) p = 2; | |
// check if multi-dimensional array, and make vector correction | |
if (isUsable(arr[0])) arr = arr[0]; | |
// vector norm | |
for (; i < arr.length; i++) { | |
nnorm += Math.pow(Math.abs(arr[i]), p); | |
} | |
return Math.pow(nnorm, 1 / p); | |
}, | |
// computes the angle between two vectors in rads | |
// In case a matrix is passed, this uses the first row as the vector | |
angle: function angle(arr, arg) { | |
return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg))); | |
}, | |
// augment one matrix by another | |
// Note: this function returns a matrix, not a jStat object | |
aug: function aug(a, b) { | |
var newarr = []; | |
for (var i = 0; i < a.length; i++) { | |
newarr.push(a[i].slice()); | |
} | |
for (var i = 0; i < newarr.length; i++) { | |
push.apply(newarr[i], b[i]); | |
} | |
return newarr; | |
}, | |
// The inv() function calculates the inverse of a matrix | |
// Create the inverse by augmenting the matrix by the identity matrix of the | |
// appropriate size, and then use G-J elimination on the augmented matrix. | |
inv: function inv(a) { | |
var rows = a.length; | |
var cols = a[0].length; | |
var b = jStat.identity(rows, cols); | |
var c = jStat.gauss_jordan(a, b); | |
var result = []; | |
var i = 0; | |
var j; | |
//We need to copy the inverse portion to a new matrix to rid G-J artifacts | |
for (; i < rows; i++) { | |
result[i] = []; | |
for (j = cols; j < c[0].length; j++) | |
result[i][j - cols] = c[i][j]; | |
} | |
return result; | |
}, | |
// calculate the determinant of a matrix | |
det: function det(a) { | |
var alen = a.length, | |
alend = alen * 2, | |
vals = new Array(alend), | |
rowshift = alen - 1, | |
colshift = alend - 1, | |
mrow = rowshift - alen + 1, | |
mcol = colshift, | |
i = 0, | |
result = 0, | |
j; | |
// check for special 2x2 case | |
if (alen === 2) { | |
return a[0][0] * a[1][1] - a[0][1] * a[1][0]; | |
} | |
for (; i < alend; i++) { | |
vals[i] = 1; | |
} | |
for (var i = 0; i < alen; i++) { | |
for (j = 0; j < alen; j++) { | |
vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j]; | |
vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j]; | |
mrow++; | |
mcol--; | |
} | |
mrow = --rowshift - alen + 1; | |
mcol = --colshift; | |
} | |
for (var i = 0; i < alen; i++) { | |
result += vals[i]; | |
} | |
for (; i < alend; i++) { | |
result -= vals[i]; | |
} | |
return result; | |
}, | |
gauss_elimination: function gauss_elimination(a, b) { | |
var i = 0, | |
j = 0, | |
n = a.length, | |
m = a[0].length, | |
factor = 1, | |
sum = 0, | |
x = [], | |
maug, pivot, temp, k; | |
a = jStat.aug(a, b); | |
maug = a[0].length; | |
for(var i = 0; i < n; i++) { | |
pivot = a[i][i]; | |
j = i; | |
for (k = i + 1; k < m; k++) { | |
if (pivot < Math.abs(a[k][i])) { | |
pivot = a[k][i]; | |
j = k; | |
} | |
} | |
if (j != i) { | |
for(k = 0; k < maug; k++) { | |
temp = a[i][k]; | |
a[i][k] = a[j][k]; | |
a[j][k] = temp; | |
} | |
} | |
for (j = i + 1; j < n; j++) { | |
factor = a[j][i] / a[i][i]; | |
for(k = i; k < maug; k++) { | |
a[j][k] = a[j][k] - factor * a[i][k]; | |
} | |
} | |
} | |
for (var i = n - 1; i >= 0; i--) { | |
sum = 0; | |
for (j = i + 1; j<= n - 1; j++) { | |
sum = sum + x[j] * a[i][j]; | |
} | |
x[i] =(a[i][maug - 1] - sum) / a[i][i]; | |
} | |
return x; | |
}, | |
gauss_jordan: function gauss_jordan(a, b) { | |
var m = jStat.aug(a, b), | |
h = m.length, | |
w = m[0].length; | |
var c = 0; | |
// find max pivot | |
for (var y = 0; y < h; y++) { | |
var maxrow = y; | |
for (var y2 = y+1; y2 < h; y2++) { | |
if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y])) | |
maxrow = y2; | |
} | |
var tmp = m[y]; | |
m[y] = m[maxrow]; | |
m[maxrow] = tmp | |
for (var y2 = y+1; y2 < h; y2++) { | |
c = m[y2][y] / m[y][y]; | |
for (var x = y; x < w; x++) { | |
m[y2][x] -= m[y][x] * c; | |
} | |
} | |
} | |
// backsubstitute | |
for (var y = h-1; y >= 0; y--) { | |
c = m[y][y]; | |
for (var y2 = 0; y2 < y; y2++) { | |
for (var x = w-1; x > y-1; x--) { | |
m[y2][x] -= m[y][x] * m[y2][y] / c; | |
} | |
} | |
m[y][y] /= c; | |
for (var x = h; x < w; x++) { | |
m[y][x] /= c; | |
} | |
} | |
return m; | |
}, | |
// solve equation | |
// Ax=b | |
// A is upper triangular matrix | |
// A=[[1,2,3],[0,4,5],[0,6,7]] | |
// b=[1,2,3] | |
// triaUpSolve(A,b) // -> [2.666,0.1666,1.666] | |
// if you use matrix style | |
// A=[[1,2,3],[0,4,5],[0,6,7]] | |
// b=[[1],[2],[3]] | |
// will return [[2.666],[0.1666],[1.666]] | |
triaUpSolve: function triaUpSolve(A, b) { | |
var size = A[0].length; | |
var x = jStat.zeros(1, size)[0]; | |
var parts; | |
var matrix_mode = false; | |
if (b[0].length != undefined) { | |
b = b.map(function(i){ return i[0] }); | |
matrix_mode = true; | |
} | |
jStat.arange(size - 1, -1, -1).forEach(function(i) { | |
parts = jStat.arange(i + 1, size).map(function(j) { | |
return x[j] * A[i][j]; | |
}); | |
x[i] = (b[i] - jStat.sum(parts)) / A[i][i]; | |
}); | |
if (matrix_mode) | |
return x.map(function(i){ return [i] }); | |
return x; | |
}, | |
triaLowSolve: function triaLowSolve(A, b) { | |
// like to triaUpSolve but A is lower triangular matrix | |
var size = A[0].length; | |
var x = jStat.zeros(1, size)[0]; | |
var parts; | |
var matrix_mode=false; | |
if (b[0].length != undefined) { | |
b = b.map(function(i){ return i[0] }); | |
matrix_mode = true; | |
} | |
jStat.arange(size).forEach(function(i) { | |
parts = jStat.arange(i).map(function(j) { | |
return A[i][j] * x[j]; | |
}); | |
x[i] = (b[i] - jStat.sum(parts)) / A[i][i]; | |
}) | |
if (matrix_mode) | |
return x.map(function(i){ return [i] }); | |
return x; | |
}, | |
// A -> [L,U] | |
// A=LU | |
// L is lower triangular matrix | |
// U is upper triangular matrix | |
lu: function lu(A) { | |
var size = A.length; | |
//var L=jStat.diagonal(jStat.ones(1,size)[0]); | |
var L = jStat.identity(size); | |
var R = jStat.zeros(A.length, A[0].length); | |
var parts; | |
jStat.arange(size).forEach(function(t) { | |
R[0][t] = A[0][t]; | |
}); | |
jStat.arange(1, size).forEach(function(l) { | |
jStat.arange(l).forEach(function(i) { | |
parts = jStat.arange(i).map(function(jj) { | |
return L[l][jj] * R[jj][i]; | |
}); | |
L[l][i] = (A[l][i] - jStat.sum(parts)) / R[i][i]; | |
}); | |
jStat.arange(l, size).forEach(function(j) { | |
parts = jStat.arange(l).map(function(jj) { | |
return L[l][jj] * R[jj][j]; | |
}); | |
R[l][j] = A[i][j] - jStat.sum(parts); | |
}); | |
}); | |
return [L, R]; | |
}, | |
// A -> T | |
// A=TT' | |
// T is lower triangular matrix | |
cholesky: function cholesky(A) { | |
var size = A.length; | |
var T = jStat.zeros(A.length, A[0].length); | |
var parts; | |
jStat.arange(size).forEach(function(i) { | |
parts = jStat.arange(i).map(function(t) { | |
return Math.pow(T[i][t],2); | |
}); | |
T[i][i] = Math.sqrt(A[i][i] - jStat.sum(parts)); | |
jStat.arange(i + 1, size).forEach(function(j) { | |
parts = jStat.arange(i).map(function(t) { | |
return T[i][t] * T[j][t]; | |
}); | |
T[j][i] = (A[i][j] - jStat.sum(parts)) / T[i][i]; | |
}); | |
}); | |
return T; | |
}, | |
gauss_jacobi: function gauss_jacobi(a, b, x, r) { | |
var i = 0; | |
var j = 0; | |
var n = a.length; | |
var l = []; | |
var u = []; | |
var d = []; | |
var xv, c, h, xk; | |
for (; i < n; i++) { | |
l[i] = []; | |
u[i] = []; | |
d[i] = []; | |
for (j = 0; j < n; j++) { | |
if (i > j) { | |
l[i][j] = a[i][j]; | |
u[i][j] = d[i][j] = 0; | |
} else if (i < j) { | |
u[i][j] = a[i][j]; | |
l[i][j] = d[i][j] = 0; | |
} else { | |
d[i][j] = a[i][j]; | |
l[i][j] = u[i][j] = 0; | |
} | |
} | |
} | |
h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1); | |
c = jStat.multiply(jStat.inv(d), b); | |
xv = x; | |
xk = jStat.add(jStat.multiply(h, x), c); | |
i = 2; | |
while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) { | |
xv = xk; | |
xk = jStat.add(jStat.multiply(h, xv), c); | |
i++; | |
} | |
return xk; | |
}, | |
gauss_seidel: function gauss_seidel(a, b, x, r) { | |
var i = 0; | |
var n = a.length; | |
var l = []; | |
var u = []; | |
var d = []; | |
var j, xv, c, h, xk; | |
for (; i < n; i++) { | |
l[i] = []; | |
u[i] = []; | |
d[i] = []; | |
for (j = 0; j < n; j++) { | |
if (i > j) { | |
l[i][j] = a[i][j]; | |
u[i][j] = d[i][j] = 0; | |
} else if (i < j) { | |
u[i][j] = a[i][j]; | |
l[i][j] = d[i][j] = 0; | |
} else { | |
d[i][j] = a[i][j]; | |
l[i][j] = u[i][j] = 0; | |
} | |
} | |
} | |
h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1); | |
c = jStat.multiply(jStat.inv(jStat.add(d, l)), b); | |
xv = x; | |
xk = jStat.add(jStat.multiply(h, x), c); | |
i = 2; | |
while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) { | |
xv = xk; | |
xk = jStat.add(jStat.multiply(h, xv), c); | |
i = i + 1; | |
} | |
return xk; | |
}, | |
SOR: function SOR(a, b, x, r, w) { | |
var i = 0; | |
var n = a.length; | |
var l = []; | |
var u = []; | |
var d = []; | |
var j, xv, c, h, xk; | |
for (; i < n; i++) { | |
l[i] = []; | |
u[i] = []; | |
d[i] = []; | |
for (j = 0; j < n; j++) { | |
if (i > j) { | |
l[i][j] = a[i][j]; | |
u[i][j] = d[i][j] = 0; | |
} else if (i < j) { | |
u[i][j] = a[i][j]; | |
l[i][j] = d[i][j] = 0; | |
} else { | |
d[i][j] = a[i][j]; | |
l[i][j] = u[i][j] = 0; | |
} | |
} | |
} | |
h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))), | |
jStat.subtract(jStat.multiply(d, 1 - w), | |
jStat.multiply(u, w))); | |
c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, | |
jStat.multiply(l, w))), b), w); | |
xv = x; | |
xk = jStat.add(jStat.multiply(h, x), c); | |
i = 2; | |
while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) { | |
xv = xk; | |
xk = jStat.add(jStat.multiply(h, xv), c); | |
i++; | |
} | |
return xk; | |
}, | |
householder: function householder(a) { | |
var m = a.length; | |
var n = a[0].length; | |
var i = 0; | |
var w = []; | |
var p = []; | |
var alpha, r, k, j, factor; | |
for (; i < m - 1; i++) { | |
alpha = 0; | |
for (j = i + 1; j < n; j++) | |
alpha += (a[j][i] * a[j][i]); | |
factor = (a[i + 1][i] > 0) ? -1 : 1; | |
alpha = factor * Math.sqrt(alpha); | |
r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2)); | |
w = jStat.zeros(m, 1); | |
w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r); | |
for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r); | |
p = jStat.subtract(jStat.identity(m, n), | |
jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2)); | |
a = jStat.multiply(p, jStat.multiply(a, p)); | |
} | |
return a; | |
}, | |
// A -> [Q,R] | |
// Q is orthogonal matrix | |
// R is upper triangular | |
QR: (function() { | |
// x -> Q | |
// find a orthogonal matrix Q st. | |
// Qx=y | |
// y is [||x||,0,0,...] | |
// quick ref | |
var sum = jStat.sum; | |
var range = jStat.arange; | |
function get_Q1(x) { | |
var size = x.length; | |
var norm_x = jStat.norm(x, 2); | |
var e1 = jStat.zeros(1, size)[0]; | |
e1[0] = 1; | |
var u = jStat.add(jStat.multiply(jStat.multiply(e1, norm_x), -1), x); | |
var norm_u = jStat.norm(u, 2); | |
var v = jStat.divide(u, norm_u); | |
var Q = jStat.subtract(jStat.identity(size), | |
jStat.multiply(jStat.outer(v, v), 2)); | |
return Q; | |
} | |
function qr(A) { | |
var size = A[0].length; | |
var QList = []; | |
jStat.arange(size).forEach(function(i) { | |
var x = jStat.slice(A, { row: { start: i }, col: i }); | |
var Q = get_Q1(x); | |
var Qn = jStat.identity(A.length); | |
Qn = jStat.sliceAssign(Qn, { row: { start: i }, col: { start: i }}, Q); | |
A = jStat.multiply(Qn, A); | |
QList.push(Qn); | |
}); | |
var Q = QList.reduce(function(x, y){ return jStat.multiply(x,y) }); | |
var R = A; | |
return [Q, R]; | |
} | |
function qr2(x) { | |
// quick impletation | |
// https://www.stat.wisc.edu/~larget/math496/qr.html | |
var n = x.length; | |
var p = x[0].length; | |
x = jStat.copy(x); | |
r = jStat.zeros(p, p); | |
var i,j,k; | |
for(j = 0; j < p; j++){ | |
r[j][j] = Math.sqrt(sum(range(n).map(function(i){ | |
return x[i][j] * x[i][j]; | |
}))); | |
for(i = 0; i < n; i++){ | |
x[i][j] = x[i][j] / r[j][j]; | |
} | |
for(k = j+1; k < p; k++){ | |
r[j][k] = sum(range(n).map(function(i){ | |
return x[i][j] * x[i][k]; | |
})); | |
for(i = 0; i < n; i++){ | |
x[i][k] = x[i][k] - x[i][j]*r[j][k]; | |
} | |
} | |
} | |
return [x, r]; | |
} | |
return qr2; | |
}()), | |
lstsq: (function(A, b) { | |
// solve least squard problem for Ax=b as QR decomposition way if b is | |
// [[b1],[b2],[b3]] form will return [[x1],[x2],[x3]] array form solution | |
// else b is [b1,b2,b3] form will return [x1,x2,x3] array form solution | |
function R_I(A) { | |
A = jStat.copy(A); | |
var size = A.length; | |
var I = jStat.identity(size); | |
jStat.arange(size - 1, -1, -1).forEach(function(i) { | |
jStat.sliceAssign( | |
I, { row: i }, jStat.divide(jStat.slice(I, { row: i }), A[i][i])); | |
jStat.sliceAssign( | |
A, { row: i }, jStat.divide(jStat.slice(A, { row: i }), A[i][i])); | |
jStat.arange(i).forEach(function(j) { | |
var c = jStat.multiply(A[j][i], -1); | |
var Aj = jStat.slice(A, { row: j }); | |
var cAi = jStat.multiply(jStat.slice(A, { row: i }), c); | |
jStat.sliceAssign(A, { row: j }, jStat.add(Aj, cAi)); | |
var Ij = jStat.slice(I, { row: j }); | |
var cIi = jStat.multiply(jStat.slice(I, { row: i }), c); | |
jStat.sliceAssign(I, { row: j }, jStat.add(Ij, cIi)); | |
}) | |
}); | |
return I; | |
} | |
function qr_solve(A, b){ | |
var array_mode = false; | |
if (b[0].length === undefined) { | |
// [c1,c2,c3] mode | |
b = b.map(function(x){ return [x] }); | |
array_mode = true; | |
} | |
var QR = jStat.QR(A); | |
var Q = QR[0]; | |
var R = QR[1]; | |
var attrs = A[0].length; | |
var Q1 = jStat.slice(Q,{col:{end:attrs}}); | |
var R1 = jStat.slice(R,{row:{end:attrs}}); | |
var RI = R_I(R1); | |
var Q2 = jStat.transpose(Q1); | |
if(Q2[0].length === undefined){ | |
Q2 = [Q2]; // The confusing jStat.multifly implementation threat nature process again. | |
} | |
var x = jStat.multiply(jStat.multiply(RI, Q2), b); | |
if(x.length === undefined){ | |
x = [[x]]; // The confusing jStat.multifly implementation threat nature process again. | |
} | |
if (array_mode) | |
return x.map(function(i){ return i[0] }); | |
return x; | |
} | |
return qr_solve; | |
}()), | |
jacobi: function jacobi(a) { | |
var condition = 1; | |
var count = 0; | |
var n = a.length; | |
var e = jStat.identity(n, n); | |
var ev = []; | |
var b, i, j, p, q, maxim, theta, s; | |
// condition === 1 only if tolerance is not reached | |
while (condition === 1) { | |
count++; | |
maxim = a[0][1]; | |
p = 0; | |
q = 1; | |
for (var i = 0; i < n; i++) { | |
for (j = 0; j < n; j++) { | |
if (i != j) { | |
if (maxim < Math.abs(a[i][j])) { | |
maxim = Math.abs(a[i][j]); | |
p = i; | |
q = j; | |
} | |
} | |
} | |
} | |
if (a[p][p] === a[q][q]) | |
theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4; | |
else | |
theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2; | |
s = jStat.identity(n, n); | |
s[p][p] = Math.cos(theta); | |
s[p][q] = -Math.sin(theta); | |
s[q][p] = Math.sin(theta); | |
s[q][q] = Math.cos(theta); | |
// eigen vector matrix | |
e = jStat.multiply(e, s); | |
b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s); | |
a = b; | |
condition = 0; | |
for (var i = 1; i < n; i++) { | |
for (j = 1; j < n; j++) { | |
if (i != j && Math.abs(a[i][j]) > 0.001) { | |
condition = 1; | |
} | |
} | |
} | |
} | |
for (var i = 0; i < n; i++) ev.push(a[i][i]); | |
//returns both the eigenvalue and eigenmatrix | |
return [e, ev]; | |
}, | |
rungekutta: function rungekutta(f, h, p, t_j, u_j, order) { | |
var k1, k2, u_j1, k3, k4; | |
if (order === 2) { | |
while (t_j <= p) { | |
k1 = h * f(t_j, u_j); | |
k2 = h * f(t_j + h, u_j + k1); | |
u_j1 = u_j + (k1 + k2) / 2; | |
u_j = u_j1; | |
t_j = t_j + h; | |
} | |
} | |
if (order === 4) { | |
while (t_j <= p) { | |
k1 = h * f(t_j, u_j); | |
k2 = h * f(t_j + h / 2, u_j + k1 / 2); | |
k3 = h * f(t_j + h / 2, u_j + k2 / 2); | |
k4 = h * f(t_j +h, u_j + k3); | |
u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6; | |
u_j = u_j1; | |
t_j = t_j + h; | |
} | |
} | |
return u_j; | |
}, | |
romberg: function romberg(f, a, b, order) { | |
var i = 0; | |
var h = (b - a) / 2; | |
var x = []; | |
var h1 = []; | |
var g = []; | |
var m, a1, j, k, I, d; | |
while (i < order / 2) { | |
I = f(a); | |
for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j; | |
m = x.length; | |
for (j = 1; j < m - 1; j++) { | |
I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]); | |
} | |
I = (h / 3) * (I + f(b)); | |
g[i] = I; | |
h /= 2; | |
i++; | |
} | |
a1 = g.length; | |
m = 1; | |
while (a1 !== 1) { | |
for (j = 0; j < a1 - 1; j++) | |
h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1); | |
a1 = h1.length; | |
g = h1; | |
h1 = []; | |
m++; | |
} | |
return g; | |
}, | |
richardson: function richardson(X, f, x, h) { | |
function pos(X, x) { | |
var i = 0; | |
var n = X.length; | |
var p; | |
for (; i < n; i++) | |
if (X[i] === x) p = i; | |
return p; | |
} | |
var n = X.length, | |
h_min = Math.abs(x - X[pos(X, x) + 1]), | |
i = 0, | |
g = [], | |
h1 = [], | |
y1, y2, m, a, j; | |
while (h >= h_min) { | |
y1 = pos(X, x + h); | |
y2 = pos(X, x); | |
g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h); | |
h /= 2; | |
i++; | |
} | |
a = g.length; | |
m = 1; | |
while (a != 1) { | |
for (j = 0; j < a - 1; j++) | |
h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1); | |
a = h1.length; | |
g = h1; | |
h1 = []; | |
m++; | |
} | |
return g; | |
}, | |
simpson: function simpson(f, a, b, n) { | |
var h = (b - a) / n; | |
var I = f(a); | |
var x = []; | |
var j = a; | |
var k = 0; | |
var i = 1; | |
var m; | |
for (; j <= b; j = j + h, k++) | |
x[k] = j; | |
m = x.length; | |
for (; i < m - 1; i++) { | |
I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]); | |
} | |
return (h / 3) * (I + f(b)); | |
}, | |
hermite: function hermite(X, F, dF, value) { | |
var n = X.length; | |
var p = 0; | |
var i = 0; | |
var l = []; | |
var dl = []; | |
var A = []; | |
var B = []; | |
var j; | |
for (; i < n; i++) { | |
l[i] = 1; | |
for (j = 0; j < n; j++) { | |
if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]); | |
} | |
dl[i] = 0; | |
for (j = 0; j < n; j++) { | |
if (i != j) dl[i] += 1 / (X [i] - X[j]); | |
} | |
A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]); | |
B[i] = (value - X[i]) * (l[i] * l[i]); | |
p += (A[i] * F[i] + B[i] * dF[i]); | |
} | |
return p; | |
}, | |
lagrange: function lagrange(X, F, value) { | |
var p = 0; | |
var i = 0; | |
var j, l; | |
var n = X.length; | |
for (; i < n; i++) { | |
l = F[i]; | |
for (j = 0; j < n; j++) { | |
// calculating the lagrange polynomial L_i | |
if (i != j) l *= (value - X[j]) / (X[i] - X[j]); | |
} | |
// adding the lagrange polynomials found above | |
p += l; | |
} | |
return p; | |
}, | |
cubic_spline: function cubic_spline(X, F, value) { | |
var n = X.length; | |
var i = 0, j; | |
var A = []; | |
var B = []; | |
var alpha = []; | |
var c = []; | |
var h = []; | |
var b = []; | |
var d = []; | |
for (; i < n - 1; i++) | |
h[i] = X[i + 1] - X[i]; | |
alpha[0] = 0; | |
for (var i = 1; i < n - 1; i++) { | |
alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) - | |
(3 / h[i-1]) * (F[i] - F[i-1]); | |
} | |
for (var i = 1; i < n - 1; i++) { | |
A[i] = []; | |
B[i] = []; | |
A[i][i-1] = h[i-1]; | |
A[i][i] = 2 * (h[i - 1] + h[i]); | |
A[i][i+1] = h[i]; | |
B[i][0] = alpha[i]; | |
} | |
c = jStat.multiply(jStat.inv(A), B); | |
for (j = 0; j < n - 1; j++) { | |
b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3; | |
d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]); | |
} | |
for (j = 0; j < n; j++) { | |
if (X[j] > value) break; | |
} | |
j -= 1; | |
return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) * | |
c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j]; | |
}, | |
gauss_quadrature: function gauss_quadrature() { | |
throw new Error('gauss_quadrature not yet implemented'); | |
}, | |
PCA: function PCA(X) { | |
var m = X.length; | |
var n = X[0].length; | |
var flag = false; | |
var i = 0; | |
var j, temp1; | |
var u = []; | |
var D = []; | |
var result = []; | |
var temp2 = []; | |
var Y = []; | |
var Bt = []; | |
var B = []; | |
var C = []; | |
var V = []; | |
var Vt = []; | |
for (var i = 0; i < m; i++) { | |
u[i] = jStat.sum(X[i]) / n; | |
} | |
for (var i = 0; i < n; i++) { | |
B[i] = []; | |
for(j = 0; j < m; j++) { | |
B[i][j] = X[j][i] - u[j]; | |
} | |
} | |
B = jStat.transpose(B); | |
for (var i = 0; i < m; i++) { | |
C[i] = []; | |
for (j = 0; j < m; j++) { | |
C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1); | |
} | |
} | |
result = jStat.jacobi(C); | |
V = result[0]; | |
D = result[1]; | |
Vt = jStat.transpose(V); | |
for (var i = 0; i < D.length; i++) { | |
for (j = i; j < D.length; j++) { | |
if(D[i] < D[j]) { | |
temp1 = D[i]; | |
D[i] = D[j]; | |
D[j] = temp1; | |
temp2 = Vt[i]; | |
Vt[i] = Vt[j]; | |
Vt[j] = temp2; | |
} | |
} | |
} | |
Bt = jStat.transpose(B); | |
for (var i = 0; i < m; i++) { | |
Y[i] = []; | |
for (j = 0; j < Bt.length; j++) { | |
Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]); | |
} | |
} | |
return [X, D, Vt, Y]; | |
} | |
}); | |
// extend jStat.fn with methods that require one argument | |
(function(funcs) { | |
for (var i = 0; i < funcs.length; i++) (function(passfunc) { | |
jStat.fn[passfunc] = function(arg, func) { | |
var tmpthis = this; | |
// check for callback | |
if (func) { | |
setTimeout(function() { | |
func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg)); | |
}, 15); | |
return this; | |
} | |
if (typeof jStat[passfunc](this, arg) === 'number') | |
return jStat[passfunc](this, arg); | |
else | |
return jStat(jStat[passfunc](this, arg)); | |
}; | |
}(funcs[i])); | |
}('add divide multiply subtract dot pow exp log abs norm angle'.split(' '))); | |
}(jStat, Math)); | |
(function(jStat, Math) { | |
var slice = [].slice; | |
var isNumber = jStat.utils.isNumber; | |
var isArray = jStat.utils.isArray; | |
// flag==true denotes use of sample standard deviation | |
// Z Statistics | |
jStat.extend({ | |
// 2 different parameter lists: | |
// (value, mean, sd) | |
// (value, array, flag) | |
zscore: function zscore() { | |
var args = slice.call(arguments); | |
if (isNumber(args[1])) { | |
return (args[0] - args[1]) / args[2]; | |
} | |
return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]); | |
}, | |
// 3 different paramter lists: | |
// (value, mean, sd, sides) | |
// (zscore, sides) | |
// (value, array, sides, flag) | |
ztest: function ztest() { | |
var args = slice.call(arguments); | |
var z; | |
if (isArray(args[1])) { | |
// (value, array, sides, flag) | |
z = jStat.zscore(args[0],args[1],args[3]); | |
return (args[2] === 1) ? | |
(jStat.normal.cdf(-Math.abs(z), 0, 1)) : | |
(jStat.normal.cdf(-Math.abs(z), 0, 1)*2); | |
} else { | |
if (args.length > 2) { | |
// (value, mean, sd, sides) | |
z = jStat.zscore(args[0],args[1],args[2]); | |
return (args[3] === 1) ? | |
(jStat.normal.cdf(-Math.abs(z),0,1)) : | |
(jStat.normal.cdf(-Math.abs(z),0,1)* 2); | |
} else { | |
// (zscore, sides) | |
z = args[0]; | |
return (args[1] === 1) ? | |
(jStat.normal.cdf(-Math.abs(z),0,1)) : | |
(jStat.normal.cdf(-Math.abs(z),0,1)*2); | |
} | |
} | |
} | |
}); | |
jStat.extend(jStat.fn, { | |
zscore: function zscore(value, flag) { | |
return (value - this.mean()) / this.stdev(flag); | |
}, | |
ztest: function ztest(value, sides, flag) { | |
var zscore = Math.abs(this.zscore(value, flag)); | |
return (sides === 1) ? | |
(jStat.normal.cdf(-zscore, 0, 1)) : | |
(jStat.normal.cdf(-zscore, 0, 1) * 2); | |
} | |
}); | |
// T Statistics | |
jStat.extend({ | |
// 2 parameter lists | |
// (value, mean, sd, n) | |
// (value, array) | |
tscore: function tscore() { | |
var args = slice.call(arguments); | |
return (args.length === 4) ? | |
((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) : | |
((args[0] - jStat.mean(args[1])) / | |
(jStat.stdev(args[1], true) / Math.sqrt(args[1].length))); | |
}, | |
// 3 different paramter lists: | |
// (value, mean, sd, n, sides) | |
// (tscore, n, sides) | |
// (value, array, sides) | |
ttest: function ttest() { | |
var args = slice.call(arguments); | |
var tscore; | |
if (args.length === 5) { | |
tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3])); | |
return (args[4] === 1) ? | |
(jStat.studentt.cdf(-tscore, args[3]-1)) : | |
(jStat.studentt.cdf(-tscore, args[3]-1)*2); | |
} | |
if (isNumber(args[1])) { | |
tscore = Math.abs(args[0]) | |
return (args[2] == 1) ? | |
(jStat.studentt.cdf(-tscore, args[1]-1)) : | |
(jStat.studentt.cdf(-tscore, args[1]-1) * 2); | |
} | |
tscore = Math.abs(jStat.tscore(args[0], args[1])) | |
return (args[2] == 1) ? | |
(jStat.studentt.cdf(-tscore, args[1].length-1)) : | |
(jStat.studentt.cdf(-tscore, args[1].length-1) * 2); | |
} | |
}); | |
jStat.extend(jStat.fn, { | |
tscore: function tscore(value) { | |
return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols())); | |
}, | |
ttest: function ttest(value, sides) { | |
return (sides === 1) ? | |
(1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) : | |
(jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2); | |
} | |
}); | |
// F Statistics | |
jStat.extend({ | |
// Paramter list is as follows: | |
// (array1, array2, array3, ...) | |
// or it is an array of arrays | |
// array of arrays conversion | |
anovafscore: function anovafscore() { | |
var args = slice.call(arguments), | |
expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j; | |
if (args.length === 1) { | |
tmpargs = new Array(args[0].length); | |
for (var i = 0; i < args[0].length; i++) { | |
tmpargs[i] = args[0][i]; | |
} | |
args = tmpargs; | |
} | |
// 2 sample case | |
if (args.length === 2) { | |
return jStat.variance(args[0]) / jStat.variance(args[1]); | |
} | |
// Builds sample array | |
sample = new Array(); | |
for (var i = 0; i < args.length; i++) { | |
sample = sample.concat(args[i]); | |
} | |
sampMean = jStat.mean(sample); | |
// Computes the explained variance | |
expVar = 0; | |
for (var i = 0; i < args.length; i++) { | |
expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2); | |
} | |
expVar /= (args.length - 1); | |
// Computes unexplained variance | |
unexpVar = 0; | |
for (var i = 0; i < args.length; i++) { | |
sampSampMean = jStat.mean(args[i]); | |
for (j = 0; j < args[i].length; j++) { | |
unexpVar += Math.pow(args[i][j] - sampSampMean, 2); | |
} | |
} | |
unexpVar /= (sample.length - args.length); | |
return expVar / unexpVar; | |
}, | |
// 2 different paramter setups | |
// (array1, array2, array3, ...) | |
// (anovafscore, df1, df2) | |
anovaftest: function anovaftest() { | |
var args = slice.call(arguments), | |
df1, df2, n, i; | |
if (isNumber(args[0])) { | |
return 1 - jStat.centralF.cdf(args[0], args[1], args[2]); | |
} | |
anovafscore = jStat.anovafscore(args); | |
df1 = args.length - 1; | |
n = 0; | |
for (var i = 0; i < args.length; i++) { | |
n = n + args[i].length; | |
} | |
df2 = n - df1 - 1; | |
return 1 - jStat.centralF.cdf(anovafscore, df1, df2); | |
}, | |
ftest: function ftest(fscore, df1, df2) { | |
return 1 - jStat.centralF.cdf(fscore, df1, df2); | |
} | |
}); | |
jStat.extend(jStat.fn, { | |
anovafscore: function anovafscore() { | |
return jStat.anovafscore(this.toArray()); | |
}, | |
anovaftes: function anovaftes() { | |
var n = 0; | |
var i; | |
for (var i = 0; i < this.length; i++) { | |
n = n + this[i].length; | |
} | |
return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length); | |
} | |
}); | |
// Tukey's range test | |
jStat.extend({ | |
// 2 parameter lists | |
// (mean1, mean2, n1, n2, sd) | |
// (array1, array2, sd) | |
qscore: function qscore() { | |
var args = slice.call(arguments); | |
var mean1, mean2, n1, n2, sd; | |
if (isNumber(args[0])) { | |
mean1 = args[0]; | |
mean2 = args[1]; | |
n1 = args[2]; | |
n2 = args[3]; | |
sd = args[4]; | |
} else { | |
mean1 = jStat.mean(args[0]); | |
mean2 = jStat.mean(args[1]); | |
n1 = args[0].length; | |
n2 = args[1].length; | |
sd = args[2]; | |
} | |
return Math.abs(mean1 - mean2) / (sd * Math.sqrt((1 / n1 + 1 / n2) / 2)); | |
}, | |
// 3 different parameter lists: | |
// (qscore, n, k) | |
// (mean1, mean2, n1, n2, sd, n, k) | |
// (array1, array2, sd, n, k) | |
qtest: function qtest() { | |
var args = slice.call(arguments); | |
var qscore; | |
if (args.length === 3) { | |
qscore = args[0]; | |
args = args.slice(1); | |
} else if (args.length === 7) { | |
qscore = jStat.qscore(args[0], args[1], args[2], args[3], args[4]); | |
args = args.slice(5); | |
} else { | |
qscore = jStat.qscore(args[0], args[1], args[2]); | |
args = args.slice(3); | |
} | |
var n = args[0]; | |
var k = args[1]; | |
return 1 - jStat.tukey.cdf(qscore, k, n - k); | |
}, | |
tukeyhsd: function tukeyhsd(arrays) { | |
var sd = jStat.pooledstdev(arrays); | |
var means = arrays.map(function (arr) {return jStat.mean(arr);}); | |
var n = arrays.reduce(function (n, arr) {return n + arr.length;}, 0); | |
var results = []; | |
for (var i = 0; i < arrays.length; ++i) { | |
for (var j = i + 1; j < arrays.length; ++j) { | |
var p = jStat.qtest(means[i], means[j], arrays[i].length, arrays[j].length, sd, n, arrays.length); | |
results.push([[i, j], p]); | |
} | |
} | |
return results; | |
} | |
}); | |
// Error Bounds | |
jStat.extend({ | |
// 2 different parameter setups | |
// (value, alpha, sd, n) | |
// (value, alpha, array) | |
normalci: function normalci() { | |
var args = slice.call(arguments), | |
ans = new Array(2), | |
change; | |
if (args.length === 4) { | |
change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) * | |
args[2] / Math.sqrt(args[3])); | |
} else { | |
change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) * | |
jStat.stdev(args[2]) / Math.sqrt(args[2].length)); | |
} | |
ans[0] = args[0] - change; | |
ans[1] = args[0] + change; | |
return ans; | |
}, | |
// 2 different parameter setups | |
// (value, alpha, sd, n) | |
// (value, alpha, array) | |
tci: function tci() { | |
var args = slice.call(arguments), | |
ans = new Array(2), | |
change; | |
if (args.length === 4) { | |
change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) * | |
args[2] / Math.sqrt(args[3])); | |
} else { | |
change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) * | |
jStat.stdev(args[2], true) / Math.sqrt(args[2].length)); | |
} | |
ans[0] = args[0] - change; | |
ans[1] = args[0] + change; | |
return ans; | |
}, | |
significant: function significant(pvalue, alpha) { | |
return pvalue < alpha; | |
} | |
}); | |
jStat.extend(jStat.fn, { | |
normalci: function normalci(value, alpha) { | |
return jStat.normalci(value, alpha, this.toArray()); | |
}, | |
tci: function tci(value, alpha) { | |
return jStat.tci(value, alpha, this.toArray()); | |
} | |
}); | |
// internal method for calculating the z-score for a difference of proportions test | |
function differenceOfProportions(p1, n1, p2, n2) { | |
if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) { | |
throw new Error("Proportions should be greater than 0 and less than 1") | |
} | |
var pooled = (p1 * n1 + p2 * n2) / (n1 + n2); | |
var se = Math.sqrt(pooled * (1 - pooled) * ((1/n1) + (1/n2))); | |
return (p1 - p2) / se; | |
} | |
// Difference of Proportions | |
jStat.extend(jStat.fn, { | |
oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) { | |
var z = differenceOfProportions(p1, n1, p2, n2); | |
return jStat.ztest(z, 1); | |
}, | |
twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) { | |
var z = differenceOfProportions(p1, n1, p2, n2); | |
return jStat.ztest(z, 2); | |
} | |
}); | |
}(jStat, Math)); | |
jStat.models = (function(){ | |
function sub_regress(endog, exog) { | |
return ols(endog, exog); | |
} | |
function sub_regress(exog) { | |
var var_count = exog[0].length; | |
var modelList = jStat.arange(var_count).map(function(endog_index) { | |
var exog_index = | |
jStat.arange(var_count).filter(function(i){return i!==endog_index}); | |
return ols(jStat.col(exog, endog_index).map(function(x){ return x[0] }), | |
jStat.col(exog, exog_index)) | |
}); | |
return modelList; | |
} | |
// do OLS model regress | |
// exog have include const columns ,it will not generate it .In fact, exog is | |
// "design matrix" look at | |
//https://en.wikipedia.org/wiki/Design_matrix | |
function ols(endog, exog) { | |
var nobs = endog.length; | |
var df_model = exog[0].length - 1; | |
var df_resid = nobs-df_model - 1; | |
var coef = jStat.lstsq(exog, endog); | |
var predict = | |
jStat.multiply(exog, coef.map(function(x) { return [x] })) | |
.map(function(p) { return p[0] }); | |
var resid = jStat.subtract(endog, predict); | |
var ybar = jStat.mean(endog); | |
// constant cause problem | |
// var SST = jStat.sum(endog.map(function(y) { | |
// return Math.pow(y-ybar,2); | |
// })); | |
var SSE = jStat.sum(predict.map(function(f) { | |
return Math.pow(f - ybar, 2); | |
})); | |
var SSR = jStat.sum(endog.map(function(y, i) { | |
return Math.pow(y - predict[i], 2); | |
})); | |
var SST = SSE + SSR; | |
var R2 = (SSE / SST); | |
return { | |
exog:exog, | |
endog:endog, | |
nobs:nobs, | |
df_model:df_model, | |
df_resid:df_resid, | |
coef:coef, | |
predict:predict, | |
resid:resid, | |
ybar:ybar, | |
SST:SST, | |
SSE:SSE, | |
SSR:SSR, | |
R2:R2 | |
}; | |
} | |
// H0: b_I=0 | |
// H1: b_I!=0 | |
function t_test(model) { | |
var subModelList = sub_regress(model.exog); | |
//var sigmaHat=jStat.stdev(model.resid); | |
var sigmaHat = Math.sqrt(model.SSR / (model.df_resid)); | |
var seBetaHat = subModelList.map(function(mod) { | |
var SST = mod.SST; | |
var R2 = mod.R2; | |
return sigmaHat / Math.sqrt(SST * (1 - R2)); | |
}); | |
var tStatistic = model.coef.map(function(coef, i) { | |
return (coef - 0) / seBetaHat[i]; | |
}); | |
var pValue = tStatistic.map(function(t) { | |
var leftppf = jStat.studentt.cdf(t, model.df_resid); | |
return (leftppf > 0.5 ? 1 - leftppf : leftppf) * 2; | |
}); | |
var c = jStat.studentt.inv(0.975, model.df_resid); | |
var interval95 = model.coef.map(function(coef, i) { | |
var d = c * seBetaHat[i]; | |
return [coef - d, coef + d]; | |
}) | |
return { | |
se: seBetaHat, | |
t: tStatistic, | |
p: pValue, | |
sigmaHat: sigmaHat, | |
interval95: interval95 | |
}; | |
} | |
function F_test(model) { | |
var F_statistic = | |
(model.R2 / model.df_model) / ((1 - model.R2) / model.df_resid); | |
var fcdf = function(x, n1, n2) { | |
return jStat.beta.cdf(x / (n2 / n1 + x), n1 / 2, n2 / 2) | |
} | |
var pvalue = 1 - fcdf(F_statistic, model.df_model, model.df_resid); | |
return { F_statistic: F_statistic, pvalue: pvalue }; | |
} | |
function ols_wrap(endog, exog) { | |
var model = ols(endog,exog); | |
var ttest = t_test(model); | |
var ftest = F_test(model); | |
// Provide the Wherry / Ezekiel / McNemar / Cohen Adjusted R^2 | |
// Which matches the 'adjusted R^2' provided by R's lm package | |
var adjust_R2 = | |
1 - (1 - model.R2) * ((model.nobs - 1) / (model.df_resid)); | |
model.t = ttest; | |
model.f = ftest; | |
model.adjust_R2 = adjust_R2; | |
return model; | |
} | |
return { ols: ols_wrap }; | |
})(); | |
return jStat; | |
}); | |
/***/ }), | |
/* 11 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var utils = __webpack_require__(1); | |
var error = __webpack_require__(0); | |
exports.UNIQUE = function () { | |
var result = []; | |
for (var i = 0; i < arguments.length; ++i) { | |
var hasElement = false; | |
var element = arguments[i]; | |
// Check if we've already seen this element. | |
for (var j = 0; j < result.length; ++j) { | |
hasElement = result[j] === element; | |
if (hasElement) { break; } | |
} | |
// If we did not find it, add it to the result. | |
if (!hasElement) { | |
result.push(element); | |
} | |
} | |
return result; | |
}; | |
exports.FLATTEN = utils.flatten; | |
exports.ARGS2ARRAY = function () { | |
return Array.prototype.slice.call(arguments, 0); | |
}; | |
exports.REFERENCE = function (context, reference) { | |
if (!arguments.length) { | |
return error.error; | |
} | |
try { | |
var path = reference.split('.'); | |
var result = context; | |
for (var i = 0; i < path.length; ++i) { | |
var step = path[i]; | |
if (step[step.length - 1] === ']') { | |
var opening = step.indexOf('['); | |
var index = step.substring(opening + 1, step.length - 1); | |
result = result[step.substring(0, opening)][index]; | |
} else { | |
result = result[step]; | |
} | |
} | |
return result; | |
} catch (error) {} | |
}; | |
exports.JOIN = function (array, separator) { | |
return array.join(separator); | |
}; | |
exports.NUMBERS = function () { | |
var possibleNumbers = utils.flatten(arguments); | |
return possibleNumbers.filter(function (el) { | |
return typeof el === 'number'; | |
}); | |
}; | |
/***/ }), | |
/* 12 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
var jStat = __webpack_require__(10); | |
var text = __webpack_require__(6); | |
var utils = __webpack_require__(1); | |
var bessel = __webpack_require__(26); | |
function isValidBinaryNumber(number) { | |
return (/^[01]{1,10}$/).test(number); | |
} | |
exports.BESSELI = function(x, n) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(x, n)) { | |
return error.value; | |
} | |
return bessel.besseli(x, n); | |
}; | |
exports.BESSELJ = function(x, n) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(x, n)) { | |
return error.value; | |
} | |
return bessel.besselj(x, n); | |
}; | |
exports.BESSELK = function(x, n) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(x, n)) { | |
return error.value; | |
} | |
return bessel.besselk(x, n); | |
}; | |
exports.BESSELY = function(x, n) { | |
x = utils.parseNumber(x); | |
n = utils.parseNumber(n); | |
if (utils.anyIsError(x, n)) { | |
return error.value; | |
} | |
return bessel.bessely(x, n); | |
}; | |
exports.BIN2DEC = function(number) { | |
// Return error if number is not binary or contains more than 10 characters (10 digits) | |
if (!isValidBinaryNumber(number)) { | |
return error.num; | |
} | |
// Convert binary number to decimal | |
var result = parseInt(number, 2); | |
// Handle negative numbers | |
var stringified = number.toString(); | |
if (stringified.length === 10 && stringified.substring(0, 1) === '1') { | |
return parseInt(stringified.substring(1), 2) - 512; | |
} else { | |
return result; | |
} | |
}; | |
exports.BIN2HEX = function(number, places) { | |
// Return error if number is not binary or contains more than 10 characters (10 digits) | |
if (!isValidBinaryNumber(number)) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character hexadecimal number if number is negative | |
var stringified = number.toString(); | |
if (stringified.length === 10 && stringified.substring(0, 1) === '1') { | |
return (1099511627264 + parseInt(stringified.substring(1), 2)).toString(16); | |
} | |
// Convert binary number to hexadecimal | |
var result = parseInt(number, 2).toString(16); | |
// Return hexadecimal number using the minimum number of characters necessary if places is undefined | |
if (places === undefined) { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.BIN2OCT = function(number, places) { | |
// Return error if number is not binary or contains more than 10 characters (10 digits) | |
if (!isValidBinaryNumber(number)) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character octal number if number is negative | |
var stringified = number.toString(); | |
if (stringified.length === 10 && stringified.substring(0, 1) === '1') { | |
return (1073741312 + parseInt(stringified.substring(1), 2)).toString(8); | |
} | |
// Convert binary number to octal | |
var result = parseInt(number, 2).toString(8); | |
// Return octal number using the minimum number of characters necessary if places is undefined | |
if (places === undefined) { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.BITAND = function(number1, number2) { | |
// Return error if either number is a non-numeric value | |
number1 = utils.parseNumber(number1); | |
number2 = utils.parseNumber(number2); | |
if (utils.anyIsError(number1, number2)) { | |
return error.value; | |
} | |
// Return error if either number is less than 0 | |
if (number1 < 0 || number2 < 0) { | |
return error.num; | |
} | |
// Return error if either number is a non-integer | |
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { | |
return error.num; | |
} | |
// Return error if either number is greater than (2^48)-1 | |
if (number1 > 281474976710655 || number2 > 281474976710655) { | |
return error.num; | |
} | |
// Return bitwise AND of two numbers | |
return number1 & number2; | |
}; | |
exports.BITLSHIFT = function(number, shift) { | |
number = utils.parseNumber(number); | |
shift = utils.parseNumber(shift); | |
if (utils.anyIsError(number, shift)) { | |
return error.value; | |
} | |
// Return error if number is less than 0 | |
if (number < 0) { | |
return error.num; | |
} | |
// Return error if number is a non-integer | |
if (Math.floor(number) !== number) { | |
return error.num; | |
} | |
// Return error if number is greater than (2^48)-1 | |
if (number > 281474976710655) { | |
return error.num; | |
} | |
// Return error if the absolute value of shift is greater than 53 | |
if (Math.abs(shift) > 53) { | |
return error.num; | |
} | |
// Return number shifted by shift bits to the left or to the right if shift is negative | |
return (shift >= 0) ? number << shift : number >> -shift; | |
}; | |
exports.BITOR = function(number1, number2) { | |
number1 = utils.parseNumber(number1); | |
number2 = utils.parseNumber(number2); | |
if (utils.anyIsError(number1, number2)) { | |
return error.value; | |
} | |
// Return error if either number is less than 0 | |
if (number1 < 0 || number2 < 0) { | |
return error.num; | |
} | |
// Return error if either number is a non-integer | |
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { | |
return error.num; | |
} | |
// Return error if either number is greater than (2^48)-1 | |
if (number1 > 281474976710655 || number2 > 281474976710655) { | |
return error.num; | |
} | |
// Return bitwise OR of two numbers | |
return number1 | number2; | |
}; | |
exports.BITRSHIFT = function(number, shift) { | |
number = utils.parseNumber(number); | |
shift = utils.parseNumber(shift); | |
if (utils.anyIsError(number, shift)) { | |
return error.value; | |
} | |
// Return error if number is less than 0 | |
if (number < 0) { | |
return error.num; | |
} | |
// Return error if number is a non-integer | |
if (Math.floor(number) !== number) { | |
return error.num; | |
} | |
// Return error if number is greater than (2^48)-1 | |
if (number > 281474976710655) { | |
return error.num; | |
} | |
// Return error if the absolute value of shift is greater than 53 | |
if (Math.abs(shift) > 53) { | |
return error.num; | |
} | |
// Return number shifted by shift bits to the right or to the left if shift is negative | |
return (shift >= 0) ? number >> shift : number << -shift; | |
}; | |
exports.BITXOR = function(number1, number2) { | |
number1 = utils.parseNumber(number1); | |
number2 = utils.parseNumber(number2); | |
if (utils.anyIsError(number1, number2)) { | |
return error.value; | |
} | |
// Return error if either number is less than 0 | |
if (number1 < 0 || number2 < 0) { | |
return error.num; | |
} | |
// Return error if either number is a non-integer | |
if (Math.floor(number1) !== number1 || Math.floor(number2) !== number2) { | |
return error.num; | |
} | |
// Return error if either number is greater than (2^48)-1 | |
if (number1 > 281474976710655 || number2 > 281474976710655) { | |
return error.num; | |
} | |
// Return bitwise XOR of two numbers | |
return number1 ^ number2; | |
}; | |
exports.COMPLEX = function(real, imaginary, suffix) { | |
real = utils.parseNumber(real); | |
imaginary = utils.parseNumber(imaginary); | |
if (utils.anyIsError(real, imaginary)) { | |
return real; | |
} | |
// Set suffix | |
suffix = (suffix === undefined) ? 'i' : suffix; | |
// Return error if suffix is neither "i" nor "j" | |
if (suffix !== 'i' && suffix !== 'j') { | |
return error.value; | |
} | |
// Return complex number | |
if (real === 0 && imaginary === 0) { | |
return 0; | |
} else if (real === 0) { | |
return (imaginary === 1) ? suffix : imaginary.toString() + suffix; | |
} else if (imaginary === 0) { | |
return real.toString(); | |
} else { | |
var sign = (imaginary > 0) ? '+' : ''; | |
return real.toString() + sign + ((imaginary === 1) ? suffix : imaginary.toString() + suffix); | |
} | |
}; | |
exports.CONVERT = function(number, from_unit, to_unit) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
// List of units supported by CONVERT and units defined by the International System of Units | |
// [Name, Symbol, Alternate symbols, Quantity, ISU, CONVERT, Conversion ratio] | |
var units = [ | |
["a.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], | |
["a.u. of charge", "e", null, "electric_charge", false, false, 1.60217653141414e-19], | |
["a.u. of energy", "Eh", null, "energy", false, false, 4.35974417757576e-18], | |
["a.u. of length", "a?", null, "length", false, false, 5.29177210818182e-11], | |
["a.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], | |
["a.u. of time", "?/Eh", null, "time", false, false, 2.41888432650516e-17], | |
["admiralty knot", "admkn", null, "speed", false, true, 0.514773333], | |
["ampere", "A", null, "electric_current", true, false, 1], | |
["ampere per meter", "A/m", null, "magnetic_field_intensity", true, false, 1], | |
["ångström", "Å", ["ang"], "length", false, true, 1e-10], | |
["are", "ar", null, "area", false, true, 100], | |
["astronomical unit", "ua", null, "length", false, false, 1.49597870691667e-11], | |
["bar", "bar", null, "pressure", false, false, 100000], | |
["barn", "b", null, "area", false, false, 1e-28], | |
["becquerel", "Bq", null, "radioactivity", true, false, 1], | |
["bit", "bit", ["b"], "information", false, true, 1], | |
["btu", "BTU", ["btu"], "energy", false, true, 1055.05585262], | |
["byte", "byte", null, "information", false, true, 8], | |
["candela", "cd", null, "luminous_intensity", true, false, 1], | |
["candela per square metre", "cd/m?", null, "luminance", true, false, 1], | |
["coulomb", "C", null, "electric_charge", true, false, 1], | |
["cubic ångström", "ang3", ["ang^3"], "volume", false, true, 1e-30], | |
["cubic foot", "ft3", ["ft^3"], "volume", false, true, 0.028316846592], | |
["cubic inch", "in3", ["in^3"], "volume", false, true, 0.000016387064], | |
["cubic light-year", "ly3", ["ly^3"], "volume", false, true, 8.46786664623715e-47], | |
["cubic metre", "m?", null, "volume", true, true, 1], | |
["cubic mile", "mi3", ["mi^3"], "volume", false, true, 4168181825.44058], | |
["cubic nautical mile", "Nmi3", ["Nmi^3"], "volume", false, true, 6352182208], | |
["cubic Pica", "Pica3", ["Picapt3", "Pica^3", "Picapt^3"], "volume", false, true, 7.58660370370369e-8], | |
["cubic yard", "yd3", ["yd^3"], "volume", false, true, 0.764554857984], | |
["cup", "cup", null, "volume", false, true, 0.0002365882365], | |
["dalton", "Da", ["u"], "mass", false, false, 1.66053886282828e-27], | |
["day", "d", ["day"], "time", false, true, 86400], | |
["degree", "°", null, "angle", false, false, 0.0174532925199433], | |
["degrees Rankine", "Rank", null, "temperature", false, true, 0.555555555555556], | |
["dyne", "dyn", ["dy"], "force", false, true, 0.00001], | |
["electronvolt", "eV", ["ev"], "energy", false, true, 1.60217656514141], | |
["ell", "ell", null, "length", false, true, 1.143], | |
["erg", "erg", ["e"], "energy", false, true, 1e-7], | |
["farad", "F", null, "electric_capacitance", true, false, 1], | |
["fluid ounce", "oz", null, "volume", false, true, 0.0000295735295625], | |
["foot", "ft", null, "length", false, true, 0.3048], | |
["foot-pound", "flb", null, "energy", false, true, 1.3558179483314], | |
["gal", "Gal", null, "acceleration", false, false, 0.01], | |
["gallon", "gal", null, "volume", false, true, 0.003785411784], | |
["gauss", "G", ["ga"], "magnetic_flux_density", false, true, 1], | |
["grain", "grain", null, "mass", false, true, 0.0000647989], | |
["gram", "g", null, "mass", false, true, 0.001], | |
["gray", "Gy", null, "absorbed_dose", true, false, 1], | |
["gross registered ton", "GRT", ["regton"], "volume", false, true, 2.8316846592], | |
["hectare", "ha", null, "area", false, true, 10000], | |
["henry", "H", null, "inductance", true, false, 1], | |
["hertz", "Hz", null, "frequency", true, false, 1], | |
["horsepower", "HP", ["h"], "power", false, true, 745.69987158227], | |
["horsepower-hour", "HPh", ["hh", "hph"], "energy", false, true, 2684519.538], | |
["hour", "h", ["hr"], "time", false, true, 3600], | |
["imperial gallon (U.K.)", "uk_gal", null, "volume", false, true, 0.00454609], | |
["imperial hundredweight", "lcwt", ["uk_cwt", "hweight"], "mass", false, true, 50.802345], | |
["imperial quart (U.K)", "uk_qt", null, "volume", false, true, 0.0011365225], | |
["imperial ton", "brton", ["uk_ton", "LTON"], "mass", false, true, 1016.046909], | |
["inch", "in", null, "length", false, true, 0.0254], | |
["international acre", "uk_acre", null, "area", false, true, 4046.8564224], | |
["IT calorie", "cal", null, "energy", false, true, 4.1868], | |
["joule", "J", null, "energy", true, true, 1], | |
["katal", "kat", null, "catalytic_activity", true, false, 1], | |
["kelvin", "K", ["kel"], "temperature", true, true, 1], | |
["kilogram", "kg", null, "mass", true, true, 1], | |
["knot", "kn", null, "speed", false, true, 0.514444444444444], | |
["light-year", "ly", null, "length", false, true, 9460730472580800], | |
["litre", "L", ["l", "lt"], "volume", false, true, 0.001], | |
["lumen", "lm", null, "luminous_flux", true, false, 1], | |
["lux", "lx", null, "illuminance", true, false, 1], | |
["maxwell", "Mx", null, "magnetic_flux", false, false, 1e-18], | |
["measurement ton", "MTON", null, "volume", false, true, 1.13267386368], | |
["meter per hour", "m/h", ["m/hr"], "speed", false, true, 0.00027777777777778], | |
["meter per second", "m/s", ["m/sec"], "speed", true, true, 1], | |
["meter per second squared", "m?s??", null, "acceleration", true, false, 1], | |
["parsec", "pc", ["parsec"], "length", false, true, 30856775814671900], | |
["meter squared per second", "m?/s", null, "kinematic_viscosity", true, false, 1], | |
["metre", "m", null, "length", true, true, 1], | |
["miles per hour", "mph", null, "speed", false, true, 0.44704], | |
["millimetre of mercury", "mmHg", null, "pressure", false, false, 133.322], | |
["minute", "?", null, "angle", false, false, 0.000290888208665722], | |
["minute", "min", ["mn"], "time", false, true, 60], | |
["modern teaspoon", "tspm", null, "volume", false, true, 0.000005], | |
["mole", "mol", null, "amount_of_substance", true, false, 1], | |
["morgen", "Morgen", null, "area", false, true, 2500], | |
["n.u. of action", "?", null, "action", false, false, 1.05457168181818e-34], | |
["n.u. of mass", "m?", null, "mass", false, false, 9.10938261616162e-31], | |
["n.u. of speed", "c?", null, "speed", false, false, 299792458], | |
["n.u. of time", "?/(me?c??)", null, "time", false, false, 1.28808866778687e-21], | |
["nautical mile", "M", ["Nmi"], "length", false, true, 1852], | |
["newton", "N", null, "force", true, true, 1], | |
["œrsted", "Oe ", null, "magnetic_field_intensity", false, false, 79.5774715459477], | |
["ohm", "Ω", null, "electric_resistance", true, false, 1], | |
["ounce mass", "ozm", null, "mass", false, true, 0.028349523125], | |
["pascal", "Pa", null, "pressure", true, false, 1], | |
["pascal second", "Pa?s", null, "dynamic_viscosity", true, false, 1], | |
["pferdestärke", "PS", null, "power", false, true, 735.49875], | |
["phot", "ph", null, "illuminance", false, false, 0.0001], | |
["pica (1/6 inch)", "pica", null, "length", false, true, 0.00035277777777778], | |
["pica (1/72 inch)", "Pica", ["Picapt"], "length", false, true, 0.00423333333333333], | |
["poise", "P", null, "dynamic_viscosity", false, false, 0.1], | |
["pond", "pond", null, "force", false, true, 0.00980665], | |
["pound force", "lbf", null, "force", false, true, 4.4482216152605], | |
["pound mass", "lbm", null, "mass", false, true, 0.45359237], | |
["quart", "qt", null, "volume", false, true, 0.000946352946], | |
["radian", "rad", null, "angle", true, false, 1], | |
["second", "?", null, "angle", false, false, 0.00000484813681109536], | |
["second", "s", ["sec"], "time", true, true, 1], | |
["short hundredweight", "cwt", ["shweight"], "mass", false, true, 45.359237], | |
["siemens", "S", null, "electrical_conductance", true, false, 1], | |
["sievert", "Sv", null, "equivalent_dose", true, false, 1], | |
["slug", "sg", null, "mass", false, true, 14.59390294], | |
["square ångström", "ang2", ["ang^2"], "area", false, true, 1e-20], | |
["square foot", "ft2", ["ft^2"], "area", false, true, 0.09290304], | |
["square inch", "in2", ["in^2"], "area", false, true, 0.00064516], | |
["square light-year", "ly2", ["ly^2"], "area", false, true, 8.95054210748189e+31], | |
["square meter", "m?", null, "area", true, true, 1], | |
["square mile", "mi2", ["mi^2"], "area", false, true, 2589988.110336], | |
["square nautical mile", "Nmi2", ["Nmi^2"], "area", false, true, 3429904], | |
["square Pica", "Pica2", ["Picapt2", "Pica^2", "Picapt^2"], "area", false, true, 0.00001792111111111], | |
["square yard", "yd2", ["yd^2"], "area", false, true, 0.83612736], | |
["statute mile", "mi", null, "length", false, true, 1609.344], | |
["steradian", "sr", null, "solid_angle", true, false, 1], | |
["stilb", "sb", null, "luminance", false, false, 0.0001], | |
["stokes", "St", null, "kinematic_viscosity", false, false, 0.0001], | |
["stone", "stone", null, "mass", false, true, 6.35029318], | |
["tablespoon", "tbs", null, "volume", false, true, 0.0000147868], | |
["teaspoon", "tsp", null, "volume", false, true, 0.00000492892], | |
["tesla", "T", null, "magnetic_flux_density", true, true, 1], | |
["thermodynamic calorie", "c", null, "energy", false, true, 4.184], | |
["ton", "ton", null, "mass", false, true, 907.18474], | |
["tonne", "t", null, "mass", false, false, 1000], | |
["U.K. pint", "uk_pt", null, "volume", false, true, 0.00056826125], | |
["U.S. bushel", "bushel", null, "volume", false, true, 0.03523907], | |
["U.S. oil barrel", "barrel", null, "volume", false, true, 0.158987295], | |
["U.S. pint", "pt", ["us_pt"], "volume", false, true, 0.000473176473], | |
["U.S. survey mile", "survey_mi", null, "length", false, true, 1609.347219], | |
["U.S. survey/statute acre", "us_acre", null, "area", false, true, 4046.87261], | |
["volt", "V", null, "voltage", true, false, 1], | |
["watt", "W", null, "power", true, true, 1], | |
["watt-hour", "Wh", ["wh"], "energy", false, true, 3600], | |
["weber", "Wb", null, "magnetic_flux", true, false, 1], | |
["yard", "yd", null, "length", false, true, 0.9144], | |
["year", "yr", null, "time", false, true, 31557600] | |
]; | |
// Binary prefixes | |
// [Name, Prefix power of 2 value, Previx value, Abbreviation, Derived from] | |
var binary_prefixes = { | |
Yi: ["yobi", 80, 1208925819614629174706176, "Yi", "yotta"], | |
Zi: ["zebi", 70, 1180591620717411303424, "Zi", "zetta"], | |
Ei: ["exbi", 60, 1152921504606846976, "Ei", "exa"], | |
Pi: ["pebi", 50, 1125899906842624, "Pi", "peta"], | |
Ti: ["tebi", 40, 1099511627776, "Ti", "tera"], | |
Gi: ["gibi", 30, 1073741824, "Gi", "giga"], | |
Mi: ["mebi", 20, 1048576, "Mi", "mega"], | |
ki: ["kibi", 10, 1024, "ki", "kilo"] | |
}; | |
// Unit prefixes | |
// [Name, Multiplier, Abbreviation] | |
var unit_prefixes = { | |
Y: ["yotta", 1e+24, "Y"], | |
Z: ["zetta", 1e+21, "Z"], | |
E: ["exa", 1e+18, "E"], | |
P: ["peta", 1e+15, "P"], | |
T: ["tera", 1e+12, "T"], | |
G: ["giga", 1e+09, "G"], | |
M: ["mega", 1e+06, "M"], | |
k: ["kilo", 1e+03, "k"], | |
h: ["hecto", 1e+02, "h"], | |
e: ["dekao", 1e+01, "e"], | |
d: ["deci", 1e-01, "d"], | |
c: ["centi", 1e-02, "c"], | |
m: ["milli", 1e-03, "m"], | |
u: ["micro", 1e-06, "u"], | |
n: ["nano", 1e-09, "n"], | |
p: ["pico", 1e-12, "p"], | |
f: ["femto", 1e-15, "f"], | |
a: ["atto", 1e-18, "a"], | |
z: ["zepto", 1e-21, "z"], | |
y: ["yocto", 1e-24, "y"] | |
}; | |
// Initialize units and multipliers | |
var from = null; | |
var to = null; | |
var base_from_unit = from_unit; | |
var base_to_unit = to_unit; | |
var from_multiplier = 1; | |
var to_multiplier = 1; | |
var alt; | |
// Lookup from and to units | |
for (var i = 0; i < units.length; i++) { | |
alt = (units[i][2] === null) ? [] : units[i][2]; | |
if (units[i][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { | |
from = units[i]; | |
} | |
if (units[i][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { | |
to = units[i]; | |
} | |
} | |
// Lookup from prefix | |
if (from === null) { | |
var from_binary_prefix = binary_prefixes[from_unit.substring(0, 2)]; | |
var from_unit_prefix = unit_prefixes[from_unit.substring(0, 1)]; | |
// Handle dekao unit prefix (only unit prefix with two characters) | |
if (from_unit.substring(0, 2) === 'da') { | |
from_unit_prefix = ["dekao", 1e+01, "da"]; | |
} | |
// Handle binary prefixes first (so that 'Yi' is processed before 'Y') | |
if (from_binary_prefix) { | |
from_multiplier = from_binary_prefix[2]; | |
base_from_unit = from_unit.substring(2); | |
} else if (from_unit_prefix) { | |
from_multiplier = from_unit_prefix[1]; | |
base_from_unit = from_unit.substring(from_unit_prefix[2].length); | |
} | |
// Lookup from unit | |
for (var j = 0; j < units.length; j++) { | |
alt = (units[j][2] === null) ? [] : units[j][2]; | |
if (units[j][1] === base_from_unit || alt.indexOf(base_from_unit) >= 0) { | |
from = units[j]; | |
} | |
} | |
} | |
// Lookup to prefix | |
if (to === null) { | |
var to_binary_prefix = binary_prefixes[to_unit.substring(0, 2)]; | |
var to_unit_prefix = unit_prefixes[to_unit.substring(0, 1)]; | |
// Handle dekao unit prefix (only unit prefix with two characters) | |
if (to_unit.substring(0, 2) === 'da') { | |
to_unit_prefix = ["dekao", 1e+01, "da"]; | |
} | |
// Handle binary prefixes first (so that 'Yi' is processed before 'Y') | |
if (to_binary_prefix) { | |
to_multiplier = to_binary_prefix[2]; | |
base_to_unit = to_unit.substring(2); | |
} else if (to_unit_prefix) { | |
to_multiplier = to_unit_prefix[1]; | |
base_to_unit = to_unit.substring(to_unit_prefix[2].length); | |
} | |
// Lookup to unit | |
for (var k = 0; k < units.length; k++) { | |
alt = (units[k][2] === null) ? [] : units[k][2]; | |
if (units[k][1] === base_to_unit || alt.indexOf(base_to_unit) >= 0) { | |
to = units[k]; | |
} | |
} | |
} | |
// Return error if a unit does not exist | |
if (from === null || to === null) { | |
return error.na; | |
} | |
// Return error if units represent different quantities | |
if (from[3] !== to[3]) { | |
return error.na; | |
} | |
// Return converted number | |
return number * from[6] * from_multiplier / (to[6] * to_multiplier); | |
}; | |
exports.DEC2BIN = function(number, places) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
// Return error if number is not decimal, is lower than -512, or is greater than 511 | |
if (!/^-?[0-9]{1,3}$/.test(number) || number < -512 || number > 511) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character binary number if number is negative | |
if (number < 0) { | |
return '1' + text.REPT('0', 9 - (512 + number).toString(2).length) + (512 + number).toString(2); | |
} | |
// Convert decimal number to binary | |
var result = parseInt(number, 10).toString(2); | |
// Return binary number using the minimum number of characters necessary if places is undefined | |
if (typeof places === 'undefined') { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.DEC2HEX = function(number, places) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
// Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 | |
if (!/^-?[0-9]{1,12}$/.test(number) || number < -549755813888 || number > 549755813887) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character hexadecimal number if number is negative | |
if (number < 0) { | |
return (1099511627776 + number).toString(16); | |
} | |
// Convert decimal number to hexadecimal | |
var result = parseInt(number, 10).toString(16); | |
// Return hexadecimal number using the minimum number of characters necessary if places is undefined | |
if (typeof places === 'undefined') { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.DEC2OCT = function(number, places) { | |
number = utils.parseNumber(number); | |
if (number instanceof Error) { | |
return number; | |
} | |
// Return error if number is not decimal, is lower than -549755813888, or is greater than 549755813887 | |
if (!/^-?[0-9]{1,9}$/.test(number) || number < -536870912 || number > 536870911) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character octal number if number is negative | |
if (number < 0) { | |
return (1073741824 + number).toString(8); | |
} | |
// Convert decimal number to octal | |
var result = parseInt(number, 10).toString(8); | |
// Return octal number using the minimum number of characters necessary if places is undefined | |
if (typeof places === 'undefined') { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.DELTA = function(number1, number2) { | |
// Set number2 to zero if undefined | |
number2 = (number2 === undefined) ? 0 : number2; | |
number1 = utils.parseNumber(number1); | |
number2 = utils.parseNumber(number2); | |
if (utils.anyIsError(number1, number2)) { | |
return error.value; | |
} | |
// Return delta | |
return (number1 === number2) ? 1 : 0; | |
}; | |
// TODO: why is upper_bound not used ? The excel documentation has no examples with upper_bound | |
exports.ERF = function(lower_bound, upper_bound) { | |
// Set number2 to zero if undefined | |
upper_bound = (upper_bound === undefined) ? 0 : upper_bound; | |
lower_bound = utils.parseNumber(lower_bound); | |
upper_bound = utils.parseNumber(upper_bound); | |
if (utils.anyIsError(lower_bound, upper_bound)) { | |
return error.value; | |
} | |
return jStat.erf(lower_bound); | |
}; | |
// TODO | |
exports.ERF.PRECISE = function() { | |
throw new Error('ERF.PRECISE is not implemented'); | |
}; | |
exports.ERFC = function(x) { | |
// Return error if x is not a number | |
if (isNaN(x)) { | |
return error.value; | |
} | |
return jStat.erfc(x); | |
}; | |
// TODO | |
exports.ERFC.PRECISE = function() { | |
throw new Error('ERFC.PRECISE is not implemented'); | |
}; | |
exports.GESTEP = function(number, step) { | |
step = step || 0; | |
number = utils.parseNumber(number); | |
if (utils.anyIsError(step, number)) { | |
return number; | |
} | |
// Return delta | |
return (number >= step) ? 1 : 0; | |
}; | |
exports.HEX2BIN = function(number, places) { | |
// Return error if number is not hexadecimal or contains more than ten characters (10 digits) | |
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Check if number is negative | |
var negative = (number.length === 10 && number.substring(0, 1).toLowerCase() === 'f') ? true : false; | |
// Convert hexadecimal number to decimal | |
var decimal = (negative) ? parseInt(number, 16) - 1099511627776 : parseInt(number, 16); | |
// Return error if number is lower than -512 or greater than 511 | |
if (decimal < -512 || decimal > 511) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character binary number if number is negative | |
if (negative) { | |
return '1' + text.REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); | |
} | |
// Convert decimal number to binary | |
var result = decimal.toString(2); | |
// Return binary number using the minimum number of characters necessary if places is undefined | |
if (places === undefined) { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.HEX2DEC = function(number) { | |
// Return error if number is not hexadecimal or contains more than ten characters (10 digits) | |
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Convert hexadecimal number to decimal | |
var decimal = parseInt(number, 16); | |
// Return decimal number | |
return (decimal >= 549755813888) ? decimal - 1099511627776 : decimal; | |
}; | |
exports.HEX2OCT = function(number, places) { | |
// Return error if number is not hexadecimal or contains more than ten characters (10 digits) | |
if (!/^[0-9A-Fa-f]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Convert hexadecimal number to decimal | |
var decimal = parseInt(number, 16); | |
// Return error if number is positive and greater than 0x1fffffff (536870911) | |
if (decimal > 536870911 && decimal < 1098974756864) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character octal number if number is negative | |
if (decimal >= 1098974756864) { | |
return (decimal - 1098437885952).toString(8); | |
} | |
// Convert decimal number to octal | |
var result = decimal.toString(8); | |
// Return octal number using the minimum number of characters necessary if places is undefined | |
if (places === undefined) { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.IMABS = function(inumber) { | |
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
// Return error if either coefficient is not a number | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return absolute value of complex number | |
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); | |
}; | |
exports.IMAGINARY = function(inumber) { | |
if (inumber === undefined || inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Return 0 if inumber is equal to 0 | |
if (inumber === 0 || inumber === '0') { | |
return 0; | |
} | |
// Handle special cases | |
if (['i', 'j'].indexOf(inumber) >= 0) { | |
return 1; | |
} | |
// Normalize imaginary coefficient | |
inumber = inumber.replace('+i', '+1i').replace('-i', '-1i').replace('+j', '+1j').replace('-j', '-1j'); | |
// Lookup sign | |
var plus = inumber.indexOf('+'); | |
var minus = inumber.indexOf('-'); | |
if (plus === 0) { | |
plus = inumber.indexOf('+', 1); | |
} | |
if (minus === 0) { | |
minus = inumber.indexOf('-', 1); | |
} | |
// Lookup imaginary unit | |
var last = inumber.substring(inumber.length - 1, inumber.length); | |
var unit = (last === 'i' || last === 'j'); | |
if (plus >= 0 || minus >= 0) { | |
// Return error if imaginary unit is neither i nor j | |
if (!unit) { | |
return error.num; | |
} | |
// Return imaginary coefficient of complex number | |
if (plus >= 0) { | |
return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? | |
error.num : | |
Number(inumber.substring(plus + 1, inumber.length - 1)); | |
} else { | |
return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? | |
error.num : | |
-Number(inumber.substring(minus + 1, inumber.length - 1)); | |
} | |
} else { | |
if (unit) { | |
return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : inumber.substring(0, inumber.length - 1); | |
} else { | |
return (isNaN(inumber)) ? error.num : 0; | |
} | |
} | |
}; | |
exports.IMARGUMENT = function(inumber) { | |
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
// Return error if either coefficient is not a number | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return error if inumber is equal to zero | |
if (x === 0 && y === 0) { | |
return error.div0; | |
} | |
// Return PI/2 if x is equal to zero and y is positive | |
if (x === 0 && y > 0) { | |
return Math.PI / 2; | |
} | |
// Return -PI/2 if x is equal to zero and y is negative | |
if (x === 0 && y < 0) { | |
return -Math.PI / 2; | |
} | |
// Return zero if x is negative and y is equal to zero | |
if (y === 0 && x > 0) { | |
return 0; | |
} | |
// Return zero if x is negative and y is equal to zero | |
if (y === 0 && x < 0) { | |
return -Math.PI; | |
} | |
// Return argument of complex number | |
if (x > 0) { | |
return Math.atan(y / x); | |
} else if (x < 0 && y >= 0) { | |
return Math.atan(y / x) + Math.PI; | |
} else { | |
return Math.atan(y / x) - Math.PI; | |
} | |
}; | |
exports.IMCONJUGATE = function(inumber) { | |
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return conjugate of complex number | |
return (y !== 0) ? exports.COMPLEX(x, -y, unit) : inumber; | |
}; | |
exports.IMCOS = function(inumber) { | |
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return cosine of complex number | |
return exports.COMPLEX(Math.cos(x) * (Math.exp(y) + Math.exp(-y)) / 2, -Math.sin(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); | |
}; | |
exports.IMCOSH = function(inumber) { | |
// Lookup real and imaginary coefficients using exports.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return hyperbolic cosine of complex number | |
return exports.COMPLEX(Math.cos(y) * (Math.exp(x) + Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) - Math.exp(-x)) / 2, unit); | |
}; | |
exports.IMCOT = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return cotangent of complex number | |
return exports.IMDIV(exports.IMCOS(inumber), exports.IMSIN(inumber)); | |
}; | |
exports.IMDIV = function(inumber1, inumber2) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var a = exports.IMREAL(inumber1); | |
var b = exports.IMAGINARY(inumber1); | |
var c = exports.IMREAL(inumber2); | |
var d = exports.IMAGINARY(inumber2); | |
if (utils.anyIsError(a, b, c, d)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit1 = inumber1.substring(inumber1.length - 1); | |
var unit2 = inumber2.substring(inumber2.length - 1); | |
var unit = 'i'; | |
if (unit1 === 'j') { | |
unit = 'j'; | |
} else if (unit2 === 'j') { | |
unit = 'j'; | |
} | |
// Return error if inumber2 is null | |
if (c === 0 && d === 0) { | |
return error.num; | |
} | |
// Return exponential of complex number | |
var den = c * c + d * d; | |
return exports.COMPLEX((a * c + b * d) / den, (b * c - a * d) / den, unit); | |
}; | |
exports.IMEXP = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return exponential of complex number | |
var e = Math.exp(x); | |
return exports.COMPLEX(e * Math.cos(y), e * Math.sin(y), unit); | |
}; | |
exports.IMLN = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return exponential of complex number | |
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)), Math.atan(y / x), unit); | |
}; | |
exports.IMLOG10 = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return exponential of complex number | |
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(10), Math.atan(y / x) / Math.log(10), unit); | |
}; | |
exports.IMLOG2 = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return exponential of complex number | |
return exports.COMPLEX(Math.log(Math.sqrt(x * x + y * y)) / Math.log(2), Math.atan(y / x) / Math.log(2), unit); | |
}; | |
exports.IMPOWER = function(inumber, number) { | |
number = utils.parseNumber(number); | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(number, x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Calculate power of modulus | |
var p = Math.pow(exports.IMABS(inumber), number); | |
// Calculate argument | |
var t = exports.IMARGUMENT(inumber); | |
// Return exponential of complex number | |
return exports.COMPLEX(p * Math.cos(number * t), p * Math.sin(number * t), unit); | |
}; | |
exports.IMPRODUCT = function() { | |
// Initialize result | |
var result = arguments[0]; | |
if (!arguments.length) { | |
return error.value; | |
} | |
// Loop on all numbers | |
for (var i = 1; i < arguments.length; i++) { | |
// Lookup coefficients of two complex numbers | |
var a = exports.IMREAL(result); | |
var b = exports.IMAGINARY(result); | |
var c = exports.IMREAL(arguments[i]); | |
var d = exports.IMAGINARY(arguments[i]); | |
if (utils.anyIsError(a, b, c, d)) { | |
return error.value; | |
} | |
// Complute product of two complex numbers | |
result = exports.COMPLEX(a * c - b * d, a * d + b * c); | |
} | |
// Return product of complex numbers | |
return result; | |
}; | |
exports.IMREAL = function(inumber) { | |
if (inumber === undefined || inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Return 0 if inumber is equal to 0 | |
if (inumber === 0 || inumber === '0') { | |
return 0; | |
} | |
// Handle special cases | |
if (['i', '+i', '1i', '+1i', '-i', '-1i', 'j', '+j', '1j', '+1j', '-j', '-1j'].indexOf(inumber) >= 0) { | |
return 0; | |
} | |
// Lookup sign | |
var plus = inumber.indexOf('+'); | |
var minus = inumber.indexOf('-'); | |
if (plus === 0) { | |
plus = inumber.indexOf('+', 1); | |
} | |
if (minus === 0) { | |
minus = inumber.indexOf('-', 1); | |
} | |
// Lookup imaginary unit | |
var last = inumber.substring(inumber.length - 1, inumber.length); | |
var unit = (last === 'i' || last === 'j'); | |
if (plus >= 0 || minus >= 0) { | |
// Return error if imaginary unit is neither i nor j | |
if (!unit) { | |
return error.num; | |
} | |
// Return real coefficient of complex number | |
if (plus >= 0) { | |
return (isNaN(inumber.substring(0, plus)) || isNaN(inumber.substring(plus + 1, inumber.length - 1))) ? | |
error.num : | |
Number(inumber.substring(0, plus)); | |
} else { | |
return (isNaN(inumber.substring(0, minus)) || isNaN(inumber.substring(minus + 1, inumber.length - 1))) ? | |
error.num : | |
Number(inumber.substring(0, minus)); | |
} | |
} else { | |
if (unit) { | |
return (isNaN(inumber.substring(0, inumber.length - 1))) ? error.num : 0; | |
} else { | |
return (isNaN(inumber)) ? error.num : inumber; | |
} | |
} | |
}; | |
exports.IMSEC = function(inumber) { | |
// Return error if inumber is a logical value | |
if (inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return secant of complex number | |
return exports.IMDIV('1', exports.IMCOS(inumber)); | |
}; | |
exports.IMSECH = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return hyperbolic secant of complex number | |
return exports.IMDIV('1', exports.IMCOSH(inumber)); | |
}; | |
exports.IMSIN = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return sine of complex number | |
return exports.COMPLEX(Math.sin(x) * (Math.exp(y) + Math.exp(-y)) / 2, Math.cos(x) * (Math.exp(y) - Math.exp(-y)) / 2, unit); | |
}; | |
exports.IMSINH = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Return hyperbolic sine of complex number | |
return exports.COMPLEX(Math.cos(y) * (Math.exp(x) - Math.exp(-x)) / 2, Math.sin(y) * (Math.exp(x) + Math.exp(-x)) / 2, unit); | |
}; | |
exports.IMSQRT = function(inumber) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit = inumber.substring(inumber.length - 1); | |
unit = (unit === 'i' || unit === 'j') ? unit : 'i'; | |
// Calculate power of modulus | |
var s = Math.sqrt(exports.IMABS(inumber)); | |
// Calculate argument | |
var t = exports.IMARGUMENT(inumber); | |
// Return exponential of complex number | |
return exports.COMPLEX(s * Math.cos(t / 2), s * Math.sin(t / 2), unit); | |
}; | |
exports.IMCSC = function (inumber) { | |
// Return error if inumber is a logical value | |
if (inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
// Return error if either coefficient is not a number | |
if (utils.anyIsError(x, y)) { | |
return error.num; | |
} | |
// Return cosecant of complex number | |
return exports.IMDIV('1', exports.IMSIN(inumber)); | |
}; | |
exports.IMCSCH = function (inumber) { | |
// Return error if inumber is a logical value | |
if (inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
// Return error if either coefficient is not a number | |
if (utils.anyIsError(x, y)) { | |
return error.num; | |
} | |
// Return hyperbolic cosecant of complex number | |
return exports.IMDIV('1', exports.IMSINH(inumber)); | |
}; | |
exports.IMSUB = function(inumber1, inumber2) { | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var a = this.IMREAL(inumber1); | |
var b = this.IMAGINARY(inumber1); | |
var c = this.IMREAL(inumber2); | |
var d = this.IMAGINARY(inumber2); | |
if (utils.anyIsError(a, b, c, d)) { | |
return error.value; | |
} | |
// Lookup imaginary unit | |
var unit1 = inumber1.substring(inumber1.length - 1); | |
var unit2 = inumber2.substring(inumber2.length - 1); | |
var unit = 'i'; | |
if (unit1 === 'j') { | |
unit = 'j'; | |
} else if (unit2 === 'j') { | |
unit = 'j'; | |
} | |
// Return _ of two complex numbers | |
return this.COMPLEX(a - c, b - d, unit); | |
}; | |
exports.IMSUM = function() { | |
if (!arguments.length) { | |
return error.value; | |
} | |
var args = utils.flatten(arguments); | |
// Initialize result | |
var result = args[0]; | |
// Loop on all numbers | |
for (var i = 1; i < args.length; i++) { | |
// Lookup coefficients of two complex numbers | |
var a = this.IMREAL(result); | |
var b = this.IMAGINARY(result); | |
var c = this.IMREAL(args[i]); | |
var d = this.IMAGINARY(args[i]); | |
if (utils.anyIsError(a, b, c, d)) { | |
return error.value; | |
} | |
// Complute product of two complex numbers | |
result = this.COMPLEX(a + c, b + d); | |
} | |
// Return sum of complex numbers | |
return result; | |
}; | |
exports.IMTAN = function(inumber) { | |
// Return error if inumber is a logical value | |
if (inumber === true || inumber === false) { | |
return error.value; | |
} | |
// Lookup real and imaginary coefficients using Formula.js [http://formulajs.org] | |
var x = exports.IMREAL(inumber); | |
var y = exports.IMAGINARY(inumber); | |
if (utils.anyIsError(x, y)) { | |
return error.value; | |
} | |
// Return tangent of complex number | |
return this.IMDIV(this.IMSIN(inumber), this.IMCOS(inumber)); | |
}; | |
exports.OCT2BIN = function(number, places) { | |
// Return error if number is not hexadecimal or contains more than ten characters (10 digits) | |
if (!/^[0-7]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Check if number is negative | |
var negative = (number.length === 10 && number.substring(0, 1) === '7') ? true : false; | |
// Convert octal number to decimal | |
var decimal = (negative) ? parseInt(number, 8) - 1073741824 : parseInt(number, 8); | |
// Return error if number is lower than -512 or greater than 511 | |
if (decimal < -512 || decimal > 511) { | |
return error.num; | |
} | |
// Ignore places and return a 10-character binary number if number is negative | |
if (negative) { | |
return '1' + text.REPT('0', 9 - (512 + decimal).toString(2).length) + (512 + decimal).toString(2); | |
} | |
// Convert decimal number to binary | |
var result = decimal.toString(2); | |
// Return binary number using the minimum number of characters necessary if places is undefined | |
if (typeof places === 'undefined') { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
exports.OCT2DEC = function(number) { | |
// Return error if number is not octal or contains more than ten characters (10 digits) | |
if (!/^[0-7]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Convert octal number to decimal | |
var decimal = parseInt(number, 8); | |
// Return decimal number | |
return (decimal >= 536870912) ? decimal - 1073741824 : decimal; | |
}; | |
exports.OCT2HEX = function(number, places) { | |
// Return error if number is not octal or contains more than ten characters (10 digits) | |
if (!/^[0-7]{1,10}$/.test(number)) { | |
return error.num; | |
} | |
// Convert octal number to decimal | |
var decimal = parseInt(number, 8); | |
// Ignore places and return a 10-character octal number if number is negative | |
if (decimal >= 536870912) { | |
return 'ff' + (decimal + 3221225472).toString(16); | |
} | |
// Convert decimal number to hexadecimal | |
var result = decimal.toString(16); | |
// Return hexadecimal number using the minimum number of characters necessary if places is undefined | |
if (places === undefined) { | |
return result; | |
} else { | |
// Return error if places is nonnumeric | |
if (isNaN(places)) { | |
return error.value; | |
} | |
// Return error if places is negative | |
if (places < 0) { | |
return error.num; | |
} | |
// Truncate places in case it is not an integer | |
places = Math.floor(places); | |
// Pad return value with leading 0s (zeros) if necessary (using Underscore.string) | |
return (places >= result.length) ? text.REPT('0', places - result.length) + result : error.num; | |
} | |
}; | |
/***/ }), | |
/* 13 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
var SUPPORTED_FORMULAS = ['ABS', 'ACCRINT', 'ACOS', 'ACOSH', 'ACOT', 'ACOTH', 'ADD', 'AGGREGATE', 'AND', 'ARABIC', 'ARGS2ARRAY', 'ASIN', 'ASINH', 'ATAN', 'ATAN2', 'ATANH', 'AVEDEV', 'AVERAGE', 'AVERAGEA', 'AVERAGEIF', 'AVERAGEIFS', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BETADIST', 'BETAINV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.DIST.RANGE', 'BINOM.INV', 'BINOMDIST', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING', 'CEILINGMATH', 'CEILINGPRECISE', 'CHAR', 'CHISQ.DIST', 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHOOSE', 'CHOOSE', 'CLEAN', 'CODE', 'COLUMN', 'COLUMNS', 'COMBIN', 'COMBINA', 'COMPLEX', 'CONCATENATE', 'CONFIDENCE', 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'CONVERT', 'CORREL', 'COS', 'COSH', 'COT', 'COTH', 'COUNT', 'COUNTA', 'COUNTBLANK', 'COUNTIF', 'COUNTIFS', 'COUNTIN', 'COUNTUNIQUE', 'COVARIANCE.P', 'COVARIANCE.S', 'CSC', 'CSCH', 'CUMIPMT', 'CUMPRINC', 'DATE', 'DATEVALUE', 'DAY', 'DAYS', 'DAYS360', 'DB', 'DDB', 'DEC2BIN', 'DEC2HEX', 'DEC2OCT', 'DECIMAL', 'DEGREES', 'DELTA', 'DEVSQ', 'DIVIDE', 'DOLLARDE', 'DOLLARFR', 'E', 'EDATE', 'EFFECT', 'EOMONTH', 'EQ', 'ERF', 'ERFC', 'EVEN', 'EXACT', 'EXP', 'EXPON.DIST', 'EXPONDIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT', 'FACT', 'FACTDOUBLE', 'FALSE', 'FDIST', 'FDISTRT', 'FIND', 'FINV', 'FINVRT', 'FISHER', 'FISHERINV', 'FLATTEN', 'FLOOR', 'FORECAST', 'FREQUENCY', 'FV', 'FVSCHEDULE', 'GAMMA', 'GAMMA.DIST', 'GAMMA.INV', 'GAMMADIST', 'GAMMAINV', 'GAMMALN', 'GAMMALN.PRECISE', 'GAUSS', 'GCD', 'GEOMEAN', 'GESTEP', 'GROWTH', 'GTE', 'HARMEAN', 'HEX2BIN', 'HEX2DEC', 'HEX2OCT', 'HOUR', 'HTML2TEXT', 'HYPGEOM.DIST', 'HYPGEOMDIST', 'IF', 'IMABS', 'IMAGINARY', 'IMARGUMENT', 'IMCONJUGATE', 'IMCOS', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMDIV', 'IMEXP', 'IMLN', 'IMLOG10', 'IMLOG2', 'IMPOWER', 'IMPRODUCT', 'IMREAL', 'IMSEC', 'IMSECH', 'IMSIN', 'IMSINH', 'IMSQRT', 'IMSUB', 'IMSUM', 'IMTAN', 'INT', 'INTERCEPT', 'INTERVAL', 'IPMT', 'IRR', 'ISBINARY', 'ISBLANK', 'ISEVEN', 'ISLOGICAL', 'ISNONTEXT', 'ISNUMBER', 'ISODD', 'ISODD', 'ISOWEEKNUM', 'ISPMT', 'ISTEXT', 'JOIN', 'KURT', 'LARGE', 'LCM', 'LEFT', 'LEN', 'LINEST', 'LN', 'LOG', 'LOG10', 'LOGEST', 'LOGNORM.DIST', 'LOGNORM.INV', 'LOGNORMDIST', 'LOGNORMINV', 'LOWER', 'LT', 'LTE', 'MATCH', 'MAX', 'MAXA', 'MEDIAN', 'MID', 'MIN', 'MINA', 'MINUS', 'MINUTE', 'MIRR', 'MOD', 'MODE.MULT', 'MODE.SNGL', 'MODEMULT', 'MODESNGL', 'MONTH', 'MROUND', 'MULTINOMIAL', 'MULTIPLY', 'NE', 'NEGBINOM.DIST', 'NEGBINOMDIST', 'NETWORKDAYS', 'NOMINAL', 'NORM.DIST', 'NORM.INV', 'NORM.S.DIST', 'NORM.S.INV', 'NORMDIST', 'NORMINV', 'NORMSDIST', 'NORMSINV', 'NOT', 'NOW', 'NPER', 'NPV', 'NUMBERS', 'OCT2BIN', 'OCT2DEC', 'OCT2HEX', 'ODD', 'OR', 'PDURATION', 'PEARSON', 'PERCENTILEEXC', 'PERCENTILEINC', 'PERCENTRANKEXC', 'PERCENTRANKINC', 'PERMUT', 'PERMUTATIONA', 'PHI', 'PI', 'PMT', 'POISSON.DIST', 'POISSONDIST', 'POW', 'POWER', 'PPMT', 'PROB', 'PRODUCT', 'PROPER', 'PV', 'QUARTILE.EXC', 'QUARTILE.INC', 'QUARTILEEXC', 'QUARTILEINC', 'QUOTIENT', 'RADIANS', 'RAND', 'RANDBETWEEN', 'RANK.AVG', 'RANK.EQ', 'RANKAVG', 'RANKEQ', 'RATE', 'REFERENCE', 'REGEXEXTRACT', 'REGEXMATCH', 'REGEXREPLACE', 'REPLACE', 'REPT', 'RIGHT', 'ROMAN', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'ROW', 'ROWS', 'RRI', 'RSQ', 'SEARCH', 'SEC', 'SECH', 'SECOND', 'SERIESSUM', 'SIGN', 'SIN', 'SINH', 'SKEW', 'SKEW.P', 'SKEWP', 'SLN', 'SLOPE', 'SMALL', 'SPLIT', 'SPLIT', 'SQRT', 'SQRTPI', 'STANDARDIZE', 'STDEV.P', 'STDEV.S', 'STDEVA', 'STDEVP', 'STDEVPA', 'STDEVS', 'STEYX', 'SUBSTITUTE', 'SUBTOTAL', 'SUM', 'SUMIF', 'SUMIFS', 'SUMPRODUCT', 'SUMSQ', 'SUMX2MY2', 'SUMX2PY2', 'SUMXMY2', 'SWITCH', 'SYD', 'T', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'TAN', 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TDIST2T', 'TDISTRT', 'TIME', 'TIMEVALUE', 'TINV', 'TINV2T', 'TODAY', 'TRANSPOSE', 'TREND', 'TRIM', 'TRIMMEAN', 'TRUE', 'TRUNC', 'UNICHAR', 'UNICODE', 'UNIQUE', 'UPPER', 'VAR.P', 'VAR.S', 'VARA', 'VARP', 'VARPA', 'VARS', 'WEEKDAY', 'WEEKNUM', 'WEIBULL.DIST', 'WEIBULLDIST', 'WORKDAY', 'XIRR', 'XNPV', 'XOR', 'YEAR', 'YEARFRAC']; | |
exports['default'] = SUPPORTED_FORMULAS; | |
/***/ }), | |
/* 14 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.rowLabelToIndex = rowLabelToIndex; | |
exports.rowIndexToLabel = rowIndexToLabel; | |
exports.columnLabelToIndex = columnLabelToIndex; | |
exports.columnIndexToLabel = columnIndexToLabel; | |
exports.extractLabel = extractLabel; | |
exports.toLabel = toLabel; | |
/** | |
* Convert row label to index. | |
* | |
* @param {String} label Row label (eq. '1', '5') | |
* @returns {Number} Returns -1 if label is not recognized otherwise proper row index. | |
*/ | |
function rowLabelToIndex(label) { | |
var result = parseInt(label, 10); | |
if (isNaN(result)) { | |
result = -1; | |
} else { | |
result = Math.max(result - 1, -1); | |
} | |
return result; | |
} | |
/** | |
* Convert row index to label. | |
* | |
* @param {Number} row Row index. | |
* @returns {String} Returns row label (eq. '1', '7'). | |
*/ | |
function rowIndexToLabel(row) { | |
var result = ''; | |
if (row >= 0) { | |
result = '' + (row + 1); | |
} | |
return result; | |
} | |
var COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
var COLUMN_LABEL_BASE_LENGTH = COLUMN_LABEL_BASE.length; | |
/** | |
* Convert column label to index. | |
* | |
* @param {String} label Column label (eq. 'ABB', 'CNQ') | |
* @returns {Number} Returns -1 if label is not recognized otherwise proper column index. | |
*/ | |
function columnLabelToIndex(label) { | |
var result = 0; | |
if (typeof label === 'string') { | |
label = label.toUpperCase(); | |
for (var i = 0, j = label.length - 1; i < label.length; i += 1, j -= 1) { | |
result += Math.pow(COLUMN_LABEL_BASE_LENGTH, j) * (COLUMN_LABEL_BASE.indexOf(label[i]) + 1); | |
} | |
} | |
--result; | |
return result; | |
} | |
/** | |
* Convert column index to label. | |
* | |
* @param {Number} column Column index. | |
* @returns {String} Returns column label (eq. 'ABB', 'CNQ'). | |
*/ | |
function columnIndexToLabel(column) { | |
var result = ''; | |
while (column >= 0) { | |
result = String.fromCharCode(column % COLUMN_LABEL_BASE_LENGTH + 97) + result; | |
column = Math.floor(column / COLUMN_LABEL_BASE_LENGTH) - 1; | |
} | |
return result.toUpperCase(); | |
} | |
var LABEL_EXTRACT_REGEXP = /^([$])?([A-Za-z]+)([$])?([0-9]+)$/; | |
/** | |
* Extract cell coordinates. | |
* | |
* @param {String} label Cell coordinates (eq. 'A1', '$B6', '$N$98'). | |
* @returns {Array} Returns an array of objects. | |
*/ | |
function extractLabel(label) { | |
if (typeof label !== 'string' || !LABEL_EXTRACT_REGEXP.test(label)) { | |
return []; | |
} | |
var _label$toUpperCase$ma = label.toUpperCase().match(LABEL_EXTRACT_REGEXP), | |
columnAbs = _label$toUpperCase$ma[1], | |
column = _label$toUpperCase$ma[2], | |
rowAbs = _label$toUpperCase$ma[3], | |
row = _label$toUpperCase$ma[4]; | |
return [{ | |
index: rowLabelToIndex(row), | |
label: row, | |
isAbsolute: rowAbs === '$' | |
}, { | |
index: columnLabelToIndex(column), | |
label: column, | |
isAbsolute: columnAbs === '$' | |
}]; | |
} | |
/** | |
* Convert row and column indexes into cell label. | |
* | |
* @param {Object} row Object with `index` and `isAbsolute` properties. | |
* @param {Object} column Object with `index` and `isAbsolute` properties. | |
* @returns {String} Returns cell label. | |
*/ | |
function toLabel(row, column) { | |
var rowLabel = (row.isAbsolute ? '$' : '') + rowIndexToLabel(row.index); | |
var columnLabel = (column.isAbsolute ? '$' : '') + columnIndexToLabel(column.index); | |
return columnLabel + rowLabel; | |
} | |
/***/ }), | |
/* 15 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.rowLabelToIndex = exports.rowIndexToLabel = exports.columnLabelToIndex = exports.columnIndexToLabel = exports.toLabel = exports.extractLabel = exports.error = exports.Parser = exports.ERROR_VALUE = exports.ERROR_REF = exports.ERROR_NUM = exports.ERROR_NULL = exports.ERROR_NOT_AVAILABLE = exports.ERROR_NAME = exports.ERROR_DIV_ZERO = exports.ERROR = exports.SUPPORTED_FORMULAS = undefined; | |
var _parser = __webpack_require__(16); | |
var _parser2 = _interopRequireDefault(_parser); | |
var _supportedFormulas = __webpack_require__(13); | |
var _supportedFormulas2 = _interopRequireDefault(_supportedFormulas); | |
var _error = __webpack_require__(2); | |
var _error2 = _interopRequireDefault(_error); | |
var _cell = __webpack_require__(14); | |
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } | |
exports.SUPPORTED_FORMULAS = _supportedFormulas2['default']; | |
exports.ERROR = _error.ERROR; | |
exports.ERROR_DIV_ZERO = _error.ERROR_DIV_ZERO; | |
exports.ERROR_NAME = _error.ERROR_NAME; | |
exports.ERROR_NOT_AVAILABLE = _error.ERROR_NOT_AVAILABLE; | |
exports.ERROR_NULL = _error.ERROR_NULL; | |
exports.ERROR_NUM = _error.ERROR_NUM; | |
exports.ERROR_REF = _error.ERROR_REF; | |
exports.ERROR_VALUE = _error.ERROR_VALUE; | |
exports.Parser = _parser2['default']; | |
exports.error = _error2['default']; | |
exports.extractLabel = _cell.extractLabel; | |
exports.toLabel = _cell.toLabel; | |
exports.columnIndexToLabel = _cell.columnIndexToLabel; | |
exports.columnLabelToIndex = _cell.columnLabelToIndex; | |
exports.rowIndexToLabel = _cell.rowIndexToLabel; | |
exports.rowLabelToIndex = _cell.rowLabelToIndex; | |
/***/ }), | |
/* 16 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
var _tinyEmitter = __webpack_require__(17); | |
var _tinyEmitter2 = _interopRequireDefault(_tinyEmitter); | |
var _evaluateByOperator = __webpack_require__(18); | |
var _evaluateByOperator2 = _interopRequireDefault(_evaluateByOperator); | |
var _grammarParser = __webpack_require__(39); | |
var _string = __webpack_require__(40); | |
var _number = __webpack_require__(3); | |
var _error = __webpack_require__(2); | |
var _error2 = _interopRequireDefault(_error); | |
var _cell = __webpack_require__(14); | |
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; } | |
/** | |
* @class Parser | |
*/ | |
var Parser = function (_Emitter) { | |
_inherits(Parser, _Emitter); | |
function Parser() { | |
_classCallCheck(this, Parser); | |
var _this = _possibleConstructorReturn(this, _Emitter.call(this)); | |
_this.parser = new _grammarParser.Parser(); | |
_this.parser.yy = { | |
toNumber: _number.toNumber, | |
trimEdges: _string.trimEdges, | |
invertNumber: _number.invertNumber, | |
throwError: function throwError(errorName) { | |
return _this._throwError(errorName); | |
}, | |
callVariable: function callVariable(variable) { | |
return _this._callVariable(variable); | |
}, | |
evaluateByOperator: _evaluateByOperator2['default'], | |
callFunction: function callFunction(name, params) { | |
return _this._callFunction(name, params); | |
}, | |
cellValue: function cellValue(value) { | |
return _this._callCellValue(value); | |
}, | |
rangeValue: function rangeValue(start, end) { | |
return _this._callRangeValue(start, end); | |
} | |
}; | |
_this.variables = Object.create(null); | |
_this.functions = Object.create(null); | |
_this.setVariable('TRUE', true).setVariable('FALSE', false).setVariable('NULL', null); | |
return _this; | |
} | |
/** | |
* Parse formula expression. | |
* | |
* @param {String} expression to parse. | |
* @return {*} Returns an object with tow properties `error` and `result`. | |
*/ | |
Parser.prototype.parse = function parse(expression) { | |
var result = null; | |
var error = null; | |
try { | |
if (expression === '') { | |
result = ''; | |
} else { | |
result = this.parser.parse(expression); | |
} | |
} catch (ex) { | |
var message = (0, _error2['default'])(ex.message); | |
if (message) { | |
error = message; | |
} else { | |
error = (0, _error2['default'])(_error.ERROR); | |
} | |
} | |
if (result instanceof Error) { | |
error = (0, _error2['default'])(result.message) || (0, _error2['default'])(_error.ERROR); | |
result = null; | |
} | |
return { | |
error: error, | |
result: result | |
}; | |
}; | |
/** | |
* Set predefined variable name which can be visible while parsing formula expression. | |
* | |
* @param {String} name Variable name. | |
* @param {*} value Variable value. | |
* @returns {Parser} | |
*/ | |
Parser.prototype.setVariable = function setVariable(name, value) { | |
this.variables[name] = value; | |
return this; | |
}; | |
/** | |
* Get variable name. | |
* | |
* @param {String} name Variable name. | |
* @returns {*} | |
*/ | |
Parser.prototype.getVariable = function getVariable(name) { | |
return this.variables[name]; | |
}; | |
/** | |
* Retrieve variable value by its name. | |
* | |
* @param name Variable name. | |
* @returns {*} | |
* @private | |
*/ | |
Parser.prototype._callVariable = function _callVariable(name) { | |
var value = this.getVariable(name); | |
this.emit('callVariable', name, function (newValue) { | |
if (newValue !== void 0) { | |
value = newValue; | |
} | |
}); | |
if (value === void 0) { | |
throw Error(_error.ERROR_NAME); | |
} | |
return value; | |
}; | |
/** | |
* Set custom function which can be visible while parsing formula expression. | |
* | |
* @param {String} name Custom function name. | |
* @param {Function} fn Custom function. | |
* @returns {Parser} | |
*/ | |
Parser.prototype.setFunction = function setFunction(name, fn) { | |
this.functions[name] = fn; | |
return this; | |
}; | |
/** | |
* Get custom function. | |
* | |
* @param {String} name Custom function name. | |
* @returns {*} | |
*/ | |
Parser.prototype.getFunction = function getFunction(name) { | |
return this.functions[name]; | |
}; | |
/** | |
* Call function with provided params. | |
* | |
* @param name Function name. | |
* @param params Function params. | |
* @returns {*} | |
* @private | |
*/ | |
Parser.prototype._callFunction = function _callFunction(name) { | |
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | |
var fn = this.getFunction(name); | |
var value = void 0; | |
if (fn) { | |
value = fn(params); | |
} | |
this.emit('callFunction', name, params, function (newValue) { | |
if (newValue !== void 0) { | |
value = newValue; | |
} | |
}); | |
return value === void 0 ? (0, _evaluateByOperator2['default'])(name, params) : value; | |
}; | |
/** | |
* Retrieve value by its label (`B3`, `B$3`, `B$3`, `$B$3`). | |
* | |
* @param {String} label Coordinates. | |
* @returns {*} | |
* @private | |
*/ | |
Parser.prototype._callCellValue = function _callCellValue(label) { | |
label = label.toUpperCase(); | |
var _extractLabel = (0, _cell.extractLabel)(label), | |
row = _extractLabel[0], | |
column = _extractLabel[1]; | |
var value = void 0; | |
this.emit('callCellValue', { label: label, row: row, column: column }, function (_value) { | |
value = _value; | |
}); | |
return value; | |
}; | |
/** | |
* Retrieve value by its label (`B3:A1`, `B$3:A1`, `B$3:$A1`, `$B$3:A$1`). | |
* | |
* @param {String} startLabel Coordinates of the first cell. | |
* @param {String} endLabel Coordinates of the last cell. | |
* @returns {Array} Returns an array of mixed values. | |
* @private | |
*/ | |
Parser.prototype._callRangeValue = function _callRangeValue(startLabel, endLabel) { | |
startLabel = startLabel.toUpperCase(); | |
endLabel = endLabel.toUpperCase(); | |
var _extractLabel2 = (0, _cell.extractLabel)(startLabel), | |
startRow = _extractLabel2[0], | |
startColumn = _extractLabel2[1]; | |
var _extractLabel3 = (0, _cell.extractLabel)(endLabel), | |
endRow = _extractLabel3[0], | |
endColumn = _extractLabel3[1]; | |
var startCell = {}; | |
var endCell = {}; | |
if (startRow.index <= endRow.index) { | |
startCell.row = startRow; | |
endCell.row = endRow; | |
} else { | |
startCell.row = endRow; | |
endCell.row = startRow; | |
} | |
if (startColumn.index <= endColumn.index) { | |
startCell.column = startColumn; | |
endCell.column = endColumn; | |
} else { | |
startCell.column = endColumn; | |
endCell.column = startColumn; | |
} | |
startCell.label = (0, _cell.toLabel)(startCell.row, startCell.column); | |
endCell.label = (0, _cell.toLabel)(endCell.row, endCell.column); | |
var value = []; | |
this.emit('callRangeValue', startCell, endCell, function () { | |
var _value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; | |
value = _value; | |
}); | |
return value; | |
}; | |
/** | |
* Try to throw error by its name. | |
* | |
* @param {String} errorName Error name. | |
* @returns {String} | |
* @private | |
*/ | |
Parser.prototype._throwError = function _throwError(errorName) { | |
if ((0, _error.isValidStrict)(errorName)) { | |
throw Error(errorName); | |
} | |
throw Error(_error.ERROR); | |
}; | |
return Parser; | |
}(_tinyEmitter2['default']); | |
exports['default'] = Parser; | |
/***/ }), | |
/* 17 */ | |
/***/ (function(module, exports) { | |
function E () { | |
// Keep this empty so it's easier to inherit from | |
// (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) | |
} | |
E.prototype = { | |
on: function (name, callback, ctx) { | |
var e = this.e || (this.e = {}); | |
(e[name] || (e[name] = [])).push({ | |
fn: callback, | |
ctx: ctx | |
}); | |
return this; | |
}, | |
once: function (name, callback, ctx) { | |
var self = this; | |
function listener () { | |
self.off(name, listener); | |
callback.apply(ctx, arguments); | |
}; | |
listener._ = callback | |
return this.on(name, listener, ctx); | |
}, | |
emit: function (name) { | |
var data = [].slice.call(arguments, 1); | |
var evtArr = ((this.e || (this.e = {}))[name] || []).slice(); | |
var i = 0; | |
var len = evtArr.length; | |
for (i; i < len; i++) { | |
evtArr[i].fn.apply(evtArr[i].ctx, data); | |
} | |
return this; | |
}, | |
off: function (name, callback) { | |
var e = this.e || (this.e = {}); | |
var evts = e[name]; | |
var liveEvents = []; | |
if (evts && callback) { | |
for (var i = 0, len = evts.length; i < len; i++) { | |
if (evts[i].fn !== callback && evts[i].fn._ !== callback) | |
liveEvents.push(evts[i]); | |
} | |
} | |
// Remove event from queue to prevent memory leak | |
// Suggested by https://github.com/lazd | |
// Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910 | |
(liveEvents.length) | |
? e[name] = liveEvents | |
: delete e[name]; | |
return this; | |
} | |
}; | |
module.exports = E; | |
/***/ }), | |
/* 18 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports['default'] = evaluateByOperator; | |
exports.registerOperation = registerOperation; | |
var _add = __webpack_require__(19); | |
var _add2 = _interopRequireDefault(_add); | |
var _ampersand = __webpack_require__(20); | |
var _ampersand2 = _interopRequireDefault(_ampersand); | |
var _divide = __webpack_require__(21); | |
var _divide2 = _interopRequireDefault(_divide); | |
var _equal = __webpack_require__(22); | |
var _equal2 = _interopRequireDefault(_equal); | |
var _formulaFunction = __webpack_require__(23); | |
var _formulaFunction2 = _interopRequireDefault(_formulaFunction); | |
var _greaterThan = __webpack_require__(31); | |
var _greaterThan2 = _interopRequireDefault(_greaterThan); | |
var _greaterThanOrEqual = __webpack_require__(32); | |
var _greaterThanOrEqual2 = _interopRequireDefault(_greaterThanOrEqual); | |
var _lessThan = __webpack_require__(33); | |
var _lessThan2 = _interopRequireDefault(_lessThan); | |
var _lessThanOrEqual = __webpack_require__(34); | |
var _lessThanOrEqual2 = _interopRequireDefault(_lessThanOrEqual); | |
var _minus = __webpack_require__(35); | |
var _minus2 = _interopRequireDefault(_minus); | |
var _multiply = __webpack_require__(36); | |
var _multiply2 = _interopRequireDefault(_multiply); | |
var _notEqual = __webpack_require__(37); | |
var _notEqual2 = _interopRequireDefault(_notEqual); | |
var _power = __webpack_require__(38); | |
var _power2 = _interopRequireDefault(_power); | |
var _error = __webpack_require__(2); | |
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } | |
/* eslint-disable import/no-named-as-default-member */ | |
var availableOperators = Object.create(null); | |
/** | |
* Evaluate values by operator id.git | |
* | |
* @param {String} operator Operator id. | |
* @param {Array} [params=[]] Arguments to evaluate. | |
* @returns {*} | |
*/ | |
function evaluateByOperator(operator) { | |
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; | |
operator = operator.toUpperCase(); | |
if (!availableOperators[operator]) { | |
throw Error(_error.ERROR_NAME); | |
} | |
return availableOperators[operator].apply(availableOperators, params); | |
} | |
/** | |
* Register operator. | |
* | |
* @param {String|Array} symbol Symbol to register. | |
* @param {Function} func Logic to register for this symbol. | |
*/ | |
function registerOperation(symbol, func) { | |
if (!Array.isArray(symbol)) { | |
symbol = [symbol.toUpperCase()]; | |
} | |
symbol.forEach(function (s) { | |
if (func.isFactory) { | |
availableOperators[s] = func(s); | |
} else { | |
availableOperators[s] = func; | |
} | |
}); | |
} | |
registerOperation(_add2['default'].SYMBOL, _add2['default']); | |
registerOperation(_ampersand2['default'].SYMBOL, _ampersand2['default']); | |
registerOperation(_divide2['default'].SYMBOL, _divide2['default']); | |
registerOperation(_equal2['default'].SYMBOL, _equal2['default']); | |
registerOperation(_power2['default'].SYMBOL, _power2['default']); | |
registerOperation(_formulaFunction2['default'].SYMBOL, _formulaFunction2['default']); | |
registerOperation(_greaterThan2['default'].SYMBOL, _greaterThan2['default']); | |
registerOperation(_greaterThanOrEqual2['default'].SYMBOL, _greaterThanOrEqual2['default']); | |
registerOperation(_lessThan2['default'].SYMBOL, _lessThan2['default']); | |
registerOperation(_lessThanOrEqual2['default'].SYMBOL, _lessThanOrEqual2['default']); | |
registerOperation(_multiply2['default'].SYMBOL, _multiply2['default']); | |
registerOperation(_notEqual2['default'].SYMBOL, _notEqual2['default']); | |
registerOperation(_minus2['default'].SYMBOL, _minus2['default']); | |
/***/ }), | |
/* 19 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.SYMBOL = undefined; | |
exports['default'] = func; | |
var _number = __webpack_require__(3); | |
var _error = __webpack_require__(2); | |
var SYMBOL = exports.SYMBOL = '+'; | |
function func(first) { | |
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
rest[_key - 1] = arguments[_key]; | |
} | |
var result = rest.reduce(function (acc, value) { | |
return acc + (0, _number.toNumber)(value); | |
}, (0, _number.toNumber)(first)); | |
if (isNaN(result)) { | |
throw Error(_error.ERROR_VALUE); | |
} | |
return result; | |
} | |
func.SYMBOL = SYMBOL; | |
/***/ }), | |
/* 20 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports['default'] = func; | |
var SYMBOL = exports.SYMBOL = '&'; | |
function func() { | |
for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) { | |
params[_key] = arguments[_key]; | |
} | |
return params.reduce(function (acc, value) { | |
return acc + value.toString(); | |
}, ''); | |
} | |
func.SYMBOL = SYMBOL; | |
/***/ }), | |
/* 21 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.SYMBOL = undefined; | |
exports['default'] = func; | |
var _number = __webpack_require__(3); | |
var _error = __webpack_require__(2); | |
var SYMBOL = exports.SYMBOL = '/'; | |
function func(first) { | |
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | |
rest[_key - 1] = arguments[_key]; | |
} | |
var result = rest.reduce(function (acc, value) { | |
return acc / (0, _number.toNumber)(value); | |
}, (0, _number.toNumber)(first)); | |
if (result === Infinity) { | |
throw Error(_error.ERROR_DIV_ZERO); | |
} | |
if (isNaN(result)) { | |
throw Error(_error.ERROR_VALUE); | |
} | |
return result; | |
} | |
func.SYMBOL = SYMBOL; | |
/***/ }), | |
/* 22 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports['default'] = func; | |
var SYMBOL = exports.SYMBOL = '='; | |
function func(exp1, exp2) { | |
return exp1 === exp2; | |
} | |
func.SYMBOL = SYMBOL; | |
/***/ }), | |
/* 23 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
"use strict"; | |
exports.__esModule = true; | |
exports.SYMBOL = undefined; | |
exports['default'] = func; | |
var _formulajs = __webpack_require__(24); | |
var formulajs = _interopRequireWildcard(_formulajs); | |
var _supportedFormulas = __webpack_require__(13); | |
var _supportedFormulas2 = _interopRequireDefault(_supportedFormulas); | |
var _error = __webpack_require__(2); | |
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } | |
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; } } | |
var SYMBOL = exports.SYMBOL = _supportedFormulas2['default']; | |
function func(symbol) { | |
return function __formulaFunction() { | |
symbol = symbol.toUpperCase(); | |
var symbolParts = symbol.split('.'); | |
var foundFormula = false; | |
var result = void 0; | |
if (symbolParts.length === 1) { | |
if (formulajs[symbolParts[0]]) { | |
foundFormula = true; | |
result = formulajs[symbolParts[0]].apply(formulajs, arguments); | |
} | |
} else { | |
var length = symbolParts.length; | |
var index = 0; | |
var nestedFormula = formulajs; | |
while (index < length) { | |
nestedFormula = nestedFormula[symbolParts[index]]; | |
index++; | |
if (!nestedFormula) { | |
nestedFormula = null; | |
break; | |
} | |
} | |
if (nestedFormula) { | |
foundFormula = true; | |
result = nestedFormula.apply(undefined, arguments); | |
} | |
} | |
if (!foundFormula) { | |
throw Error(_error.ERROR_NAME); | |
} | |
return result; | |
}; | |
} | |
func.isFactory = true; | |
func.SYMBOL = SYMBOL; | |
/***/ }), | |
/* 24 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var categories = [ | |
__webpack_require__(25), | |
__webpack_require__(27), | |
__webpack_require__(12), | |
__webpack_require__(28), | |
__webpack_require__(4), | |
__webpack_require__(6), | |
__webpack_require__(9), | |
__webpack_require__(29), | |
__webpack_require__(8), | |
__webpack_require__(30), | |
__webpack_require__(5), | |
__webpack_require__(11) | |
]; | |
for (var c in categories) { | |
var category = categories[c]; | |
for (var f in category) { | |
exports[f] = exports[f] || category[f]; | |
} | |
} | |
/***/ }), | |
/* 25 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var mathTrig = __webpack_require__(4); | |
var statistical = __webpack_require__(5); | |
var engineering = __webpack_require__(12); | |
var dateTime = __webpack_require__(9); | |
function set(fn, root) { | |
if (root) { | |
for (var i in root) { | |
fn[i] = root[i]; | |
} | |
} | |
return fn; | |
} | |
exports.BETADIST = statistical.BETA.DIST; | |
exports.BETAINV = statistical.BETA.INV; | |
exports.BINOMDIST = statistical.BINOM.DIST; | |
exports.CEILING = exports.ISOCEILING = set(mathTrig.CEILING.MATH, mathTrig.CEILING); | |
exports.CEILINGMATH = mathTrig.CEILING.MATH; | |
exports.CEILINGPRECISE = mathTrig.CEILING.PRECISE; | |
exports.CHIDIST = statistical.CHISQ.DIST; | |
exports.CHIDISTRT = statistical.CHISQ.DIST.RT; | |
exports.CHIINV = statistical.CHISQ.INV; | |
exports.CHIINVRT = statistical.CHISQ.INV.RT; | |
exports.CHITEST = statistical.CHISQ.TEST; | |
exports.CONFIDENCE = set(statistical.CONFIDENCE.NORM, statistical.CONFIDENCE); | |
exports.COVAR = statistical.COVARIANCE.P; | |
exports.COVARIANCEP = statistical.COVARIANCE.P; | |
exports.COVARIANCES = statistical.COVARIANCE.S; | |
exports.CRITBINOM = statistical.BINOM.INV; | |
exports.EXPONDIST = statistical.EXPON.DIST; | |
exports.ERFCPRECISE = engineering.ERFC.PRECISE; | |
exports.ERFPRECISE = engineering.ERF.PRECISE; | |
exports.FDIST = statistical.F.DIST; | |
exports.FDISTRT = statistical.F.DIST.RT; | |
exports.FINVRT = statistical.F.INV.RT; | |
exports.FINV = statistical.F.INV; | |
exports.FLOOR = set(mathTrig.FLOOR.MATH, mathTrig.FLOOR); | |
exports.FLOORMATH = mathTrig.FLOOR.MATH; | |
exports.FLOORPRECISE = mathTrig.FLOOR.PRECISE; | |
exports.FTEST = statistical.F.TEST; | |
exports.GAMMADIST = statistical.GAMMA.DIST; | |
exports.GAMMAINV = statistical.GAMMA.INV; | |
exports.GAMMALNPRECISE = statistical.GAMMALN.PRECISE; | |
exports.HYPGEOMDIST = statistical.HYPGEOM.DIST; | |
exports.LOGINV = statistical.LOGNORM.INV; | |
exports.LOGNORMINV = statistical.LOGNORM.INV; | |
exports.LOGNORMDIST = statistical.LOGNORM.DIST; | |
exports.MODE = set(statistical.MODE.SNGL, statistical.MODE); | |
exports.MODEMULT = statistical.MODE.MULT; | |
exports.MODESNGL = statistical.MODE.SNGL; | |
exports.NEGBINOMDIST = statistical.NEGBINOM.DIST; | |
exports.NETWORKDAYSINTL = dateTime.NETWORKDAYS.INTL; | |
exports.NORMDIST = statistical.NORM.DIST; | |
exports.NORMINV = statistical.NORM.INV; | |
exports.NORMSDIST = statistical.NORM.S.DIST; | |
exports.NORMSINV = statistical.NORM.S.INV; | |
exports.PERCENTILE = set(statistical.PERCENTILE.EXC, statistical.PERCENTILE); | |
exports.PERCENTILEEXC = statistical.PERCENTILE.EXC; | |
exports.PERCENTILEINC = statistical.PERCENTILE.INC; | |
exports.PERCENTRANK = set(statistical.PERCENTRANK.INC, statistical.PERCENTRANK); | |
exports.PERCENTRANKEXC = statistical.PERCENTRANK.EXC; | |
exports.PERCENTRANKINC = statistical.PERCENTRANK.INC; | |
exports.POISSON = set(statistical.POISSON.DIST, statistical.POISSON); | |
exports.POISSONDIST = statistical.POISSON.DIST; | |
exports.QUARTILE = set(statistical.QUARTILE.INC, statistical.QUARTILE); | |
exports.QUARTILEEXC = statistical.QUARTILE.EXC; | |
exports.QUARTILEINC = statistical.QUARTILE.INC; | |
exports.RANK = set(statistical.RANK.EQ, statistical.RANK); | |
exports.RANKAVG = statistical.RANK.AVG; | |
exports.RANKEQ = statistical.RANK.EQ; | |
exports.SKEWP = statistical.SKEW.P; | |
exports.STDEV = set(statistical.STDEV.S, statistical.STDEV); | |
exports.STDEVP = statistical.STDEV.P; | |
exports.STDEVS = statistical.STDEV.S; | |
exports.TDIST = statistical.T.DIST; | |
exports.TDISTRT = statistical.T.DIST.RT; | |
exports.TINV = statistical.T.INV; | |
exports.TTEST = statistical.T.TEST; | |
exports.VAR = set(statistical.VAR.S, statistical.VAR); | |
exports.VARP = statistical.VAR.P; | |
exports.VARS = statistical.VAR.S; | |
exports.WEIBULL = set(statistical.WEIBULL.DIST, statistical.WEIBULL); | |
exports.WEIBULLDIST = statistical.WEIBULL.DIST; | |
exports.WORKDAYINTL = dateTime.WORKDAY.INTL; | |
exports.ZTEST = statistical.Z.TEST; | |
/***/ }), | |
/* 26 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var M = Math; | |
function _horner(arr, v) { return arr.reduce(function(z,w){return v * z + w;},0); }; | |
function _bessel_iter(x, n, f0, f1, sign) { | |
if(!sign) sign = -1; | |
var tdx = 2 / x, f2; | |
if(n === 0) return f0; | |
if(n === 1) return f1; | |
for(var o = 1; o != n; ++o) { | |
f2 = f1 * o * tdx + sign * f0; | |
f0 = f1; f1 = f2; | |
} | |
return f1; | |
} | |
function _bessel_wrap(bessel0, bessel1, name, nonzero, sign) { | |
return function bessel(x,n) { | |
if(n === 0) return bessel0(x); | |
if(n === 1) return bessel1(x); | |
if(n < 0) throw name + ': Order (' + n + ') must be nonnegative'; | |
if(nonzero == 1 && x === 0) throw name + ': Undefined when x == 0'; | |
if(nonzero == 2 && x <= 0) throw name + ': Undefined when x <= 0'; | |
var b0 = bessel0(x), b1 = bessel1(x); | |
return _bessel_iter(x, n, b0, b1, sign); | |
}; | |
} | |
var besselj = (function() { | |
var b0_a1a = [57568490574.0,-13362590354.0,651619640.7,-11214424.18,77392.33017,-184.9052456].reverse(); | |
var b0_a2a = [57568490411.0,1029532985.0,9494680.718,59272.64853,267.8532712,1.0].reverse(); | |
var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); | |
var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934935152e-7].reverse(); | |
var W = 0.636619772; // 2 / Math.PI | |
function bessel0(x) { | |
var a, a1, a2, y = x * x, xx = M.abs(x) - 0.785398164; | |
if(M.abs(x) < 8) { | |
a1 = _horner(b0_a1a, y); | |
a2 = _horner(b0_a2a, y); | |
a = a1/a2; | |
} | |
else { | |
y = 64 / y; | |
a1 = _horner(b0_a1b, y); | |
a2 = _horner(b0_a2b, y); | |
a = M.sqrt(W/M.abs(x))*(M.cos(xx)*a1-M.sin(xx)*a2*8/M.abs(x)); | |
} | |
return a; | |
} | |
var b1_a1a = [72362614232.0,-7895059235.0,242396853.1,-2972611.439, 15704.48260, -30.16036606].reverse(); | |
var b1_a2a = [144725228442.0, 2300535178.0, 18583304.74, 99447.43394, 376.9991397, 1.0].reverse(); | |
var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); | |
var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); | |
function bessel1(x) { | |
var a, a1, a2, y = x*x, xx = M.abs(x) - 2.356194491; | |
if(Math.abs(x)< 8) { | |
a1 = x*_horner(b1_a1a, y); | |
a2 = _horner(b1_a2a, y); | |
a = a1 / a2; | |
} else { | |
y = 64 / y; | |
a1=_horner(b1_a1b, y); | |
a2=_horner(b1_a2b, y); | |
a=M.sqrt(W/M.abs(x))*(M.cos(xx)*a1-M.sin(xx)*a2*8/M.abs(x)); | |
if(x < 0) a = -a; | |
} | |
return a; | |
} | |
return function besselj(x, n) { | |
n = Math.round(n); | |
if(n === 0) return bessel0(M.abs(x)); | |
if(n === 1) return bessel1(M.abs(x)); | |
if(n < 0) throw 'BESSELJ: Order (' + n + ') must be nonnegative'; | |
if(M.abs(x) === 0) return 0; | |
var ret, j, tox = 2 / M.abs(x), m, jsum, sum, bjp, bj, bjm; | |
if(M.abs(x) > n) { | |
ret = _bessel_iter(x, n, bessel0(M.abs(x)), bessel1(M.abs(x)),-1); | |
} else { | |
m=2*M.floor((n+M.floor(M.sqrt(40*n)))/2); | |
jsum=0; | |
bjp=ret=sum=0.0; | |
bj=1.0; | |
for (j=m;j>0;j--) { | |
bjm=j*tox*bj-bjp; | |
bjp=bj; | |
bj=bjm; | |
if (M.abs(bj) > 1E10) { | |
bj *= 1E-10; | |
bjp *= 1E-10; | |
ret *= 1E-10; | |
sum *= 1E-10; | |
} | |
if (jsum) sum += bj; | |
jsum=!jsum; | |
if (j == n) ret=bjp; | |
} | |
sum=2.0*sum-bj; | |
ret /= sum; | |
} | |
return x < 0 && (n%2) ? -ret : ret; | |
}; | |
})(); | |
var bessely = (function() { | |
var b0_a1a = [-2957821389.0, 7062834065.0, -512359803.6, 10879881.29, -86327.92757, 228.4622733].reverse(); | |
var b0_a2a = [40076544269.0, 745249964.8, 7189466.438, 47447.26470, 226.1030244, 1.0].reverse(); | |
var b0_a1b = [1.0, -0.1098628627e-2, 0.2734510407e-4, -0.2073370639e-5, 0.2093887211e-6].reverse(); | |
var b0_a2b = [-0.1562499995e-1, 0.1430488765e-3, -0.6911147651e-5, 0.7621095161e-6, -0.934945152e-7].reverse(); | |
var W = 0.636619772; | |
function bessel0(x) { | |
var a, a1, a2, y = x * x, xx = x - 0.785398164; | |
if(x < 8) { | |
a1 = _horner(b0_a1a, y); | |
a2 = _horner(b0_a2a, y); | |
a = a1/a2 + W * besselj(x,0) * M.log(x); | |
} else { | |
y = 64 / y; | |
a1 = _horner(b0_a1b, y); | |
a2 = _horner(b0_a2b, y); | |
a = M.sqrt(W/x)*(M.sin(xx)*a1+M.cos(xx)*a2*8/x); | |
} | |
return a; | |
} | |
var b1_a1a = [-0.4900604943e13, 0.1275274390e13, -0.5153438139e11, 0.7349264551e9, -0.4237922726e7, 0.8511937935e4].reverse(); | |
var b1_a2a = [0.2499580570e14, 0.4244419664e12, 0.3733650367e10, 0.2245904002e8, 0.1020426050e6, 0.3549632885e3, 1].reverse(); | |
var b1_a1b = [1.0, 0.183105e-2, -0.3516396496e-4, 0.2457520174e-5, -0.240337019e-6].reverse(); | |
var b1_a2b = [0.04687499995, -0.2002690873e-3, 0.8449199096e-5, -0.88228987e-6, 0.105787412e-6].reverse(); | |
function bessel1(x) { | |
var a, a1, a2, y = x*x, xx = x - 2.356194491; | |
if(x < 8) { | |
a1 = x*_horner(b1_a1a, y); | |
a2 = _horner(b1_a2a, y); | |
a = a1/a2 + W * (besselj(x,1) * M.log(x) - 1 / x); | |
} else { | |
y = 64 / y; | |
a1=_horner(b1_a1b, y); | |
a2=_horner(b1_a2b, y); | |
a=M.sqrt(W/x)*(M.sin(xx)*a1+M.cos(xx)*a2*8/x); | |
} | |
return a; | |
} | |
return _bessel_wrap(bessel0, bessel1, 'BESSELY', 1, -1); | |
})(); | |
var besseli = (function() { | |
var b0_a = [1.0, 3.5156229, 3.0899424, 1.2067492, 0.2659732, 0.360768e-1, 0.45813e-2].reverse(); | |
var b0_b = [0.39894228, 0.1328592e-1, 0.225319e-2, -0.157565e-2, 0.916281e-2, -0.2057706e-1, 0.2635537e-1, -0.1647633e-1, 0.392377e-2].reverse(); | |
function bessel0(x) { | |
if(x <= 3.75) return _horner(b0_a, x*x/(3.75*3.75)); | |
return M.exp(M.abs(x))/M.sqrt(M.abs(x))*_horner(b0_b, 3.75/M.abs(x)); | |
} | |
var b1_a = [0.5, 0.87890594, 0.51498869, 0.15084934, 0.2658733e-1, 0.301532e-2, 0.32411e-3].reverse(); | |
var b1_b = [0.39894228, -0.3988024e-1, -0.362018e-2, 0.163801e-2, -0.1031555e-1, 0.2282967e-1, -0.2895312e-1, 0.1787654e-1, -0.420059e-2].reverse(); | |
function bessel1(x) { | |
if(x < 3.75) return x * _horner(b1_a, x*x/(3.75*3.75)); | |
return (x < 0 ? -1 : 1) * M.exp(M.abs(x))/M.sqrt(M.abs(x))*_horner(b1_b, 3.75/M.abs(x)); | |
} | |
return function besseli(x, n) { | |
n = Math.round(n); | |
if(n === 0) return bessel0(x); | |
if(n == 1) return bessel1(x); | |
if(n < 0) throw 'BESSELI Order (' + n + ') must be nonnegative'; | |
if(M.abs(x) === 0) return 0; | |
var ret, j, tox = 2 / M.abs(x), m, bip, bi, bim; | |
m=2*M.round((n+M.round(M.sqrt(40*n)))/2); | |
bip=ret=0.0; | |
bi=1.0; | |
for (j=m;j>0;j--) { | |
bim=j*tox*bi + bip; | |
bip=bi; bi=bim; | |
if (M.abs(bi) > 1E10) { | |
bi *= 1E-10; | |
bip *= 1E-10; | |
ret *= 1E-10; | |
} | |
if(j == n) ret = bip; | |
} | |
ret *= besseli(x, 0) / bi; | |
return x < 0 && (n%2) ? -ret : ret; | |
}; | |
})(); | |
var besselk = (function() { | |
var b0_a = [-0.57721566, 0.42278420, 0.23069756, 0.3488590e-1, 0.262698e-2, 0.10750e-3, 0.74e-5].reverse(); | |
var b0_b = [1.25331414, -0.7832358e-1, 0.2189568e-1, -0.1062446e-1, 0.587872e-2, -0.251540e-2, 0.53208e-3].reverse(); | |
function bessel0(x) { | |
if(x <= 2) return -M.log(x/2)*besseli(x,0) + _horner(b0_a, x*x/4); | |
return M.exp(-x)/M.sqrt(x)*_horner(b0_b, 2/x); | |
} | |
var b1_a = [1.0, 0.15443144, -0.67278579, -0.18156897, -0.1919402e-1, -0.110404e-2, -0.4686e-4].reverse(); | |
var b1_b = [1.25331414, 0.23498619, -0.3655620e-1, 0.1504268e-1, -0.780353e-2, 0.325614e-2, -0.68245e-3].reverse(); | |
function bessel1(x) { | |
if(x <= 2) return M.log(x/2)*besseli(x,1) + (1/x)*_horner(b1_a, x*x/4); | |
return M.exp(-x)/M.sqrt(x)*_horner(b1_b, 2/x); | |
} | |
return _bessel_wrap(bessel0, bessel1, 'BESSELK', 2, 1); | |
})(); | |
if(true) { | |
exports.besselj = besselj; | |
exports.bessely = bessely; | |
exports.besseli = besseli; | |
exports.besselk = besselk; | |
} | |
/***/ }), | |
/* 27 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
var stats = __webpack_require__(5); | |
var maths = __webpack_require__(4); | |
var utils = __webpack_require__(1); | |
var evalExpression = __webpack_require__(7); | |
function compact(array) { | |
var result = []; | |
utils.arrayEach(array, function(value) { | |
if (value) { | |
result.push(value); | |
} | |
}); | |
return result; | |
} | |
exports.FINDFIELD = function(database, title) { | |
var index = null; | |
utils.arrayEach(database, function(value, i) { | |
if (value[0] === title) { | |
index = i; | |
return false; | |
} | |
}); | |
// Return error if the input field title is incorrect | |
if (index == null) { | |
return error.value; | |
} | |
return index; | |
}; | |
function findResultIndex(database, criterias) { | |
var matches = {}; | |
for (var i = 1; i < database[0].length; ++i) { | |
matches[i] = true; | |
} | |
var maxCriteriaLength = criterias[0].length; | |
for (i = 1; i < criterias.length; ++i) { | |
if (criterias[i].length > maxCriteriaLength) { | |
maxCriteriaLength = criterias[i].length; | |
} | |
} | |
for (var k = 1; k < database.length; ++k) { | |
for (var l = 1; l < database[k].length; ++l) { | |
var currentCriteriaResult = false; | |
var hasMatchingCriteria = false; | |
for (var j = 0; j < criterias.length; ++j) { | |
var criteria = criterias[j]; | |
if (criteria.length < maxCriteriaLength) { | |
continue; | |
} | |
var criteriaField = criteria[0]; | |
if (database[k][0] !== criteriaField) { | |
continue; | |
} | |
hasMatchingCriteria = true; | |
for (var p = 1; p < criteria.length; ++p) { | |
if (!currentCriteriaResult) { | |
var isWildcard = criteria[p] === void 0 || criteria[p] === '*'; | |
if (isWildcard) { | |
currentCriteriaResult = true; | |
} else { | |
var tokenizedCriteria = evalExpression.parse(criteria[p] + ''); | |
var tokens = [evalExpression.createToken(database[k][l], evalExpression.TOKEN_TYPE_LITERAL)].concat(tokenizedCriteria); | |
currentCriteriaResult = evalExpression.compute(tokens); | |
} | |
} | |
} | |
} | |
if (hasMatchingCriteria) { | |
matches[l] = matches[l] && currentCriteriaResult; | |
} | |
} | |
} | |
var result = []; | |
for (var n = 0; n < database[0].length; ++n) { | |
if (matches[n]) { | |
result.push(n - 1); | |
} | |
} | |
return result; | |
} | |
// Database functions | |
exports.DAVERAGE = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var sum = 0; | |
utils.arrayEach(resultIndexes, function(value) { | |
sum += targetFields[value]; | |
}); | |
return resultIndexes.length === 0 ? error.div0 : sum / resultIndexes.length; | |
}; | |
exports.DCOUNT = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
return stats.COUNT(targetValues); | |
}; | |
exports.DCOUNTA = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
return stats.COUNTA(targetValues); | |
}; | |
exports.DGET = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
// Return error if no record meets the criteria | |
if (resultIndexes.length === 0) { | |
return error.value; | |
} | |
// Returns the #NUM! error value because more than one record meets the | |
// criteria | |
if (resultIndexes.length > 1) { | |
return error.num; | |
} | |
return targetFields[resultIndexes[0]]; | |
}; | |
exports.DMAX = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var maxValue = targetFields[resultIndexes[0]]; | |
utils.arrayEach(resultIndexes, function(value) { | |
if (maxValue < targetFields[value]) { | |
maxValue = targetFields[value]; | |
} | |
}); | |
return maxValue; | |
}; | |
exports.DMIN = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var minValue = targetFields[resultIndexes[0]]; | |
utils.arrayEach(resultIndexes, function(value) { | |
if (minValue > targetFields[value]) { | |
minValue = targetFields[value]; | |
} | |
}); | |
return minValue; | |
}; | |
exports.DPRODUCT = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
targetValues = compact(targetValues); | |
var result = 1; | |
utils.arrayEach(targetValues, function(value) { | |
result *= value; | |
}); | |
return result; | |
}; | |
exports.DSTDEV = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
targetValues = compact(targetValues); | |
return stats.STDEV.S(targetValues); | |
}; | |
exports.DSTDEVP = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
targetValues = compact(targetValues); | |
return stats.STDEV.P(targetValues); | |
}; | |
exports.DSUM = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
return maths.SUM(targetValues); | |
}; | |
exports.DVAR = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
return stats.VAR.S(targetValues); | |
}; | |
exports.DVARP = function(database, field, criteria) { | |
// Return error if field is not a number and not a string | |
if (isNaN(field) && (typeof field !== "string")) { | |
return error.value; | |
} | |
var resultIndexes = findResultIndex(database, criteria); | |
var targetFields = []; | |
if (typeof field === "string") { | |
var index = exports.FINDFIELD(database, field); | |
targetFields = utils.rest(database[index]); | |
} else { | |
targetFields = utils.rest(database[field]); | |
} | |
var targetValues = []; | |
utils.arrayEach(resultIndexes, function(value) { | |
targetValues.push(targetFields[value]); | |
}); | |
return stats.VAR.P(targetValues); | |
}; | |
/***/ }), | |
/* 28 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
var utils = __webpack_require__(1); | |
var information = __webpack_require__(8); | |
exports.AND = function() { | |
var args = utils.flatten(arguments); | |
var result = true; | |
for (var i = 0; i < args.length; i++) { | |
if (!args[i]) { | |
result = false; | |
} | |
} | |
return result; | |
}; | |
exports.CHOOSE = function() { | |
if (arguments.length < 2) { | |
return error.na; | |
} | |
var index = arguments[0]; | |
if (index < 1 || index > 254) { | |
return error.value; | |
} | |
if (arguments.length < index + 1) { | |
return error.value; | |
} | |
return arguments[index]; | |
}; | |
exports.FALSE = function() { | |
return false; | |
}; | |
exports.IF = function(test, then_value, otherwise_value) { | |
return test ? then_value : otherwise_value; | |
}; | |
exports.IFERROR = function(value, valueIfError) { | |
if (information.ISERROR(value)) { | |
return valueIfError; | |
} | |
return value; | |
}; | |
exports.IFNA = function(value, value_if_na) { | |
return value === error.na ? value_if_na : value; | |
}; | |
exports.NOT = function(logical) { | |
return !logical; | |
}; | |
exports.OR = function() { | |
var args = utils.flatten(arguments); | |
var result = false; | |
for (var i = 0; i < args.length; i++) { | |
if (args[i]) { | |
result = true; | |
} | |
} | |
return result; | |
}; | |
exports.TRUE = function() { | |
return true; | |
}; | |
exports.XOR = function() { | |
var args = utils.flatten(arguments); | |
var result = 0; | |
for (var i = 0; i < args.length; i++) { | |
if (args[i]) { | |
result++; | |
} | |
} | |
return (Math.floor(Math.abs(result)) & 1) ? true : false; | |
}; | |
exports.SWITCH = function () { | |
var result; | |
if (arguments.length > 0) { | |
var targetValue = arguments[0]; | |
var argc = arguments.length - 1; | |
var switchCount = Math.floor(argc / 2); | |
var switchSatisfied = false; | |
var hasDefaultClause = argc % 2 !== 0; | |
var defaultClause = argc % 2 === 0 ? null : arguments[arguments.length - 1]; | |
if (switchCount) { | |
for (var index = 0; index < switchCount; index++) { | |
if (targetValue === arguments[index * 2 + 1]) { | |
result = arguments[index * 2 + 2]; | |
switchSatisfied = true; | |
break; | |
} | |
} | |
} | |
if (!switchSatisfied) { | |
result = hasDefaultClause ? defaultClause : error.na; | |
} | |
} else { | |
result = error.value; | |
} | |
return result; | |
}; | |
/***/ }), | |
/* 29 */ | |
/***/ (function(module, exports, __webpack_require__) { | |
var error = __webpack_require__(0); | |
var dateTime = __webpack_require__(9); | |
var utils = __webpack_require__(1); | |
function validDate(d) { | |
return d && d.getTime && !isNaN(d.getTime()); | |
} | |
function ensureDate(d) { | |
return (d instanceof Date)?d:new Date(d); | |
} | |
exports.ACCRINT = function(issue, first, settlement, rate, par, frequency, basis) { | |
// Return error if either date is invalid | |
issue = ensureDate(issue); | |
first = ensureDate(first); | |
settlement = ensureDate(settlement); | |
if (!validDate(issue) || !validDate(first) || !validDate(settlement)) { | |
return error.value; | |
} | |
// Return error if either rate or par are lower than or equal to zero | |
if (rate <= 0 || par <= 0) { | |
return error.num; | |
} | |
// Return error if frequency is neither 1, 2, or 4 | |
if ([1, 2, 4].indexOf(frequency) === -1) { | |
return error.num; | |
} | |
// Return error if basis is neither 0, 1, 2, 3, or 4 | |
if ([0, 1, 2, 3, 4].indexOf(basis) === -1) { | |
return error.num; | |
} | |
// Return error if settlement is before or equal to issue | |
if (settlement <= issue) { | |
return error.num; | |
} | |
// Set default values | |
par = par || 0; | |
basis = basis || 0; | |
// Compute accrued interest | |
return par * rate * dateTime.YEARFRAC(issue, settlement, basis); | |
}; | |
// TODO | |
exports.ACCRINTM = function() { | |
throw new Error('ACCRINTM is not implemented'); | |
}; | |
// TODO | |
exports.AMORDEGRC = function() { | |
throw new Error('AMORDEGRC is not implemented'); | |
}; | |
// TODO | |
exports.AMORLINC = function() { | |
throw new Error('AMORLINC is not implemented'); | |
}; | |
// TODO | |
exports.COUPDAYBS = function() { | |
throw new Error('COUPDAYBS is not implemented'); | |
}; | |
// TODO | |
exports.COUPDAYS = function() { | |
throw new Error('COUPDAYS is not implemented'); | |
}; | |
// TODO | |
exports.COUPDAYSNC = function() { | |
throw new Error('COUPDAYSNC is not implemented'); | |
}; | |
// TODO | |
exports.COUPNCD = function() { | |
throw new Error('COUPNCD is not implemented'); | |
}; | |
// TODO | |
exports.COUPNUM = function() { | |
throw new Error('COUPNUM is not implemented'); | |
}; | |
// TODO | |
exports.COUPPCD = function() { | |
throw new Error('COUPPCD is not implemented'); | |
}; | |
exports.CUMIPMT = function(rate, periods, value, start, end, type) { | |
// Credits: algorithm inspired by Apache OpenOffice | |
// Credits: Hannes Stiebitzhofer for the translations of function and variable names | |
// Requires exports.FV() and exports.PMT() from exports.js [http://stoic.com/exports/] | |
rate = utils.parseNumber(rate); | |
periods = utils.parseNumber(periods); | |
value = utils.parseNumber(value); | |
if (utils.anyIsError(rate, periods, value)) { | |
return error.value; | |
} | |
// Return error if either rate, periods, or value are lower than or equal to zero | |
if (rate <= 0 || periods <= 0 || value <= 0) { | |
return error.num; | |
} | |
// Return error if start < 1, end < 1, or start > end | |
if (start < 1 || end < 1 || start > end) { | |
return error.num; | |
} | |
// Return error if type is neither 0 nor 1 | |
if (type !== 0 && type !== 1) { | |
return error.num; | |
} | |
// Compute cumulative interest | |
var payment = exports.PMT(rate, periods, value, 0, type); | |
var interest = 0; | |
if (start === 1) { | |
if (type === 0) { | |
interest = -value; | |
start++; | |
} | |
} | |
for (var i = start; i <= end; i++) { | |
if (type === 1) { | |
interest += exports.FV(rate, i - 2, payment, value, 1) - payment; | |
} else { | |
interest += exports.FV(rate, i - 1, payment, value, 0); | |
} | |
} | |
interest *= rate; | |
// Return cumulative interest | |
return interest; | |
}; | |
exports.CUMPRINC = function(rate, periods, value, start, end, type) { | |
// Credits: algorithm inspired by Apache OpenOffice | |
// Credits: Hannes Stiebitzhofer for the translations of function and variable names | |
rate = utils.parseNumber(rate); | |
periods = utils.parseNumber(periods); | |
value = utils.parseNumber(value); | |
if (utils.anyIsError(rate, periods, value)) { | |
return error.value; | |
} | |
// Return error if either rate, periods, or value are lower than or equal to zero | |
if (rate <= 0 || periods <= 0 || value <= 0) { | |
return error.num; | |
} | |
// Return error if start < 1, end < 1, or start > end | |
if (start < 1 || end < 1 || start > end) { | |
return error.num; | |
} | |
// Return error if type is neither 0 nor 1 | |
if (type !== 0 && type !== 1) { | |
return error.num; | |
} | |
// Compute cumulative principal | |
var payment = exports.PMT(rate, periods, value, 0, type); | |
var principal = 0; | |
if (start === 1) { | |
if (type === 0) { | |
principal = payment + value * rate; | |
} else { | |
principal = payment; | |
} | |
start++; | |
} | |
for (var i = start; i <= end; i++) { | |
if (type > 0) { | |
principal += payment - (exports.FV(rate, i - 2, payment, value, 1) - payment) * rate; | |
} else { | |
principal += payment - exports.FV(rate, i - 1, payment, value, 0) * rate; | |
} | |
} | |
// Return cumulative principal | |
return principal; | |
}; | |
exports.DB = function(cost, salvage, life, period, month) { | |
// Initialize month | |
month = (month === undefined) ? 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment