UNPKG

@fileverse-dev/formula-parser

Version:

Formula parser

313 lines (302 loc) 13.7 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _tinyEmitter = _interopRequireDefault(require("tiny-emitter")); var _evaluateByOperator = _interopRequireDefault(require("./evaluate-by-operator/evaluate-by-operator")); var _grammarParser = require("./grammar-parser/grammar-parser"); var _string = require("./helper/string"); var _number = require("./helper/number"); var _error = _interopRequireWildcard(require("./error")); var _cell = require("./helper/cell"); function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t2 in e) "default" !== _t2 && {}.hasOwnProperty.call(e, _t2) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t2)) && (i.get || i.set) ? o(f, _t2, i) : f[_t2] = e[_t2]); return f; })(e, t); } function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } /** * @class Parser */ var Parser = /*#__PURE__*/function (_Emitter) { function Parser() { var _this; _classCallCheck(this, Parser); _this = _callSuper(this, Parser); _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: _evaluateByOperator["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.options = Object.create(null); _this.setVariable("TRUE", true).setVariable("FALSE", false).setVariable("NULL", null); return _this; } /** * Parse formula expression. * * @param {string} expression to parse. * @param {object} options additional params. * @param {string} options.sheetId id of sheet which the formula expression belongs to. * @return {*} Returns an object with tow properties `error` and `result`. */ _inherits(Parser, _Emitter); return _createClass(Parser, [{ key: "parse", value: function parse(expression, options) { var result = null; var error = null; this.options = options; try { if (expression === "") { result = ""; } else { result = this.parser.parse(expression); } } catch (ex) { var message = (0, _error["default"])(ex.message); if (message) { error = message; } else { error = (0, _error["default"])(_error.ERROR); } } if (result instanceof Error) { error = (0, _error["default"])(result.message) || (0, _error["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} */ }, { key: "setVariable", value: function setVariable(name, value) { this.variables[name] = value; return this; } /** * Get variable name. * * @param {String} name Variable name. * @returns {*} */ }, { key: "getVariable", value: function getVariable(name) { return this.variables[name]; } /** * Retrieve variable value by its name. * * @param name Variable name. * @returns {*} * @private */ }, { key: "_callVariable", value: 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} */ }, { key: "setFunction", value: function setFunction(name, fn) { this.functions[name] = fn; return this; } /** * Get custom function. * * @param {String} name Custom function name. * @returns {*} */ }, { key: "getFunction", value: function getFunction(name) { return this.functions[name]; } /** * Call function with provided params. * * @param name Function name. * @param params Function params. * @returns {*} * @private */ }, { key: "_callFunction", value: function _callFunction(name) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var fn = this.getFunction(name); var value; if (fn) { value = fn(params); } this.emit("callFunction", name, params, function (newValue) { if (newValue !== void 0) { value = newValue; } }); return value === void 0 ? (0, _evaluateByOperator["default"])(name, params) : value; } /** * Retrieve value by its label (`B3`, `B$3`, `B$3`, `$B$3`). * * @param {String} label Coordinates. * @returns {*} * @private */ }, { key: "_callCellValue", value: function _callCellValue(label) { var _extractLabel = (0, _cell.extractLabel)(label), _extractLabel2 = _slicedToArray(_extractLabel, 3), row = _extractLabel2[0], column = _extractLabel2[1], sheetName = _extractLabel2[2]; if ((column === null || column === void 0 ? void 0 : column.index) === -1) { if (row.isAbsolute || column.isAbsolute) { throw Error(_error.ERROR_NAME); } return row.index + 1; } else if ((row === null || row === void 0 ? void 0 : row.index) === -1) { throw Error(_error.ERROR_NAME); } var value = void 0; this.emit("callCellValue", { label: label, row: row, column: column, sheetName: sheetName }, this.options, 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 */ }, { key: "_callRangeValue", value: function _callRangeValue(startLabel, endLabel) { var _extractLabel3 = (0, _cell.extractLabel)(startLabel), _extractLabel4 = _slicedToArray(_extractLabel3, 3), startRow = _extractLabel4[0], startColumn = _extractLabel4[1], startSheetName = _extractLabel4[2]; var _extractLabel5 = (0, _cell.extractLabel)(endLabel), _extractLabel6 = _slicedToArray(_extractLabel5, 3), endRow = _extractLabel6[0], endColumn = _extractLabel6[1], endSheetName = _extractLabel6[2]; if (endSheetName != null && startSheetName != endSheetName) { throw Error(_error.ERROR_VALUE); } var startCell = {}; var endCell = {}; startCell.sheetName = startSheetName; 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, this.options, 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 */ }, { key: "_throwError", value: function _throwError(errorName) { if ((0, _error.isValidStrict)(errorName)) { throw Error(errorName); } throw Error(_error.ERROR); } }]); }(_tinyEmitter["default"]); var _default = exports["default"] = Parser;