hyperformula-dc
Version:
HyperFormula is a JavaScript engine for efficient processing of spreadsheet-like data and formulas
334 lines (279 loc) • 14.5 kB
JavaScript
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
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); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
import "core-js/modules/es.array.map.js";
import "core-js/modules/es.array.concat.js";
import "core-js/modules/es.array.join.js";
import "core-js/modules/es.symbol.js";
import "core-js/modules/es.symbol.description.js";
import "core-js/modules/es.object.to-string.js";
import "core-js/modules/es.symbol.iterator.js";
import "core-js/modules/es.array.iterator.js";
import "core-js/modules/es.string.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.array.from.js";
import "core-js/modules/es.array.slice.js";
import "core-js/modules/es.function.name.js";
import "core-js/modules/es.object.get-prototype-of.js";
import "core-js/modules/es.reflect.construct.js";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @license
* Copyright (c) 2021 Handsoncode. All rights reserved.
*/
import { CellError, ErrorType } from '../../Cell';
import { ErrorMessage } from '../../error-message';
import { Condition, CriterionFunctionCompute } from '../CriterionFunctionCompute';
import { getRawValue, isExtendedNumber } from '../InterpreterValue';
import { ArgumentTypes, FunctionPlugin } from './FunctionPlugin';
var AverageResult = /*#__PURE__*/function () {
function AverageResult(sum, count) {
_classCallCheck(this, AverageResult);
this.sum = sum;
this.count = count;
}
_createClass(AverageResult, [{
key: "compose",
value: function compose(other) {
return new AverageResult(this.sum + other.sum, this.count + other.count);
}
}, {
key: "averageValue",
value: function averageValue() {
if (this.count > 0) {
return this.sum / this.count;
} else {
return undefined;
}
}
}], [{
key: "single",
value: function single(arg) {
return new AverageResult(arg, 1);
}
}]);
return AverageResult;
}();
AverageResult.empty = new AverageResult(0, 0);
/** Computes key for criterion function cache */
function sumifCacheKey(conditions) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var conditionsStrings = conditions.map(function (c) {
return "".concat(c.conditionRange.range.sheet, ",").concat(c.conditionRange.range.start.col, ",").concat(c.conditionRange.range.start.row);
});
return ['SUMIF'].concat(_toConsumableArray(conditionsStrings)).join(',');
}
function averageifCacheKey(conditions) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var conditionsStrings = conditions.map(function (c) {
return "".concat(c.conditionRange.range.sheet, ",").concat(c.conditionRange.range.start.col, ",").concat(c.conditionRange.range.start.row);
});
return ['AVERAGEIF'].concat(_toConsumableArray(conditionsStrings)).join(',');
}
function countifsCacheKey(conditions) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var conditionsStrings = conditions.map(function (c) {
return "".concat(c.conditionRange.range.sheet, ",").concat(c.conditionRange.range.start.col, ",").concat(c.conditionRange.range.start.row);
});
return ['COUNTIFS'].concat(_toConsumableArray(conditionsStrings)).join(',');
}
export var SumifPlugin = /*#__PURE__*/function (_FunctionPlugin) {
_inherits(SumifPlugin, _FunctionPlugin);
var _super = _createSuper(SumifPlugin);
function SumifPlugin() {
_classCallCheck(this, SumifPlugin);
return _super.apply(this, arguments);
}
_createClass(SumifPlugin, [{
key: "sumif",
value:
/**
* Corresponds to SUMIF(Range, Criterion, SumRange)
*
* Range is the range to which criterion is to be applied.
* Criterion is the criteria used to choose which cells will be included in sum.
* SumRange is the range on which adding will be performed.
*
* @param ast
* @param state
*/
function sumif(ast, state) {
var _this = this;
return this.runFunction(ast.args, state, this.metadata('SUMIF'), function (conditionArg, criterionValue, valuesArg) {
var criterion = _this.interpreter.criterionBuilder.fromCellValue(criterionValue, _this.arithmeticHelper);
if (criterion === undefined) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadCriterion);
}
valuesArg = valuesArg !== null && valuesArg !== void 0 ? valuesArg : conditionArg;
return new CriterionFunctionCompute(_this.interpreter, sumifCacheKey, 0, function (left, right) {
return _this.arithmeticHelper.nonstrictadd(left, right);
}, function (arg) {
return getRawValue(arg);
}).compute(valuesArg, [new Condition(conditionArg, criterion)]);
});
}
}, {
key: "sumifs",
value: function sumifs(ast, state) {
var _this2 = this;
return this.runFunction(ast.args, state, this.metadata('SUMIFS'), function (values) {
var conditions = [];
for (var i = 0; i < (arguments.length <= 1 ? 0 : arguments.length - 1); i += 2) {
var conditionArg = i + 1 < 1 || arguments.length <= i + 1 ? undefined : arguments[i + 1];
var criterionPackage = _this2.interpreter.criterionBuilder.fromCellValue(i + 1 + 1 < 1 || arguments.length <= i + 1 + 1 ? undefined : arguments[i + 1 + 1], _this2.arithmeticHelper);
if (criterionPackage === undefined) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadCriterion);
}
conditions.push(new Condition(conditionArg, criterionPackage));
}
return new CriterionFunctionCompute(_this2.interpreter, sumifCacheKey, 0, function (left, right) {
return _this2.arithmeticHelper.nonstrictadd(left, right);
}, function (arg) {
return getRawValue(arg);
}).compute(values, conditions);
});
}
}, {
key: "averageif",
value: function averageif(ast, state) {
var _this3 = this;
return this.runFunction(ast.args, state, this.metadata('AVERAGEIF'), function (conditionArg, criterionValue, valuesArg) {
var criterion = _this3.interpreter.criterionBuilder.fromCellValue(criterionValue, _this3.arithmeticHelper);
if (criterion === undefined) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadCriterion);
}
valuesArg = valuesArg !== null && valuesArg !== void 0 ? valuesArg : conditionArg;
var averageResult = new CriterionFunctionCompute(_this3.interpreter, averageifCacheKey, AverageResult.empty, function (left, right) {
return left.compose(right);
}, function (arg) {
if (isExtendedNumber(arg)) {
return AverageResult.single(getRawValue(arg));
} else {
return AverageResult.empty;
}
}).compute(valuesArg, [new Condition(conditionArg, criterion)]);
if (averageResult instanceof CellError) {
return averageResult;
} else {
return averageResult.averageValue() || new CellError(ErrorType.DIV_BY_ZERO);
}
});
}
/**
* Corresponds to COUNTIF(Range, Criterion)
*
* Range is the range to which criterion is to be applied.
* Criterion is the criteria used to choose which cells will be included in sum.
*
* Returns number of cells on which criteria evaluates to true.
*
* @param ast
* @param state
*/
}, {
key: "countif",
value: function countif(ast, state) {
var _this4 = this;
return this.runFunction(ast.args, state, this.metadata('COUNTIF'), function (conditionArg, criterionValue) {
var criterion = _this4.interpreter.criterionBuilder.fromCellValue(criterionValue, _this4.arithmeticHelper);
if (criterion === undefined) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadCriterion);
}
return new CriterionFunctionCompute(_this4.interpreter, function () {
return 'COUNTIF';
}, 0, function (left, right) {
return left + right;
}, function () {
return 1;
}).compute(conditionArg, [new Condition(conditionArg, criterion)]);
});
}
}, {
key: "countifs",
value: function countifs(ast, state) {
var _this5 = this;
return this.runFunction(ast.args, state, this.metadata('COUNTIFS'), function () {
var conditions = [];
for (var i = 0; i < arguments.length; i += 2) {
var conditionArg = i < 0 || arguments.length <= i ? undefined : arguments[i];
var criterionPackage = _this5.interpreter.criterionBuilder.fromCellValue(i + 1 < 0 || arguments.length <= i + 1 ? undefined : arguments[i + 1], _this5.arithmeticHelper);
if (criterionPackage === undefined) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadCriterion);
}
conditions.push(new Condition(conditionArg, criterionPackage));
}
return new CriterionFunctionCompute(_this5.interpreter, countifsCacheKey, 0, function (left, right) {
return left + right;
}, function () {
return 1;
}).compute(conditions[0].conditionRange, conditions);
});
}
}]);
return SumifPlugin;
}(FunctionPlugin);
SumifPlugin.implementedFunctions = {
'SUMIF': {
method: 'sumif',
parameters: [{
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.NOERROR
}, {
argumentType: ArgumentTypes.RANGE,
optionalArg: true
}]
},
'COUNTIF': {
method: 'countif',
parameters: [{
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.NOERROR
}]
},
'AVERAGEIF': {
method: 'averageif',
parameters: [{
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.NOERROR
}, {
argumentType: ArgumentTypes.RANGE,
optionalArg: true
}]
},
'SUMIFS': {
method: 'sumifs',
parameters: [{
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.NOERROR
}],
repeatLastArgs: 2
},
'COUNTIFS': {
method: 'countifs',
parameters: [{
argumentType: ArgumentTypes.RANGE
}, {
argumentType: ArgumentTypes.NOERROR
}],
repeatLastArgs: 2
}
};