UNPKG

@fileverse-dev/formula-parser

Version:

Formula parser

306 lines (295 loc) 12.6 kB
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); } 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); } import Emitter from "tiny-emitter"; import evaluateByOperator from "./evaluate-by-operator/evaluate-by-operator"; import { Parser as GrammarParser } from "./grammar-parser/grammar-parser"; import { trimEdges } from "./helper/string"; import { toNumber, invertNumber } from "./helper/number"; import errorParser, { isValidStrict as isErrorValid, ERROR, ERROR_NAME, ERROR_VALUE } from "./error"; import { extractLabel, toLabel } from "./helper/cell"; /** * @class Parser */ var Parser = /*#__PURE__*/function (_Emitter) { function Parser() { var _this; _classCallCheck(this, Parser); _this = _callSuper(this, Parser); _this.parser = new GrammarParser(); _this.parser.yy = { toNumber: toNumber, trimEdges: trimEdges, invertNumber: invertNumber, throwError: function throwError(errorName) { return _this._throwError(errorName); }, callVariable: function callVariable(variable) { return _this._callVariable(variable); }, evaluateByOperator: evaluateByOperator, 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 = errorParser(ex.message); if (message) { error = message; } else { error = errorParser(ERROR); } } if (result instanceof Error) { error = errorParser(result.message) || errorParser(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_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 ? evaluateByOperator(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 = 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_NAME); } return row.index + 1; } else if ((row === null || row === void 0 ? void 0 : row.index) === -1) { throw 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 = extractLabel(startLabel), _extractLabel4 = _slicedToArray(_extractLabel3, 3), startRow = _extractLabel4[0], startColumn = _extractLabel4[1], startSheetName = _extractLabel4[2]; var _extractLabel5 = extractLabel(endLabel), _extractLabel6 = _slicedToArray(_extractLabel5, 3), endRow = _extractLabel6[0], endColumn = _extractLabel6[1], endSheetName = _extractLabel6[2]; if (endSheetName != null && startSheetName != endSheetName) { throw 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 = toLabel(startCell.row, startCell.column); endCell.label = 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 (isErrorValid(errorName)) { throw Error(errorName); } throw Error(ERROR); } }]); }(Emitter); export default Parser;