@8sheets/data-grid 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/api/serialize.js +1 -1
- package/calc/adjust.js +1 -1
- package/calc/compile.js +1 -1
- package/calc/engine.js +1 -1
- package/calc/functions/array.js +1 -1
- package/calc/functions/database.js +1 -1
- package/calc/functions/date.js +1 -1
- package/calc/functions/financial.js +1 -1
- package/calc/functions/helpers.js +1 -1
- package/calc/functions/info.js +1 -1
- package/calc/functions/logical.js +1 -1
- package/calc/functions/lookup.js +1 -1
- package/calc/functions/math.js +1 -1
- package/calc/functions/stat.js +1 -1
- package/calc/functions/text.js +1 -1
- package/calc/parser.js +3 -3
- package/calc/values.js +1 -1
- package/calcx/async.js +1 -1
- package/calcx/functions/dynamic.js +1 -1
- package/calcx/functions/ets.js +1 -1
- package/calcx/functions/misc.js +1 -1
- package/calcx/lang/convert.js +1 -1
- package/cells/axis-ops.js +1 -1
- package/cells/book-css.js +7 -2
- package/cells/cf-engine.js +1 -1
- package/cells/find-engine.js +2 -2
- package/cells/find.js +1 -1
- package/cells/goto.js +1 -1
- package/cells/link-model.js +1 -0
- package/cells/outline-column.js +1 -1
- package/cells/panes.js +1 -1
- package/cells/rich-runs.js +2 -2
- package/cells/rich-values.js +1 -1
- package/cells/selection-modes.js +1 -1
- package/celltypes/cell-types.js +2 -2
- package/celltypes/dropdowns.js +3 -2
- package/celltypes/file-cell.js +2 -2
- package/celltypes/range-template.js +2 -2
- package/core/cell-type-rules.js +1 -0
- package/core/changes.js +1 -1
- package/core/cond-format.js +1 -1
- package/core/culture.js +1 -1
- package/core/edit-ranges.js +1 -0
- package/core/host-rules.js +1 -0
- package/core/input.js +1 -1
- package/core/numfmt.js +1 -1
- package/core/protection.js +1 -1
- package/core/region-input.js +1 -1
- package/core/sheet.js +1 -1
- package/core/sparse.js +1 -1
- package/core/structure.js +1 -1
- package/core/validation-ranges.js +1 -0
- package/core/workbook.js +1 -1
- package/datasheets/manager.js +1 -1
- package/datasheets/persist.js +1 -1
- package/extras/getdata/persist.js +2 -2
- package/i18n/en/cells.js +1 -1
- package/i18n/en/format.js +1 -1
- package/i18n/en/misc.js +1 -1
- package/i18n/en/ribbon.js +1 -1
- package/i18n/pl/cells.js +1 -1
- package/i18n/pl/format.js +1 -1
- package/i18n/pl/misc.js +1 -1
- package/i18n/pl/ribbon.js +1 -1
- package/io/client.js +1 -1
- package/io/csv.js +7 -7
- package/io/encoding.js +1 -0
- package/io/foreign-sheets.js +2 -2
- package/io/plan.js +1 -1
- package/io/xlsx-read.js +1 -1
- package/io/xlsx-tail.js +1 -1
- package/io/xlsx-write.js +2 -2
- package/io/xml-scan.js +2 -1
- package/io/zip-reader.js +1 -1
- package/package.json +1 -1
- package/pivot/engine.js +1 -1
- package/pivot/xml.js +2 -2
- package/print/note-pages.js +2 -0
- package/print/paginate.js +1 -1
- package/print/pdf-links.js +1 -0
- package/print/pdf.js +11 -11
- package/print/render-page.js +3 -3
- package/slicers/format.js +2 -2
- package/slicers/structured.js +1 -1
- package/table-view/files.js +1 -1
- package/table-view/labels-de.js +1 -1
- package/table-view/labels-es.js +1 -1
- package/table-view/labels-fr.js +1 -1
- package/table-view/labels-ja.js +1 -1
- package/table-view/labels.js +1 -1
- package/table-view/mount.js +1 -1
- package/table-view/version.js +1 -1
- package/ui/dialogs.js +3 -3
- package/ui/icons.js +1 -1
- package/ui/protection-ui.js +1 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
A data grid for the web in plain JavaScript modules with no runtime dependencies. Open a CSV or Excel file, or pass your records, and search, filter, sort, group, total, pivot and export them as CSV, Excel or PDF. Files are read in a Worker as a stream, the page keeps a bounded DOM, and a million records stay responsive. Server data plugs in through a query contract, so search, filters and totals cover the whole result.
|
|
4
4
|
|
|
5
|
-
This is version 1.1.
|
|
5
|
+
This is version 1.1.2. Components for [React](https://www.npmjs.com/package/@8sheets/data-grid-react), [Vue](https://www.npmjs.com/package/@8sheets/data-grid-vue) and [Angular](https://www.npmjs.com/package/@8sheets/data-grid-angular) build on it. For a full Excel-compatible workbook, see the Spreadsheet, [`@8sheets/core`](https://www.npmjs.com/package/@8sheets/core).
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
package/api/serialize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{BOOL as E,CHUNK_BITS as X,CHUNK_MASK as Y,CHUNK_SIZE as J,ERR as M,ERRORS as j,FORMULA as G,KIND_MASK as L,NUM as I,SPILL as Z,STR as N,Sheet as U}from"../core/sheet.js";import{MAX_COLS as v}from"../core/address.js";import{defaultStyle as b}from"../core/styles.js";import{Workbook as k}from"../core/workbook.js";import{Engine as ee}from"../calc/engine.js";const T="8sheets",_=1,ne=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),te=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder"]),B={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged"},D=new Map;function ze(e,n){D.set(e,n)}const se=new U(""),re=e=>{if(e===null||typeof e!="object")return!0;const n=Object.getPrototypeOf(e);return n===Object.prototype||n===null};function m(e,n,t){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){n?.push(`${t}: a function was left out`);return}if(Array.isArray(e))return e.map((i,s)=>m(i,n,`${t}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([i,s],o)=>[m(i,n,t),m(s,n,`${t}.${o}`)??null])};if(e instanceof Set)return{$set:[...e].map(i=>m(i,n,t))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!re(e)){if(typeof e.toJSON=="function")return m(e.toJSON(),n,t);n?.push(`${t}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${t}: a key starting with $ can't be stored`);const r={};for(const i of Object.keys(e)){if(i[0]==="_")continue;const s=m(e[i],n,`${t}.${i}`);s!==void 0&&(r[i]=s)}return r}const ie={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function h(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(h);if(e.$map)return new Map(e.$map.map(([t,r])=>[h(t),h(r)]));if(e.$set)return new Set(e.$set.map(h));if(e.$typed)return ie[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const n={};for(const t of Object.keys(e))n[t]=h(e[t]);return n}function K(e){const n={size:e.defaultSize};if(e.sizes!==null){const t=[],{sizes:r}=e;for(let i=0;i<r.length;i++){if(!e.isCustom(i)||e.isHidden(i))continue;const s=r[i],o=e.isAuto(i);let f=i;for(;f+1<r.length&&r[f+1]===s&&e.isCustom(f+1)&&!e.isHidden(f+1)&&e.isAuto(f+1)===o;)f++;t.push(o?[i,f-i+1,s,1]:[i,f-i+1,s]),i=f}t.length&&(n.runs=t)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(n.hidden=[...e.hiddenSizes]),n}function V(e,n){if(n){n.size!==void 0&&n.size!==e.defaultSize&&e.setDefaultSize(n.size);for(const[t,r,i,s]of n.runs??[])for(let o=t;o<t+r;o++)e.setSize(o,i,s===1);for(const[t,r]of n.hidden??[])r>=0&&e.setSize(t,r),e.setHidden(t,!0)}}const oe=16;function le(e){const n={};for(const t of Object.keys(e))t!=="tpl"&&t[0]!=="_"&&(n[t]=e[t]);return n}function P(e,n,t){switch(n&L){case I:return t;case N:return e.strings.get(t);case E:return t!==0;case M:return{e:j[t]??"#N/A"};default:return null}}function fe(e,n,t,r,i){const s=[],o=[];let f=null,c=-2,d=-1,l=0,u=-1;const{formulas:y}=n,{rich:a}=e.strings,S=i.styles===!1,C=i.formulas===!1;for(let p=0;p<r.length;p++){const H=r[p];if(H===void 0)continue;const Q=p*J,{kinds:W,values:$,styles:A}=H;for(let g=0;g<J;g++){const O=W[g],w=Q+g;if(A!==null&&!S&&A[g]!==0&&(A[g]===l&&w===u+1?u=w:(l!==0&&o.push([d,u-d+1,l]),d=w,u=w,l=A[g])),O===0||O&Z)continue;let z;if(O&G){const x=y.get(w*v+t),R=P(e,O,$[g]);x&&!C?(z={f:le(x)},R!==null&&(z.v=R)):z=R}else(O&L)===N?(z=e.strings.get($[g]),a!==null&&a.has($[g])&&(z={s:z,rich:a.get($[g])})):z=P(e,O,$[g]);const F=w-c-1;if(f===null||F>oe)f={r:w,v:[]},s.push(f);else for(let x=0;x<F;x++)f.v.push(null);f.v.push(z),c=w}}return l!==0&&o.push([d,u-d+1,l]),{blocks:s,styles:o}}function ce(e,n,t,r){for(const{r:i,v:s}of r){let o=null,f=-1;for(let d=0;d<s.length;d++){const l=s[d];if(l===null)continue;const u=i+d,y=u>>>X;y!==f&&(o=n._ensure(u,t),f=y);const a=u&Y;if(typeof l=="number")o.kinds[a]=I,o.values[a]=l;else if(typeof l=="string")o.kinds[a]=N,o.values[a]=e.strings.add(l);else if(typeof l=="boolean")o.kinds[a]=E,o.values[a]=l?1:0;else if(l.e!==void 0)o.kinds[a]=M,o.values[a]=Math.max(0,j.indexOf(l.e));else if(l.s!==void 0){const S=e.strings.add(l.s);o.kinds[a]=N,o.values[a]=S,e.strings.rich??=new Map,e.strings.rich.set(S,l.rich)}else if(l.f!==void 0){let S=G,C=0;const p=l.v;typeof p=="number"?(S|=I,C=p):typeof p=="string"?(S|=N,C=e.strings.add(p)):typeof p=="boolean"?(S|=E,C=p?1:0):p&&p.e!==void 0&&(S|=M,C=Math.max(0,j.indexOf(p.e))),o.kinds[a]=S,o.values[a]=C,n.setFormula(u,t,typeof l.f=="string"?{f:l.f,typed:!0}:l.f)}}const c=i+s.length-1;c>n.maxRow&&(n.maxRow=c)}t>n.maxCol&&(n.maxCol=t)}function ue(e,n,t){for(const[r,i,s]of t)for(let o=r;o<r+i;o++)e.setStyle(o,n,s)}function q(e,n){const t={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const i=e[r];i!==n[r]&&!(typeof i=="object"&&i!==null&&JSON.stringify(i)===JSON.stringify(n[r]))&&(t[r]=i)}return t}function ae(e,n,t,r,i){const s={name:n.name};n.hidden&&(s.hidden=!0),n.hidden&&n.veryHidden&&(s.veryHidden=!0),n.tabColor&&(s.tabColor=n.tabColor),n.rtl&&(s.rtl=!0),n.zoom!==1&&(s.zoom=n.zoom),n.frozenRows&&(s.frozenRows=n.frozenRows),n.frozenCols&&(s.frozenCols=n.frozenCols),n.showGridlines===!1&&(s.showGridlines=!1),s.rows=K(n.rows),s.cols=K(n.cols),n.rowStyles?.size&&(s.rowStyles=[...n.rowStyles]),n.colStyles?.size&&(s.colStyles=[...n.colStyles]),n.merges.length&&(s.merges=n.merges.map(({r0:l,c0:u,r1:y,c1:a})=>[l,u,y,a]));const o=[],f=[];n.columns.forEach((l,u)=>{if(r.cells===!1)return;const{blocks:y,styles:a}=fe(e,n,u,l,r);y.length&&o.push({c:u,blocks:y}),a.length&&f.push({c:u,runs:a})}),o.length&&(s.cells=o),f.length&&(s.styles=f);const c={};for(const l of Object.keys(n)){if(ne.has(l)||te.has(l)||l[0]==="_"||l.endsWith("Changed"))continue;const u=n[l];if(u==null||u===se[l])continue;const y=m(u,i,`${n.name}.${l}`);y!==void 0&&(c[l]=y)}Object.keys(c).length&&(s.features=c);const d=t?.objectsOf?.(n);if(d?.length){const l=m(d.map(de),i,`${n.name}.objects`);l.length&&(s.objects=l)}return s}function de(e){const{bitmap:n,blob:t,canvas:r,modelEpoch:i,...s}=e;return t&&(s.imageType=t.type),s}function Oe(e,n=null,t={}){const r=t.warnings??[],i=b(),s={format:T,version:_};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=m(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const o=e.styles.list;s.styles=o.length===1&&Object.keys(q(o[0],i)).length===0?[]:o.map(c=>q(c,i)),e.dxfs?.length&&(s.dxfs=m(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=m(e.persons,r,"persons")),e.protection&&(s.protection=m(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=m(e.getDataQueries,r,"queries")),e.customData&&(s.custom=m(e.customData,r,"custom"));const f=e.engine;if(f&&(f.manual&&(s.manualCalc=!0),f.names.size&&(s.names=[...f.names].map(([c,d])=>{const l=c.indexOf("!");return{name:d.name??(l>=0?c.slice(l+1):c),text:d.text,...l>=0?{sheet:Number(c.slice(0,l))}:{}}})),f.tables.size&&(s.tables=[...f.tables.values()].map(c=>{const{sheet:d,source:l,part:u,id:y,isNew:a,dirty:S,...C}=c;return{...m(C,r,`table ${c.name}`),sheet:e.sheets.indexOf(d)}}))),s.sheets=e.sheets.map(c=>ae(e,c,n,t,r)),n?.extrasToJSON){const c=n.extrasToJSON(r);c&&(s.extras=c)}return r.length&&(s.warnings=r),s}function me(e,n){n.hidden&&(e.hidden=!0),n.hidden&&n.veryHidden&&(e.veryHidden=!0),n.tabColor&&(e.tabColor=n.tabColor,e.tabColorChanged=!0),n.rtl&&(e.rtl=!0),n.zoom&&(e.zoom=n.zoom),e.frozenRows=n.frozenRows??0,e.frozenCols=n.frozenCols??0,n.showGridlines===!1&&(e.showGridlines=!1),V(e.rows,n.rows),V(e.cols,n.cols),(n.cols?.runs||n.cols?.hidden)&&(e.colsChanged=!0),n.rowStyles&&(e.rowStyles=new Map(n.rowStyles)),n.colStyles&&(e.colStyles=new Map(n.colStyles)),n.merges&&(e.merges=n.merges.map(([t,r,i,s])=>({r0:t,c0:r,r1:i,c1:s}))),e.viewChanged=!0;for(const[t,r]of Object.entries(n.features??{})){const i=h(r);e[t]=D.has(t)?D.get(t)(i):i,B[t]&&(e[B[t]]=!0)}}function pe(e,n){const t=b();n.styles?.length&&e.styles.load(n.styles.map(r=>({...t,...r}))),n.dxfs&&(e.dxfs=h(n.dxfs),e.sourceDxfs=0),n.persons&&(e.persons=h(n.persons),e.personsChanged=!0),n.protection&&(e.protection=h(n.protection),e.protectionChanged=!0),n.calcMode&&(e.calcMode=n.calcMode,e.calcModeChanged=!0),n.queries&&(e.getDataQueries=h(n.queries)),n.custom&&(e.customData=h(n.custom)),n.fileName&&(e.fileName=n.fileName),n.themeColors&&(e.theme=n.themeColors)}function ye(e,n,t={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(n.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),n.manualCalc&&(r.manual=!0),r.setNames((n.names??[]).map(i=>({name:i.name,text:i.text,localSheetId:i.sheet}))),n.names?.length&&(e.namesChanged=!0),r.setTables((n.tables??[]).map(i=>{const{sheet:s,...o}=i;return{...h(o),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:t.recalculate===!0}),e.dirty=!1}function $e(e,n={}){if(e?.format!==T)throw new Error(`This isn't ${T} JSON`);if(e.version>_)throw new Error(`This JSON has version ${e.version}; this code reads up to ${_}`);const t=new k;return t.engine=new ee(t),pe(t,n.styles===!1?{...e,styles:[]}:e),t.sheets=e.sheets.map(r=>new U(r.name)),e.sheets.forEach((r,i)=>{const s=t.sheets[i];me(s,r);for(const o of r.cells??[])ce(t,s,o.c,o.blocks);if(n.styles!==!1)for(const o of r.styles??[])ue(s,o.c,o.runs);if(r.styles?.length)for(const o of r.styles)o.c>s.maxCol&&(s.maxCol=o.c)}),ye(t,e,n),t}export{T as FORMAT_NAME,_ as FORMAT_VERSION,pe as applyBookMeta,me as applySheetMeta,$e as bookFromJSON,Oe as bookToJSON,h as decodeData,m as encodeData,ye as finishLoad,ze as registerFeatureReviver};
|
|
1
|
+
import{BOOL as $,CHUNK_BITS as Y,CHUNK_MASK as Z,CHUNK_SIZE as F,ERR as T,ERRORS as M,FORMULA as J,KIND_MASK as b,NUM as I,SPILL as k,STR as x,Sheet as U}from"../core/sheet.js";import{MAX_COLS as v}from"../core/address.js";import{defaultStyle as G}from"../core/styles.js";import{Workbook as ee}from"../core/workbook.js";import{Engine as te}from"../calc/engine.js";const j="8sheets",L=4,ne=new Set(["uid","name","columns","maxRow","maxCol","rows","cols","formulas","spills","rowStyles","colStyles","merges","mergeIndex","frozenRows","frozenCols","showGridlines","zoom","sourceId","sourceIndex","revision","hidden","tabColor","rtl"]),se=new Set(["apiObjects","cfEval","structureOps","dataBindings","report","isVirtual","split","onRefresh","onRejected","recorder","hostRules"]),B={cf:"cfChanged",comments:"commentsChanged",hyperlinks:"hyperlinksChanged",validations:"validationsChanged",pageSetup:"pageSetupChanged",protection:"protectionChanged",protectedRanges:"protectedRangesChanged",scenarios:"scenariosChanged",sparklines:"sparklinesChanged",threads:"threadsChanged",autoFilter:"filterChanged",cellTypes:"cellTypesChanged",cellTypeRules:"cellTypesChanged"},_=new Map;function Ee(e,t){_.set(e,t)}function re(e,t){return _.has(e)?_.get(e)(t):t}const ie=new U(""),oe=e=>{if(e===null||typeof e!="object")return!0;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null};function m(e,t,n){if(e===null||typeof e=="number"||typeof e=="string"||typeof e=="boolean")return e;if(e===void 0)return;if(typeof e=="function"){t?.push(`${n}: a function was left out`);return}if(Array.isArray(e))return e.map((i,s)=>m(i,t,`${n}[${s}]`)??null);if(e instanceof Map)return{$map:[...e].map(([i,s],o)=>[m(i,t,n),m(s,t,`${n}.${o}`)??null])};if(e instanceof Set)return{$set:[...e].map(i=>m(i,t,n))};if(ArrayBuffer.isView(e))return{$typed:e.constructor.name,v:[...e]};if(e instanceof Date)return{$date:e.toISOString()};if(!oe(e)){if(typeof e.toJSON=="function")return m(e.toJSON(),t,n);t?.push(`${n}: a ${e.constructor?.name??"class"} instance was left out`);return}if("$map"in e||"$set"in e)throw new Error(`${n}: a key starting with $ can't be stored`);const r={};for(const i of Object.keys(e)){if(i[0]==="_")continue;const s=m(e[i],t,`${n}.${i}`);s!==void 0&&(r[i]=s)}return r}const le={Uint8Array,Int8Array,Uint16Array,Int16Array,Uint32Array,Int32Array,Float32Array,Float64Array};function h(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(h);if(e.$map)return new Map(e.$map.map(([n,r])=>[h(n),h(r)]));if(e.$set)return new Set(e.$set.map(h));if(e.$typed)return le[e.$typed].from(e.v);if(e.$date)return new Date(e.$date);const t={};for(const n of Object.keys(e))t[n]=h(e[n]);return t}function V(e){const t={size:e.defaultSize};if(e.sizes!==null){const n=[],{sizes:r}=e;for(let i=0;i<r.length;i++){if(!e.isCustom(i)||e.isHidden(i))continue;const s=r[i],o=e.isAuto(i);let l=i;for(;l+1<r.length&&r[l+1]===s&&e.isCustom(l+1)&&!e.isHidden(l+1)&&e.isAuto(l+1)===o;)l++;n.push(o?[i,l-i+1,s,1]:[i,l-i+1,s]),i=l}n.length&&(t.runs=n)}return e.hiddenSizes!==null&&e.hiddenSizes.size>0&&(t.hidden=[...e.hiddenSizes]),t}function K(e,t){if(t){t.size!==void 0&&t.size!==e.defaultSize&&e.setDefaultSize(t.size);for(const[n,r,i,s]of t.runs??[])for(let o=n;o<n+r;o++)e.setSize(o,i,s===1);for(const[n,r]of t.hidden??[])r>=0&&e.setSize(n,r),e.setHidden(n,!0)}}function fe(e){const t=[];let n;for(const r of[...e.keys()].sort((i,s)=>i-s)){const i=e.get(r);n&&r===n[0]+n[1]&&i===n[2]?n[1]++:(n=[r,1,i],t.push(n))}return t}function ce(e){const t=new Map;for(const n of e){if(n.length===2){const[o,l]=n;t.set(o,l);continue}const[r,i,s]=n;if(n.length!==3||!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<1||r+i>v)throw new RangeError("Column style run exceeds the sheet or has invalid bounds");for(let o=r;o<r+i;o++)t.set(o,s)}return t}const ue=16;function ae(e){const t={};for(const n of Object.keys(e))n!=="tpl"&&n[0]!=="_"&&(t[n]=e[n]);return t}function P(e,t,n){switch(t&b){case I:return n;case x:return e.strings.get(n);case $:return n!==0;case T:return{e:M[n]??"#N/A"};default:return null}}function de(e,t,n,r,i){const s=[],o=[];let l=null,f=-2,u=-1,c=0,d=-1;const{formulas:S}=t,{rich:a}=e.strings,g=i.styles===!1,C=i.formulas===!1;for(let p=0;p<r.length;p++){const D=r[p];if(D===void 0)continue;const W=p*F,{kinds:X,values:N,styles:E}=D;for(let y=0;y<F;y++){const z=X[y],w=W+y;if(E!==null&&!g&&E[y]!==0&&(E[y]===c&&w===d+1?d=w:(c!==0&&o.push([u,d-u+1,c]),u=w,d=w,c=E[y])),z===0||z&k)continue;let O;if(z&J){const R=S.get(w*v+n),A=P(e,z,N[y]);R&&!C?(O={f:ae(R)},A!==null&&(O.v=A)):O=A}else(z&b)===x?(O=e.strings.get(N[y]),a!==null&&a.has(N[y])&&(O={s:O,rich:a.get(N[y])})):O=P(e,z,N[y]);const H=w-f-1;if(l===null||H>ue)l={r:w,v:[]},s.push(l);else for(let R=0;R<H;R++)l.v.push(null);l.v.push(O),f=w}}return c!==0&&o.push([u,d-u+1,c]),{blocks:s,styles:o}}function me(e,t,n,r){for(const{r:i,v:s}of r){let o=null,l=-1;for(let u=0;u<s.length;u++){const c=s[u];if(c===null)continue;const d=i+u,S=d>>>Y;S!==l&&(o=t._ensure(d,n),l=S);const a=d&Z;if(typeof c=="number")o.kinds[a]=I,o.values[a]=c;else if(typeof c=="string")o.kinds[a]=x,o.values[a]=e.strings.add(c);else if(typeof c=="boolean")o.kinds[a]=$,o.values[a]=c?1:0;else if(c.e!==void 0)o.kinds[a]=T,o.values[a]=Math.max(0,M.indexOf(c.e));else if(c.s!==void 0){const g=e.strings.add(c.s);o.kinds[a]=x,o.values[a]=g,e.strings.rich??=new Map,e.strings.rich.set(g,c.rich)}else if(c.f!==void 0){let g=J,C=0;const p=c.v;typeof p=="number"?(g|=I,C=p):typeof p=="string"?(g|=x,C=e.strings.add(p)):typeof p=="boolean"?(g|=$,C=p?1:0):p&&p.e!==void 0&&(g|=T,C=Math.max(0,M.indexOf(p.e))),o.kinds[a]=g,o.values[a]=C,t.setFormula(d,n,typeof c.f=="string"?{f:c.f,typed:!0}:c.f)}}const f=i+s.length-1;f>t.maxRow&&(t.maxRow=f)}n>t.maxCol&&(t.maxCol=n)}function pe(e,t,n){for(const[r,i,s]of n)for(let o=r;o<r+i;o++)e.setStyle(o,t,s)}function q(e,t){const n={};for(const r of Object.keys(e)){if(r[0]==="_")continue;const i=e[r];i!==t[r]&&!(typeof i=="object"&&i!==null&&JSON.stringify(i)===JSON.stringify(t[r]))&&(n[r]=i)}return n}function ye(e,t,n,r,i){const s={name:t.name};if(t.hidden&&(s.hidden=!0),t.hidden&&t.veryHidden&&(s.veryHidden=!0),t.tabColor&&(s.tabColor=t.tabColor),t.rtl&&(s.rtl=!0),t.zoom!==1&&(s.zoom=t.zoom),t.frozenRows&&(s.frozenRows=t.frozenRows),t.frozenCols&&(s.frozenCols=t.frozenCols),t.showGridlines===!1&&(s.showGridlines=!1),t.isVirtual&&r.dataSheets==="inline")return{...s,...Q(t,n,i,he)};s.rows=V(t.rows),s.cols=V(t.cols),t.rowStyles?.size&&(s.rowStyles=[...t.rowStyles]),t.colStyles?.size&&(s.colStyles=fe(t.colStyles)),t.merges.length&&(s.merges=t.merges.map(({r0:u,c0:c,r1:d,c1:S})=>[u,c,d,S]));const l=[],f=[];return t.columns.forEach((u,c)=>{if(r.cells===!1)return;const{blocks:d,styles:S}=de(e,t,c,u,r);d.length&&l.push({c,blocks:d}),S.length&&f.push({c,runs:S})}),l.length&&(s.cells=l),f.length&&(s.styles=f),{...s,...Q(t,n,i)}}const he=new Set(["pageSetup","cf","validations","hyperlinks","protection","comments","sparklines","rowExtras","colExtras"]);function Q(e,t,n,r=null){const i={},s={};for(const l of Object.keys(e)){if(ne.has(l)||se.has(l)||l[0]==="_"||l.endsWith("Changed")||r&&!r.has(l))continue;const f=e[l];if(f==null||f===ie[l])continue;const u=m(f,n,`${e.name}.${l}`);u!==void 0&&(s[l]=u)}Object.keys(s).length&&(i.features=s);const o=t?.objectsOf?.(e);if(o?.length){const l=m(o.map(ge),n,`${e.name}.objects`);l.length&&(i.objects=l)}return i}function ge(e){const{bitmap:t,blob:n,canvas:r,modelEpoch:i,...s}=e;return n&&(s.imageType=n.type),s}function Ae(e,t=null,n={}){const r=n.warnings??[],i=G(),s={format:j,version:1};s.activeSheet=e.activeSheet,e.fileName&&(s.fileName=e.fileName),e.themeInfo?s.theme=m(e.themeInfo,r,"theme"):e.theme&&(s.themeColors=e.theme);const o=e.styles.list;s.styles=o.length===1&&Object.keys(q(o[0],i)).length===0?[]:o.map(f=>q(f,i)),e.dxfs?.length&&(s.dxfs=m(e.dxfs,r,"dxfs")),e.persons?.length&&(s.persons=m(e.persons,r,"persons")),e.protection&&(s.protection=m(e.protection,r,"protection")),e.calcMode&&(s.calcMode=e.calcMode),e.getDataQueries&&(s.queries=m(e.getDataQueries,r,"queries")),e.customData&&(s.custom=m(e.customData,r,"custom"));const l=e.engine;if(l&&(l.manual&&(s.manualCalc=!0),l.names.size&&(s.names=[...l.names].map(([f,u])=>{const c=f.indexOf("!");return{name:u.name??(c>=0?f.slice(c+1):f),text:u.text,...c>=0?{sheet:Number(f.slice(0,c))}:{}}})),l.tables.size&&(s.tables=[...l.tables.values()].map(f=>{const{sheet:u,source:c,part:d,id:S,isNew:a,dirty:g,...C}=f;return{...m(C,r,`table ${f.name}`),sheet:e.sheets.indexOf(u)}}))),s.sheets=e.sheets.map(f=>ye(e,f,t,n,r)),s.sheets.some(f=>f.colStyles)&&(s.version=2),s.sheets.some(f=>f.features?.cellTypeRules)&&(s.version=3),n.pivots==="definitions"&&t?.pivotsToJSON){const f=t.pivotsToJSON(n);f&&(s.pivots=f,s.version=4)}if((n.dataSheets==="inline"||t?.keepsDataSheets)&&t?.dataSheetsToJSON){const f=t.dataSheetsToJSON({rows:n.rows!==!1});f&&(s.dataSheets=f,s.version=4)}if(t?.extrasToJSON){const f=t.extrasToJSON(r,n);f&&(s.extras=f)}return r.length&&(s.warnings=r),s}function Se(e,t){t.hidden&&(e.hidden=!0),t.hidden&&t.veryHidden&&(e.veryHidden=!0),t.tabColor&&(e.tabColor=t.tabColor,e.tabColorChanged=!0),t.rtl&&(e.rtl=!0),t.zoom&&(e.zoom=t.zoom),e.frozenRows=t.frozenRows??0,e.frozenCols=t.frozenCols??0,t.showGridlines===!1&&(e.showGridlines=!1),K(e.rows,t.rows),K(e.cols,t.cols),(t.cols?.runs||t.cols?.hidden)&&(e.colsChanged=!0),t.rowStyles&&(e.rowStyles=new Map(t.rowStyles)),t.colStyles&&(e.colStyles=ce(t.colStyles)),t.merges&&(e.merges=t.merges.map(([n,r,i,s])=>({r0:n,c0:r,r1:i,c1:s}))),e.viewChanged=!0;for(const[n,r]of Object.entries(t.features??{})){let i=h(r);(n==="cf"||n==="validations")&&Array.isArray(i)&&(i=i.filter(s=>!s?.managedBy)),e[n]=re(n,i),B[n]&&(e[B[n]]=!0)}}function Ce(e,t){const n=G();t.styles?.length&&e.styles.load(t.styles.map(r=>({...n,...r}))),t.dxfs&&(e.dxfs=h(t.dxfs),e.sourceDxfs=0),t.persons&&(e.persons=h(t.persons),e.personsChanged=!0),t.protection&&(e.protection=h(t.protection),e.protectionChanged=!0),t.calcMode&&(e.calcMode=t.calcMode,e.calcModeChanged=!0),t.queries&&(e.getDataQueries=h(t.queries)),t.custom&&(e.customData=h(t.custom)),t.fileName&&(e.fileName=t.fileName),t.themeColors&&(e.theme=t.themeColors)}function we(e,t,n={}){const{engine:r}=e;e.formulasEdited=!0,e.activeSheet=Math.min(t.activeSheet??0,e.sheets.length-1),r.sheetsChanged(),t.manualCalc&&(r.manual=!0),r.setNames((t.names??[]).map(i=>({name:i.name,text:i.text,localSheetId:i.sheet}))),t.names?.length&&(e.namesChanged=!0),r.setTables((t.tables??[]).map(i=>{const{sheet:s,...o}=i;return{...h(o),sheet:e.sheets[s],isNew:!0,dirty:!0}})),r.buildGraph({fullCalc:n.recalculate===!0}),e.dirty=!1}function $e(e,t={}){if(e?.format!==j)throw new Error(`This isn't ${j} JSON`);if(e.version>L)throw new Error(`This JSON has version ${e.version}; this code reads up to ${L}`);const n=new ee;return n.engine=new te(n),Ce(n,t.styles===!1?{...e,styles:[]}:e),n.sheets=e.sheets.map(r=>new U(r.name)),e.sheets.forEach((r,i)=>{const s=n.sheets[i];Se(s,r);for(const o of r.cells??[])me(n,s,o.c,o.blocks);if(t.styles!==!1)for(const o of r.styles??[])pe(s,o.c,o.runs);if(r.styles?.length)for(const o of r.styles)o.c>s.maxCol&&(s.maxCol=o.c)}),we(n,e,t),n}export{j as FORMAT_NAME,L as FORMAT_VERSION,Ce as applyBookMeta,Se as applySheetMeta,$e as bookFromJSON,Ae as bookToJSON,h as decodeData,m as encodeData,we as finishLoad,Ee as registerFeatureReviver,re as reviveSheetFeature};
|
package/calc/adjust.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{colName as j,MAX_COLS as E,MAX_ROWS as
|
|
1
|
+
import{colName as j,MAX_COLS as E,MAX_ROWS as F}from"../core/address.js";import{tokenize as T}from"./parser.js";function O(e,s,c){return e<s?e:c>0?e+c:e<s-c?null:e+c}function x(e,s,c,o,m){if(o>0){const u=e>=c?e+o:e,C=s>=c?Math.min(s+o,m-1):s;return u>=m?null:[u,C]}const h=c-o;if(e>=c&&s<h)return null;const w=e<c?e:e<h?c:e+o,U=s<c?s:s<h?c-1:s+o;return[w,U]}const b=(e,s,c,o)=>`${c?"$":""}${j(e)}${o?"$":""}${s+1}`;function X(e){if(!e?.length)return null;const s=new Map;return e.forEach((c,o)=>{for(const m of c)s.set(m.toUpperCase(),o)}),s}function _(e,s,c,o){if(e===null||s.toUpperCase()!==o)return!1;const m=e.get(o);return m!==void 0&&m===e.get(c.toUpperCase())}function G(e,s,c,o){const m=(i,a)=>!s.span||i>=s.span[0]&&a<=s.span[1];let h;try{h=T(e)}catch{return e}const w=o.toUpperCase(),U=X(s.group),u=s.axis==="row";let C="",S=0;const d=(i,a,p)=>{C+=e.slice(S,i)+p,S=a};for(let i=0;i<h.length;i++){const a=h[i];let p=c,r=null,A=i;a.t==="sheet"&&(r=a,p=a.v.book===null&&(a.v.sheet2===null?a.v.sheet.toUpperCase()===w:_(U,a.v.sheet,a.v.sheet2,w)),A=i+1);const l=h[A];if(l===void 0)break;if(l.t==="cell"){const t=l.v,v=h[A+1],$=h[A+2];if(v?.t==="op"&&v.v===":"&&$?.t==="cell"){const n=$.v,k=u?[Math.min(t.c,n.c),Math.max(t.c,n.c)]:[Math.min(t.r,n.r),Math.max(t.r,n.r)];if(p&&m(k[0],k[1])){const M=r?e.slice(r.s,r.e):"",f=u?x(Math.min(t.r,n.r),Math.max(t.r,n.r),s.at,s.n,F):x(Math.min(t.c,n.c),Math.max(t.c,n.c),s.at,s.n,E),y=r?r.s:l.s;if(f===null)d(y,$.e,`${M}#REF!`);else if(u){const R=t.r<=n.r;d(y,$.e,`${M}${b(t.c,R?f[0]:f[1],t.cAbs,t.rAbs)}:${b(n.c,R?f[1]:f[0],n.cAbs,n.rAbs)}`)}else{const R=t.c<=n.c;d(y,$.e,`${M}${b(R?f[0]:f[1],t.r,t.cAbs,t.rAbs)}:${b(R?f[1]:f[0],n.r,n.cAbs,n.rAbs)}`)}}i=A+2;continue}if(p&&m(u?t.c:t.r,u?t.c:t.r)){const n=O(u?t.r:t.c,s.at,s.n),k=u?F:E,M=r?r.s:l.s,f=r?e.slice(r.s,r.e):"";n===null||n>=k?d(M,l.e,`${f}#REF!`):d(M,l.e,f+(u?b(t.c,n,t.cAbs,t.rAbs):b(n,t.r,t.cAbs,t.rAbs)))}i=A}else if(l.t==="rows"&&u&&p&&!s.span){const t=l.v,v=x(t.r0,t.r1,s.at,s.n,F),$=r?r.s:l.s,n=r?e.slice(r.s,r.e):"";v===null?d($,l.e,`${n}#REF!`):d($,l.e,`${n}${t.a0?"$":""}${v[0]+1}:${t.a1?"$":""}${v[1]+1}`),i=A}else if(l.t==="cols"&&!u&&p&&!s.span){const t=l.v,v=x(t.c0,t.c1,s.at,s.n,E),$=r?r.s:l.s,n=r?e.slice(r.s,r.e):"";v===null?d($,l.e,`${n}#REF!`):d($,l.e,`${n}${t.a0?"$":""}${j(v[0])}:${t.a1?"$":""}${j(v[1])}`),i=A}else r&&(i=A-1)}return C+e.slice(S)}function I(e,s){const c=s.axis==="row",o=c?x(e.r0,e.r1,s.at,s.n,F):x(e.c0,e.c1,s.at,s.n,E);return o===null?null:c?{...e,r0:o[0],r1:o[1]}:{...e,c0:o[0],c1:o[1]}}export{G as adjustFormula,I as adjustRange,b as cellText};
|
package/calc/compile.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MAX_COLS as d,MAX_ROWS as A}from"../core/address.js";import{Arr as x,compareValues as L,ERR as p,Lambda as w,num as k,OMITTED as M,Ref as m,RefList as g,REJECTED as R,str as U,XlError as b}from"./values.js";import{FUNCS as E}from"./functions/registry.js";const C=5e-16;class N{constructor(e){this.cx=e,this.refs=[],this.names=[],this.tables=[],this.isVolatile=!1,this.readsSheets=!1,this.mayArray=!1,this.external=!1,this.arrayCtx=!1,this.scopes=[],this.slots=0,this.rangeSlots=new Set}compileTop(e){const i=this.any(e),{slots:a,cx:c}=this;return a===0?i:(o,t,r)=>{const s=c.frame;c.frame=new Array(a);try{return i(o,t,r)}finally{c.frame=s}}}sheetOf(e){const{cx:i}=this;if(e==null)return t=>t;if(e.book!==null&&e.book!==void 0){const t=i.externalSheet?.(e.book,e.sheet)??null;return t===null&&(this.external=!0),()=>t}const a=e.sheet;let c=-1,o=null;return()=>(c!==i.sheetGen&&(o=i.sheetByName(a),c=i.sheetGen),o)}cellRefClosure(e){const i=this.sheetOf(e.sheet),{rAbs:a,cAbs:c,r:o,c:t}=e;return this.refs.push({sheet:e.sheet,rAbs0:a,r0:o,rAbs1:a,r1:o,cAbs0:c,c0:t,cAbs1:c,c1:t}),e.sheet?.sheet2?this.sheet3d(e.sheet,(r,s,n)=>{const u=a?o:s+o,h=c?t:n+t;return new m(r,u,h,u,h)}):(r,s,n)=>{const u=a?o:r+o,h=c?t:s+t,l=i(n);return l===null||u<0||h<0||u>=A||h>=d?p.REF:new m(l,u,h,u,h)}}sheet3d(e,i){const{cx:a}=this;return(c,o)=>{const t=a.sheetsBetween(e.sheet,e.sheet2);return t===null?p.REF:new g(t.map(r=>i(r,c,o)))}}rangeClosure(e){const{a:i,b:a}=e,c=this.sheetOf(e.sheet);this.refs.push({sheet:e.sheet,rAbs0:i.rAbs,r0:i.r,rAbs1:a.rAbs,r1:a.r,cAbs0:i.cAbs,c0:i.c,cAbs1:a.cAbs,c1:a.c});const o=(t,r,s)=>{const n=i.rAbs?i.r:r+i.r,u=i.cAbs?i.c:s+i.c,h=a.rAbs?a.r:r+a.r,l=a.cAbs?a.c:s+a.c;return n<0||u<0||h<0||l<0||n>=A||h>=A||u>=d||l>=d?p.REF:new m(t,Math.min(n,h),Math.min(u,l),Math.max(n,h),Math.max(u,l))};return e.sheet?.sheet2?this.sheet3d(e.sheet,o):(t,r,s)=>{const n=c(s);return n===null?p.REF:o(n,t,r)}}rowsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:e.a0,r0:e.r0,rAbs1:e.a1,r1:e.r1,cAbs0:!0,c0:0,cAbs1:!0,c1:d-1}),(a,c,o)=>{const t=e.a0?e.r0:a+e.r0,r=e.a1?e.r1:a+e.r1,s=i(o);return s===null||t<0||r<0||t>=A||r>=A?p.REF:new m(s,Math.min(t,r),0,Math.max(t,r),d-1)}}colsClosure(e){const i=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:!0,r0:0,rAbs1:!0,r1:A-1,cAbs0:e.a0,c0:e.c0,cAbs1:e.a1,c1:e.c1}),(a,c,o)=>{const t=e.a0?e.c0:c+e.c0,r=e.a1?e.c1:c+e.c1,s=i(o);return s===null||t<0||r<0||t>=d||r>=d?p.REF:new m(s,0,Math.min(t,r),A-1,Math.max(t,r))}}any(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"omit":return()=>M;case"paren":return this.any(e.e);case"cell":return this.cellRefClosure(e);case"range":return this.rangeClosure(e);case"rows":return this.rowsClosure(e);case"cols":return this.colsClosure(e);case"array":{const a=x.of2D(e.rows);return()=>a}case"union":{const a=e.items.map(c=>this.any(c));return(c,o,t)=>{const r=[];for(const s of a){const n=s(c,o,t);if(n instanceof m)r.push(n);else if(n instanceof g)r.push(...n.refs);else return n instanceof b?n:p.VALUE}return new g(r)}}case"intersect":{const a=this.any(e.l),c=this.any(e.r);return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(s instanceof b)return s;if(n instanceof b)return n;if(!(s instanceof m)||!(n instanceof m)||s.sheet!==n.sheet)return p.VALUE;const u=Math.max(s.r0,n.r0),h=Math.min(s.r1,n.r1),l=Math.max(s.c0,n.c0),f=Math.min(s.c1,n.c1);return u>h||l>f?p.NULL:new m(s.sheet,u,l,h,f)}}case"rangeOp":{const a=this.any(e.l),c=this.any(e.r);return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return s instanceof b?s:n instanceof b?n:!(s instanceof m)||!(n instanceof m)||s.sheet!==n.sheet?p.REF:new m(s.sheet,Math.min(s.r0,n.r0),Math.min(s.c0,n.c0),Math.max(s.r1,n.r1),Math.max(s.c1,n.c1))}}case"implicit":{const a=this.any(e.e);return(c,o,t)=>{const r=a(c,o,t);return r instanceof m?r.isCell?i.read(r.sheet,r.r0,r.c0):i.intersect(r,c,o):r instanceof x?r.data[0]:r}}case"spillRef":{const a=this.any(e.e);return(c,o,t)=>{const r=a(c,o,t);return r instanceof m?i.spillRange(r):p.REF}}case"name":return this.nameNode(e);case"table":return this.tables.push({name:e.name,spec:e.spec}),(a,c,o)=>i.resolveTable(e.name,e.spec,a,c,o);case"call":return this.call(e);case"apply":{const a=this.any(e.fn),c=e.args.map(o=>this.any(o));return(o,t,r)=>{const s=a(o,t,r);return s instanceof b?s:s instanceof w?i.invoke(s,c.map(n=>n(o,t,r)),o,t,r):p.VALUE}}default:return this.value(e)}}nameNode(e){const{cx:i}=this,a=this.lookupVar(e.name);if(a!==null){const s=a;return()=>i.frame[s]}const c=i.tables?.get(e.name.toUpperCase());if(c&&(!e.sheet||e.sheet.book===null&&!e.sheet.sheet2&&e.sheet.sheet.toUpperCase()===c.sheet.name.toUpperCase()))return this.any({t:"table",name:e.name,spec:"[]"});this.names.push(e.name);const o=e.name,t=e.sheet?this.sheetOf(e.sheet):s=>s,r=e.sheet?void 0:E.get(o.toUpperCase());if(r!==void 0){const s=new w([],null,null);return s.native=r,s.label=o.toUpperCase(),(n,u,h)=>{const l=i.evalName(o,n,u,h);return l===p.NAME?s:l}}return(s,n,u)=>i.evalName(o,s,n,t(u)??u)}lookupVar(e){const i=e.toUpperCase();for(let a=this.scopes.length-1;a>=0;a--){const c=this.scopes[a].get(i);if(c!==void 0)return c}return null}deref(e){const{cx:i}=this;return this.arrayCtx?(a,c,o)=>{const t=e(a,c,o);return t instanceof m||t instanceof g?i.refToValue(t):t}:(a,c,o)=>{const t=e(a,c,o);return t instanceof m||t instanceof g?i.refAuto(t,a,c):t}}value(e){const{cx:i}=this;switch(e.t){case"lit":{const a=e.v;return()=>a}case"paren":return this.value(e.e);case"cell":{const{rAbs:a,cAbs:c,r:o,c:t}=e;if(this.refs.push({sheet:e.sheet,rAbs0:a,r0:o,rAbs1:a,r1:o,cAbs0:c,c0:t,cAbs1:c,c1:t}),e.sheet?.sheet2)return()=>p.VALUE;const r=e.sheet?this.sheetOf(e.sheet):null;return r===null?!a&&!c?(s,n,u)=>{const h=s+o,l=n+t;return h<0||l<0||h>=A||l>=d?p.REF:i.read(u,h,l)}:(s,n,u)=>{const h=a?o:s+o,l=c?t:n+t;return h<0||l<0||h>=A||l>=d?p.REF:i.read(u,h,l)}:(s,n,u)=>{const h=a?o:s+o,l=c?t:n+t,f=r(u);return f===null||h<0||l<0||h>=A||l>=d?p.REF:i.read(f,h,l)}}case"range":case"rows":case"cols":return this.arrayCtx||(this.mayArray=!0),this.deref(this.any(e));case"neg":{const a=this.value(e.e);return(c,o,t)=>{const r=a(c,o,t);return typeof r=="number"?-r:i.unary(r,s=>-s)}}case"pct":{const a=this.value(e.e);return(c,o,t)=>{const r=a(c,o,t);return typeof r=="number"?r/100:i.unary(r,s=>s/100)}}case"bin":return this.binary(e);default:return!this.arrayCtx&&this.mayYieldRange(e)&&(this.mayArray=!0),this.deref(this.any(e))}}mayYieldRange(e){switch(e.t){case"paren":return this.mayYieldRange(e.e);case"range":case"rows":case"cols":case"union":case"rangeOp":case"intersect":case"spillRef":case"apply":return!0;case"table":return!/^\[\[#This Row\],\[[^\]]+\]\]$/i.test(e.spec);case"name":{if(e.sheet)return!0;const i=this.lookupVar(e.name);return i!==null?this.rangeSlots.has(i):this.cx.nameMayYieldRange?.(e.name)??!0}case"call":{if(e.name==="LET"||e.name==="LAMBDA"||this.lookupVar(e.name)!==null)return!0;const i=E.get(e.name);return i===void 0||i.refResult?!0:i.passes?e.args.some((a,c)=>i.passes(c,e.args.length)&&this.mayYieldRange(a)):!1}default:return!1}}binary(e){const{cx:i}=this,a=this.value(e.l),c=this.value(e.r);switch(e.op){case"+":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(typeof s=="number"&&typeof n=="number"){const u=s+n;return Math.abs(u)<Math.abs(s)*C?0:u}return i.slowBin("+",s,n)};case"-":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);if(typeof s=="number"&&typeof n=="number"){const u=s-n;return Math.abs(u)<Math.abs(s)*C?0:u}return i.slowBin("-",s,n)};case"*":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return typeof s=="number"&&typeof n=="number"?s*n:i.slowBin("*",s,n)};case"/":return(o,t,r)=>{const s=a(o,t,r),n=c(o,t,r);return typeof s=="number"&&typeof n=="number"&&n!==0?s/n:i.slowBin("/",s,n)};case"^":return(o,t,r)=>i.slowBin("^",a(o,t,r),c(o,t,r));case"&":return(o,t,r)=>i.slowBin("&",a(o,t,r),c(o,t,r));default:{const o=e.op;return(t,r,s)=>i.slowBin(o,a(t,r,s),c(t,r,s))}}}call(e){const{cx:i}=this,{name:a,args:c}=e;if(a==="LET")return this.compileLet(c);if(a==="LAMBDA")return this.compileLambda(c);const o=this.lookupVar(a);if(o!==null){const r=o,s=c.map(n=>this.any(n));return(n,u,h)=>{const l=i.frame[r];return l instanceof w?i.invoke(l,s.map(f=>f(n,u,h)),n,u,h):p.VALUE}}const t=E.get(a);if(t===void 0){this.names.push(a);const r=c.map(s=>this.any(s));return(s,n,u)=>{const h=i.evalName(a,s,n,u);return h instanceof w?i.invoke(h,r.map(l=>l(s,n,u)),s,n,u):p.NAME}}if((c.length<t.min||c.length>t.max)&&!(c.length===1&&c[0].t==="omit"&&t.min===0))return()=>p.VALUE;if(t.volatile&&(this.isVolatile=!0),t.readsSheets&&(this.readsSheets=!0),t.notInExcel&&(this.notInExcel=!0),t.frozen&&(this.external=!0),t.kind==="lazy"||t.kind==="raw"){const r=this.arrayCtx;t.array&&(this.arrayCtx=!0);const s=c.map(u=>this.any(u));this.arrayCtx=r;const{fn:n}=t;return t.kind==="lazy"?(u,h,l)=>{try{return n(i,s,u,h,l)}catch(f){if(f instanceof b)return f;throw f}}:(u,h,l)=>{const f=new Array(s.length);for(let y=0;y<s.length;y++)f[y]=s[y](u,h,l);try{return n(i,f,u,h,l)}catch(y){if(y instanceof b)return y;throw y}}}return this.lifted(t,c)}toolpakArg(e,i){const{cx:a}=this,c=t=>typeof t=="boolean"&&!i?R:t;if(e.t!=="range"&&e.t!=="rows"&&e.t!=="cols"&&e.t!=="union"&&e.t!=="call"&&e.t!=="name"){const t=this.value(e);return(r,s,n)=>c(t(r,s,n))}const o=this.any(e);return(t,r,s)=>{const n=o(t,r,s);return n instanceof g||!a.legacy&&n instanceof m&&(n.r0!==n.r1||n.c0!==n.c1)?R:c(n instanceof m?a.refAuto(n,t,r):n)}}lifted(e,i){const{cx:a}=this,{fn:c,errors:o}=e,t=i.map((s,n)=>s.t==="omit"?()=>M:e.toolpak?this.toolpakArg(s,e.toolpak.logical.includes(n)):this.value(s)),r=t.length;if(r===1){const s=t[0];return(n,u,h)=>{const l=s(n,u,h);if(l instanceof x)return a.liftArr(c,[l],o);if(!o&&l instanceof b)return l;try{return c(l)}catch(f){if(f instanceof b)return f;throw f}}}if(r===2){const[s,n]=t;return(u,h,l)=>{const f=s(u,h,l),y=n(u,h,l);if(f instanceof x||y instanceof x)return a.liftArr(c,[f,y],o);if(!o){if(f instanceof b)return f;if(y instanceof b)return y}try{return c(f,y)}catch(v){if(v instanceof b)return v;throw v}}}return(s,n,u)=>{const h=new Array(r);let l=!1;for(let f=0;f<r;f++){const y=t[f](s,n,u);h[f]=y,y instanceof x&&(l=!0)}if(l)return a.liftArr(c,h,o);if(!o){for(let f=0;f<r;f++)if(h[f]instanceof b)return h[f]}try{return c(...h)}catch(f){if(f instanceof b)return f;throw f}}}compileLet(e){const{cx:i}=this;if(e.length<3||e.length%2===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const c=[];for(let t=0;t+1<e.length;t+=2){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.any(e[t+1]),n=this.slots++;this.mayYieldRange(e[t+1])&&this.rangeSlots.add(n),a.set(r.name.toUpperCase(),n),c.push(n,s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),(t,r,s)=>{for(let n=0;n<c.length;n+=2)i.frame[c[n]]=c[n+1](t,r,s);return o(t,r,s)}}compileLambda(e){const{cx:i}=this;if(e.length===0)return()=>p.VALUE;const a=new Map;this.scopes.push(a);const c=[];for(let t=0;t<e.length-1;t++){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.slots++;this.rangeSlots.add(s),a.set(r.name.toUpperCase(),s),c.push(s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),()=>new w(c,o,i.frame)}}export{N as Compiler,L as compareValues,k as num,U as str};
|
|
1
|
+
import{MAX_COLS as d,MAX_ROWS as A}from"../core/address.js";import{Arr as x,compareValues as L,ERR as p,Lambda as w,num as U,OMITTED as E,Ref as m,RefArray as M,RefList as g,REJECTED as C,str as O,XlError as b}from"./values.js";import{FUNCS as v}from"./functions/registry.js";const k=5e-16;class B{constructor(e,c=!1){this.definedName=c,this.cx=e,this.refs=[],this.names=[],this.tables=[],this.isVolatile=!1,this.readsSheets=!1,this.mayArray=!1,this.external=!1,this.keepImportedResult=!1,this.arrayCtx=!1,this.scopes=[],this.slots=0,this.rangeSlots=new Set}compileTop(e){const c=this.any(e),{slots:n,cx:i}=this;return n===0?c:(o,t,r)=>{const s=i.frame;i.frame=new Array(n);try{return c(o,t,r)}finally{i.frame=s}}}sheetOf(e){const{cx:c}=this;if(e==null)return t=>t;if(e.book!==null&&e.book!==void 0){const t=c.externalSheet?.(e.book,e.sheet)??null;return t===null&&(this.external=!0),()=>t}const n=e.sheet;let i=-1,o=null;return()=>(i!==c.sheetGen&&(o=c.sheetByName(n),i=c.sheetGen),o)}cellRefClosure(e){const c=this.sheetOf(e.sheet),n=this.definedName,{rAbs:i,cAbs:o,r:t,c:r}=e;return this.refs.push({wrap:n,sheet:e.sheet,rAbs0:i,r0:t,rAbs1:i,r1:t,cAbs0:o,c0:r,cAbs1:o,c1:r}),e.sheet?.sheet2?this.sheet3d(e.sheet,(s,a,u)=>{const h=n?(i?t:a+t)%A:i?t:a+t,f=n?(o?r:u+r)%d:o?r:u+r;return new m(s,h,f,h,f)}):(s,a,u)=>{const h=n?(i?t:s+t)%A:i?t:s+t,f=n?(o?r:a+r)%d:o?r:a+r,l=c(u);return l===null||h<0||f<0||h>=A||f>=d?p.REF:new m(l,h,f,h,f)}}sheet3d(e,c){const{cx:n}=this;return(i,o)=>{const t=n.sheetsBetween(e.sheet,e.sheet2);return t===null?p.REF:new g(t.map(r=>c(r,i,o)))}}rangeClosure(e){const{a:c,b:n}=e,i=this.sheetOf(e.sheet),o=this.definedName;this.refs.push({wrap:o,sheet:e.sheet,rAbs0:c.rAbs,r0:c.r,rAbs1:n.rAbs,r1:n.r,cAbs0:c.cAbs,c0:c.c,cAbs1:n.cAbs,c1:n.c});const t=(r,s,a)=>{const u=o?(c.rAbs?c.r:s+c.r)%A:c.rAbs?c.r:s+c.r,h=o?(c.cAbs?c.c:a+c.c)%d:c.cAbs?c.c:a+c.c,f=o?(n.rAbs?n.r:s+n.r)%A:n.rAbs?n.r:s+n.r,l=o?(n.cAbs?n.c:a+n.c)%d:n.cAbs?n.c:a+n.c;return u<0||h<0||f<0||l<0||u>=A||f>=A||h>=d||l>=d?p.REF:new m(r,Math.min(u,f),Math.min(h,l),Math.max(u,f),Math.max(h,l))};return e.sheet?.sheet2?this.sheet3d(e.sheet,t):(r,s,a)=>{const u=i(a);return u===null?p.REF:t(u,r,s)}}rowsClosure(e){const c=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:e.a0,r0:e.r0,rAbs1:e.a1,r1:e.r1,cAbs0:!0,c0:0,cAbs1:!0,c1:d-1}),(n,i,o)=>{const t=e.a0?e.r0:n+e.r0,r=e.a1?e.r1:n+e.r1,s=c(o);return s===null||t<0||r<0||t>=A||r>=A?p.REF:new m(s,Math.min(t,r),0,Math.max(t,r),d-1)}}colsClosure(e){const c=this.sheetOf(e.sheet);return this.refs.push({sheet:e.sheet,rAbs0:!0,r0:0,rAbs1:!0,r1:A-1,cAbs0:e.a0,c0:e.c0,cAbs1:e.a1,c1:e.c1}),(n,i,o)=>{const t=e.a0?e.c0:i+e.c0,r=e.a1?e.c1:i+e.c1,s=c(o);return s===null||t<0||r<0||t>=d||r>=d?p.REF:new m(s,0,Math.min(t,r),A-1,Math.max(t,r))}}any(e){const{cx:c}=this;switch(e.t){case"lit":{const n=e.v;return()=>n}case"omit":return()=>E;case"paren":return this.any(e.e);case"cell":return this.cellRefClosure(e);case"range":return this.rangeClosure(e);case"rows":return this.rowsClosure(e);case"cols":return this.colsClosure(e);case"array":{const n=x.of2D(e.rows);return()=>n}case"union":{const n=e.items.map(i=>this.any(i));return(i,o,t)=>{const r=[];for(const s of n){const a=s(i,o,t);if(a instanceof m)r.push(a);else if(a instanceof g)r.push(...a.refs);else return a instanceof b?a:p.VALUE}return new g(r)}}case"intersect":{const n=this.any(e.l),i=this.any(e.r);return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);if(s instanceof b)return s;if(a instanceof b)return a;if(!(s instanceof m)||!(a instanceof m)||s.sheet!==a.sheet)return p.VALUE;const u=Math.max(s.r0,a.r0),h=Math.min(s.r1,a.r1),f=Math.max(s.c0,a.c0),l=Math.min(s.c1,a.c1);return u>h||f>l?p.NULL:new m(s.sheet,u,f,h,l)}}case"rangeOp":{const n=this.any(e.l),i=this.any(e.r);return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);return s instanceof b?s:a instanceof b?a:!(s instanceof m)||!(a instanceof m)||s.sheet!==a.sheet?p.REF:new m(s.sheet,Math.min(s.r0,a.r0),Math.min(s.c0,a.c0),Math.max(s.r1,a.r1),Math.max(s.c1,a.c1))}}case"implicit":{const n=this.any(e.e);return(i,o,t)=>{const r=n(i,o,t);return r instanceof m?r.isCell?c.read(r.sheet,r.r0,r.c0):c.intersect(r,i,o):r instanceof x?r.data[0]:r}}case"spillRef":{const n=this.any(e.e);return(i,o,t)=>{const r=n(i,o,t);return r instanceof m?c.spillRange(r):p.REF}}case"name":return this.nameNode(e);case"table":return this.tables.push({name:e.name,spec:e.spec}),(n,i,o)=>c.resolveTable(e.name,e.spec,n,i,o);case"call":return this.call(e);case"apply":{const n=this.any(e.fn),i=e.args.map(o=>this.any(o));return(o,t,r)=>{const s=n(o,t,r);return s instanceof b?s:s instanceof w?c.invoke(s,i.map(a=>a(o,t,r)),o,t,r):p.VALUE}}default:return this.value(e)}}nameNode(e){const{cx:c}=this,n=this.lookupVar(e.name);if(n!==null){const s=n;return()=>c.frame[s]}const i=c.tables?.get(e.name.toUpperCase());if(i&&(!e.sheet||e.sheet.book===null&&!e.sheet.sheet2&&e.sheet.sheet.toUpperCase()===i.sheet.name.toUpperCase()))return this.any({t:"table",name:e.name,spec:"[]"});this.names.push(e.name);const o=e.name,t=e.sheet?this.sheetOf(e.sheet):s=>s,r=e.sheet?void 0:v.get(o.toUpperCase());if(r!==void 0){const s=new w([],null,null);return s.native=r,s.label=o.toUpperCase(),(a,u,h)=>{const f=c.evalName(o,a,u,h);return f===p.NAME?s:f}}return(s,a,u)=>c.evalName(o,s,a,t(u)??u)}lookupVar(e){const c=e.toUpperCase();for(let n=this.scopes.length-1;n>=0;n--){const i=this.scopes[n].get(c);if(i!==void 0)return i}return null}deref(e){const{cx:c}=this;return this.arrayCtx?(n,i,o)=>{const t=e(n,i,o);return t instanceof M?c.toArr(t):t instanceof m||t instanceof g?c.refToValue(t):t}:(n,i,o)=>{const t=e(n,i,o);return t instanceof M?c.toArr(t):t instanceof m||t instanceof g?c.refAuto(t,n,i):t}}value(e){const{cx:c}=this;switch(e.t){case"lit":{const n=e.v;return()=>n}case"paren":return this.value(e.e);case"cell":{if(this.definedName){const s=this.cellRefClosure(e);return(a,u,h)=>c.refAuto(s(a,u,h),a,u)}const{rAbs:n,cAbs:i,r:o,c:t}=e;if(this.refs.push({sheet:e.sheet,rAbs0:n,r0:o,rAbs1:n,r1:o,cAbs0:i,c0:t,cAbs1:i,c1:t}),e.sheet?.sheet2)return()=>p.VALUE;const r=e.sheet?this.sheetOf(e.sheet):null;return r===null?!n&&!i?(s,a,u)=>{const h=s+o,f=a+t;return h<0||f<0||h>=A||f>=d?p.REF:c.read(u,h,f)}:(s,a,u)=>{const h=n?o:s+o,f=i?t:a+t;return h<0||f<0||h>=A||f>=d?p.REF:c.read(u,h,f)}:(s,a,u)=>{const h=n?o:s+o,f=i?t:a+t,l=r(u);return l===null||h<0||f<0||h>=A||f>=d?p.REF:c.read(l,h,f)}}case"range":case"rows":case"cols":return this.arrayCtx||(this.mayArray=!0),this.deref(this.any(e));case"neg":{const n=this.value(e.e);return(i,o,t)=>{const r=n(i,o,t);return typeof r=="number"?-r:c.unary(r,s=>-s)}}case"pct":{const n=this.value(e.e);return(i,o,t)=>{const r=n(i,o,t);return typeof r=="number"?r/100:c.unary(r,s=>s/100)}}case"bin":return this.binary(e);default:return!this.arrayCtx&&this.mayYieldRange(e)&&(this.mayArray=!0),this.deref(this.any(e))}}mayYieldRange(e){switch(e.t){case"paren":return this.mayYieldRange(e.e);case"range":case"rows":case"cols":case"union":case"rangeOp":case"intersect":case"spillRef":case"apply":return!0;case"table":return!/^\[\[#This Row\],\[[^\]]+\]\]$/i.test(e.spec);case"name":{if(e.sheet)return!0;const c=this.lookupVar(e.name);return c!==null?this.rangeSlots.has(c):this.cx.nameMayYieldRange?.(e.name)??!0}case"call":{if(e.name==="LET"||e.name==="LAMBDA"||this.lookupVar(e.name)!==null)return!0;const c=v.get(e.name);return c===void 0||c.refResult?!0:c.passes?e.args.some((n,i)=>c.passes(i,e.args.length)&&this.mayYieldRange(n)):!1}default:return!1}}binary(e){const{cx:c}=this,n=this.value(e.l),i=this.value(e.r);switch(e.op){case"+":return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);if(typeof s=="number"&&typeof a=="number"){const u=s+a;return Math.abs(u)<Math.abs(s)*k?0:u}return c.slowBin("+",s,a)};case"-":return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);if(typeof s=="number"&&typeof a=="number"){const u=s-a;return Math.abs(u)<Math.abs(s)*k?0:u}return c.slowBin("-",s,a)};case"*":return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);return typeof s=="number"&&typeof a=="number"?s*a:c.slowBin("*",s,a)};case"/":return(o,t,r)=>{const s=n(o,t,r),a=i(o,t,r);return typeof s=="number"&&typeof a=="number"&&a!==0?s/a:c.slowBin("/",s,a)};case"^":return(o,t,r)=>c.slowBin("^",n(o,t,r),i(o,t,r));case"&":return(o,t,r)=>c.slowBin("&",n(o,t,r),i(o,t,r));default:{const o=e.op;return(t,r,s)=>c.slowBin(o,n(t,r,s),i(t,r,s))}}}call(e){const{cx:c}=this,{args:n}=e;let{name:i}=e;if(i.startsWith("_XLUDF.")&&(i=i.slice(7),!v.get(i)?.custom))return()=>p.NAME;if(i==="LET")return this.compileLet(n);if(i==="LAMBDA")return this.compileLambda(n);const o=this.lookupVar(i);if(o!==null){const r=o,s=n.map(a=>this.any(a));return(a,u,h)=>{const f=c.frame[r];return f instanceof w?c.invoke(f,s.map(l=>l(a,u,h)),a,u,h):p.VALUE}}const t=v.get(i);if(t===void 0){this.names.push(i);const r=n.map(s=>this.any(s));return(s,a,u)=>{const h=c.evalName(i,s,a,u);return h instanceof w?c.invoke(h,r.map(f=>f(s,a,u)),s,a,u):p.NAME}}if((n.length<t.min||n.length>t.max)&&!(n.length===1&&n[0].t==="omit"&&t.min===0))return()=>p.VALUE;if(t.volatile&&(this.isVolatile=!0),t.readsSheets&&(this.readsSheets=!0),t.notInExcel&&(this.notInExcel=!0),t.frozen&&(this.external=!0),(typeof t.keepImportedResult=="function"?t.keepImportedResult(n):t.keepImportedResult)&&(this.keepImportedResult=!0),t.kind==="lazy"||t.kind==="raw"){const r=this.arrayCtx,s=n.map((u,h)=>(this.arrayCtx=r||t.array===!0||typeof t.array=="function"&&t.array(h),this.any(u)));this.arrayCtx=r;const{fn:a}=t;return t.kind==="lazy"?(u,h,f)=>{try{return a(c,s,u,h,f)}catch(l){if(l instanceof b)return l;throw l}}:(u,h,f)=>{const l=new Array(s.length);for(let y=0;y<s.length;y++)l[y]=s[y](u,h,f);try{return a(c,l,u,h,f,r)}catch(y){if(y instanceof b)return y;throw y}}}return this.lifted(t,n)}toolpakArg(e,c){const{cx:n}=this,i=t=>typeof t=="boolean"&&!c?C:t;if(e.t!=="range"&&e.t!=="rows"&&e.t!=="cols"&&e.t!=="union"&&e.t!=="call"&&e.t!=="name"){const t=this.value(e);return(r,s,a)=>i(t(r,s,a))}const o=this.any(e);return(t,r,s)=>{const a=o(t,r,s);return a instanceof g||!n.legacy&&a instanceof m&&(a.r0!==a.r1||a.c0!==a.c1)?C:i(a instanceof m?n.refAuto(a,t,r):a)}}lifted(e,c){const{cx:n}=this,{errors:i}=e,o=e.dateSystem?(...s)=>e.fn(n.book.dateOffset,...s):e.fn,t=c.map((s,a)=>s.t==="omit"?()=>E:e.toolpak?this.toolpakArg(s,e.toolpak.logical.includes(a)):this.value(s)),r=t.length;if(r===1){const s=t[0];return(a,u,h)=>{const f=s(a,u,h);if(f instanceof x)return n.liftArr(o,[f],i);if(!i&&f instanceof b)return f;try{return o(f)}catch(l){if(l instanceof b)return l;throw l}}}if(r===2){const[s,a]=t;return(u,h,f)=>{const l=s(u,h,f),y=a(u,h,f);if(l instanceof x||y instanceof x)return n.liftArr(o,[l,y],i);if(!i){if(l instanceof b)return l;if(y instanceof b)return y}try{return o(l,y)}catch(R){if(R instanceof b)return R;throw R}}}return(s,a,u)=>{const h=new Array(r);let f=!1;for(let l=0;l<r;l++){const y=t[l](s,a,u);h[l]=y,y instanceof x&&(f=!0)}if(f)return n.liftArr(o,h,i);if(!i){for(let l=0;l<r;l++)if(h[l]instanceof b)return h[l]}try{return o(...h)}catch(l){if(l instanceof b)return l;throw l}}}compileLet(e){const{cx:c}=this;if(e.length<3||e.length%2===0)return()=>p.VALUE;const n=new Map;this.scopes.push(n);const i=[];for(let t=0;t+1<e.length;t+=2){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.any(e[t+1]),a=this.slots++;this.mayYieldRange(e[t+1])&&this.rangeSlots.add(a),n.set(r.name.toUpperCase(),a),i.push(a,s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),(t,r,s)=>{for(let a=0;a<i.length;a+=2)c.frame[i[a]]=i[a+1](t,r,s);return o(t,r,s)}}compileLambda(e){const{cx:c}=this;if(e.length===0)return()=>p.VALUE;const n=new Map;this.scopes.push(n);const i=[];for(let t=0;t<e.length-1;t++){const r=e[t];if(r.t!=="name")return this.scopes.pop(),()=>p.VALUE;const s=this.slots++;this.rangeSlots.add(s),n.set(r.name.toUpperCase(),s),i.push(s)}const o=this.any(e[e.length-1]);return this.scopes.pop(),()=>new w(i,o,c.frame)}}export{B as Compiler,L as compareValues,U as num,O as str};
|
package/calc/engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveStructuredSpec as kt}from"../slicers/structured.js";import{Arr as A,compareValues as v,ERR as k,ERR_BY_INDEX as Q,Lambda as _t,num as S,power as gt,Ref as q,RefList as $,RichValue as O,str as rt,XlError as C}from"./values.js";import{entityVm as at,richValueAt as bt}from"../cells/rich-values.js";import{Compiler as lt}from"./compile.js";import{formulaEntryLimit as wt,FormulaSyntaxError as P,Parser as z,templateKey as Mt,tokenize as X,toDisplayFormula as At}from"./parser.js";import{BOOL as H,CHUNK_BITS as L,CHUNK_MASK as x,CONTENT_MASK as ot,DIRTY as M,EMPTY as J,EVALUATING as Y,FORMULA as T,KIND_MASK as V,NUM as F,SPILL as K,STR as B,ERR as E}from"../core/sheet.js";import{colName as ct,MAX_COLS as w,MAX_ROWS as Z,parseRangeRef as G}from"../core/address.js";import{CellSet as Ct}from"./cell-set.js";import{isRowBelow as Rt}from"./fill-shape.js";import{FUNCS as xt}from"./functions/registry.js";import"./functions/index.js";const Tt=new Set(["range","rows","cols","rangeOp","intersect","union"]),tt=Symbol("pending"),ht=200,St=4096,Lt=64,et=2147483647,D=4;class st{constructor(){this.n=0,this.data=new Int32Array(D*8)}push(t,e,s,n){if((this.n+1)*D>this.data.length){const r=new Int32Array(this.data.length*2);r.set(this.data),this.data=r}const i=this.n++*D,a=this.data;a[i]=t,a[i+1]=e,a[i+2]=s,a[i+3]=n}}function Et(m,t){if(!m.valueMeta.has(t))return;const e=new Map(m.valueMeta);e.delete(t),m.valueMeta=e.size>0?e:null}function ft(m,t,e){if(m.valueMeta?.get(t)===e)return;const s=new Map(m.valueMeta??[]);s.set(t,e),m.valueMeta=s}function W(m,t){let e=m.get(t);return e===void 0&&(e=new Ct,m.set(t,e)),e}class Nt{constructor(){this.buckets=[],this.wide=[],this.all=new st,this.allCols=[]}}class Kt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=et,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.sheetReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this;this._wakeReaders(this.sheetReaders)}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(a=>a.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(a=>a.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=X(t)}catch(r){if(r instanceof P)return this._broken(t);throw r}const i=Mt(n,e,s);let a=this.templates.get(i);if(a===void 0){try{const r=new z(n,e,s).parse();a=this._compile(r)}catch(r){if(!(r instanceof P))throw r;a=this._broken(t)}a.cacheKey=i,this.templates.set(i,a)}return a}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&Rt(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t){const e=new lt(this),s=e.compileTop(t);for(;t.t==="paren";)t=t.e;return{fn:s,refs:e.refs,names:e.names,tables:e.tables,isVolatile:e.isVolatile,readsSheets:e.readsSheets,notInExcel:e.notInExcel===!0,mayArray:e.mayArray,rangeResult:Tt.has(t.t)||t.t==="call"&&xt.get(t.name)?.refResult===!0,external:e.external}}_broken(){return{invalid:!0,fn:()=>k.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){const e=wt(t);if(e)throw new P(e);it(new z(X(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/w),n.base%w):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/w),n.base%w):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Nt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,a,r,o){const l=this._index(t),c=a.uid<<14|o;if(i-s>=Lt){l.all.push(r,c,e,n),l.allCols.push(s,i);return}if(n-e>=St){for(let p=s;p<=i;p++){let f=l.wide[p];f===void 0&&(f=new st,l.wide[p]=f),f.push(r,c,e,n)}return}const u=e>>>L,d=n>>>L;for(let p=s;p<=i;p++){let f=l.buckets[p];f===void 0&&(f=[],l.buckets[p]=f);for(let h=u;h<=d;h++){let y=f[h];y===void 0&&(y=new st,f[h]=y),y.push(r,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external)return i;for(const a of i.refs)this._addRefDep(a,t,e,s);for(const a of i.names)this._addNameDeps(a,t,e,s);for(const a of i.tables)this._addTableDep(a,t,e,s);return i.readsSheets&&W(this.sheetReaders,t).add(e,s),i.isVolatile&&W(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&W(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&W(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.rAbs0?t.r0:s+t.r0,a=t.rAbs1?t.r1:s+t.r1,r=t.cAbs0?t.c0:n+t.c0,o=t.cAbs1?t.c1:n+t.c1,l=Math.max(0,Math.min(i,a)),c=Math.min(Z-1,Math.max(i,a)),u=Math.max(0,Math.min(r,o)),d=Math.min(w-1,Math.max(r,o));if(l>c||u>d)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const f of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(f,l,u,c,d,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const p=t.sheet?this.sheetByName(t.sheet.sheet):e;p&&this._addDep(p,l,u,c,d,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){i.readsSheets&&W(this.sheetReaders,e).add(s,n);for(const a of i.refs)this._addRefDep(a,e,s,n);for(const a of i.tables)this._addTableDep(a,e,s,n);for(const a of i.names)a.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(a,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof q&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.sheetReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const s=this,n=this.sheetGen,i=this.book.sheets.map(u=>[u,u.formulas]);let a=0,r=0,o=0,l=0;const c=()=>{const u=performance.now()+s.sliceMs;let d=0;for(;a<i.length;a++,r=0,o=0,l=0){const[f,h]=i[a],{columns:y}=h;for(;r<y.length;r++,o=0,l=0){const _=y[r];if(_!==void 0)for(;o<_.length;o++,l=0){const g=_[o];if(g===void 0)continue;const{ids:b}=g,N=o<<L;for(;l<=x;l++){const R=b[l];if(R===0)continue;const U=h.infos[R],I=N+l;U.t==="dataTable"&&s.dataTables.push({sheet:f,row:I,col:r,info:U});const yt=s.register(f,I,r,U);if(s._initFormula(f,I,r,U,yt,t),++d%256===0&&performance.now()>u){l++,s.onProgress?.({preparing:!0}),s._later(c);return}}}}}s.graphReady=!0,s.sheetGen!==n&&s._wakeReaders(s.sheetReaders);const p=s.pendingChanges;s.pendingChanges=[];for(const[f,h,y,_]of p)s.cellsChanged(f,h,y,_);s._schedule(),e?.()};c()}_initFormula(t,e,s,n,i,a){const r=t._chunk(e,s);if(r===void 0)return;const o=e&x;if(n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n),i.external)return;const l=r.kinds[o];(a||i.isVolatile||(l&V)===J||i.notInExcel&&(l&V)===E)&&(r.kinds[o]=l|M,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=G(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*w+s,{...i,blocked:!1,fixed:!n.cm});for(let a=i.r0;a<=i.r1;a++)for(let r=i.c0;r<=i.c1;r++){if(a===e&&r===s)continue;const o=t._ensure(a,r);o.kinds[a&x]|=K}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const a=[t,e,s,n,i];for(;a.length>0;){const r=a.pop(),o=a.pop(),l=a.pop(),c=a.pop(),u=a.pop(),d=this.deps.get(u);if(d===void 0)continue;const p=(y,_)=>{const g=this.sheetsByUid.get(_>>>14);if(g===void 0)return;const b=_&16383,N=g._chunk(y,b);if(N===void 0)return;const R=y&x,U=N.kinds[R];(U&T)===0||(U&M)!==0||(N.kinds[R]=U|M,this._enqueue(g,y,b),a.push(g,b,b,y,y))},f=o>>>L,h=r>>>L;for(let y=c;y<=l;y++){const _=d.buckets[y];if(_!==void 0)for(let b=f;b<=h;b++){const N=_[b];if(N===void 0)continue;const{data:R}=N,U=N.n*D;for(let I=0;I<U;I+=D)r>=R[I+2]&&o<=R[I+3]&&p(R[I],R[I+1])}const g=d.wide[y];if(g!==void 0){const{data:b}=g,N=g.n*D;for(let R=0;R<N;R+=D)r>=b[R+2]&&o<=b[R+3]&&p(b[R],b[R+1])}}if(d.all.n>0){const{data:y}=d.all;for(let _=0;_<d.all.n;_++){const g=_*D;r>=y[g+2]&&o<=y[g+3]&&l>=d.allCols[_*2]&&c<=d.allCols[_*2+1]&&p(y[g],y[g+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let a=0;a<n;a++){const r=e[a],o=s[a],l=i.get(o);l===void 0?i.set(o,[r,r]):(r<l[0]&&(l[0]=r),r>l[1]&&(l[1]=r));const c=t._chunk(r,o);if(c===void 0)continue;const u=r&x,d=c.kinds[u];if(d&T){const p=t.formula(r,o);p&&(this.register(t,r,o,p),d&M||(c.kinds[u]=d|M,this._enqueue(t,r,o)))}t.spills&&this._spillTouched(t,r,o)}for(const[a,r]of i)this._dirtyFrom(t,a,a,r[0],r[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*w+s;for(const[i,a]of t.spills){const r=Math.floor(i/w),o=i-r*w;if(i===n){(t.kind(r,o)&T)===0&&(this._clearSpill(t,a,r,o),t.spills.delete(i));continue}if(e>=a.r0&&e<=a.r1&&s>=a.c0&&s<=a.c1){const l=t._chunk(r,o);if(l===void 0)continue;const c=r&x,u=l.kinds[c];u&T&&!(u&M)&&(l.kinds[c]=u|M,this._enqueue(t,r,o),this._dirtyFrom(t,o,o,r,r))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const a=s&x,r=i.kinds[a];if(!(r&T)){e.delete(s,n);return}r&M||(i.kinds[a]=r|M,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending;if(t<=this.syncLimit&&(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.pending===0)){this._finish();return}this.running=!0,this._total=t;const e=()=>{this._slice(this.sliceMs),this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this._later(e)):(this.running=!1,this._finish())};this._later(e)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,a=1;for(;this.qHead<this.qLen;){const r=this.queue[this.qHead++],o=this.queue[this.qHead++],l=this.queue[this.qHead++],c=this.sheetsByUid.get(r);if(c!==void 0&&(this._run(c,o,l),e&&--a===0)){const u=performance.now();if(u>n)break;i=u-s<.5?Math.min(i*2,16):1,a=i,s=u}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&V){case F:return n;case B:return this.book.strings.get(n);case H:return n!==0;case E:return Q[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&T;n==null?t.setCell(e,s,i|F,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|F,n):t.setCell(e,s,i|E,k.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|H,n?1:0):n instanceof C?t.setCell(e,s,i|E,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,a)=>{t.setCell(i.row,i.col,i.kind,i.value),s[a]=i.row,n[a]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:a,col:r})=>({row:a,col:r,kind:t.kind(a,r)&(V|T),value:t.value(a,r)})),i=this.inTables;this.inTables=!0;try{return this._setInputs(t,e.map(({row:a,col:r,text:o})=>{const l=Number(o);return o!==""&&Number.isFinite(l)?{row:a,col:r,kind:F,value:l}:{row:a,col:r,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=G(e.ref),n=G(e.r1??"");if(!s||!n)return;const i=e.r2?G(e.r2):null,a=e.dt2D==="1"||e.dt2D==="true",r=e.dtr==="1"||e.dtr==="true",o=(h,y)=>({kind:t.kind(h,y)&V,value:t.value(h,y)}),c=[n,i].filter(Boolean).map(h=>({row:h.r0,col:h.c0,kind:t.kind(h.r0,h.c0)&(V|T),value:t.value(h.r0,h.c0)})),u=[];for(let h=s.r0;h<=s.r1;h++)for(let y=s.c0;y<=s.c1;y++){let _,g;a?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)},{row:i.r0,col:i.c0,...o(h,s.c0-1)}],g=[s.r0-1,s.c0-1]):r?(_=[{row:n.r0,col:n.c0,...o(s.r0-1,y)}],g=[h,s.c0-1]):(_=[{row:n.r0,col:n.c0,...o(h,s.c0-1)}],g=[s.r0-1,y]),this._setInputs(t,_);let b=this.read(t,g[0],g[1]);b instanceof A&&(b=b.data[0]),u.push(h,y,b)}this._setInputs(t,c);const d=u.length/3,p=new Uint32Array(d),f=new Uint32Array(d);for(let h=0;h<d;h++)p[h]=u[h*3],f[h]=u[h*3+1],this._writePlain(t,p[h],f[h],u[h*3+2]);this.cellsChanged(t,p,f,d),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=G(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(r,o,l)=>{let c=e.get(r.uid);c===void 0&&(c=new Map,e.set(r.uid,c)),c.set(o*w+l,[r,o,l])};for(let r=0;r<t.length;r+=3)s(t[r],t[r+1],t[r+2]);const n=[];for(const r of this.book.sheets){const o=e.get(r.uid);o&&n.push(...[...o.keys()].sort((l,c)=>l-c).map(l=>o.get(l)))}this.cycleMembers??=new Map;for(const r of n)this.cycleMembers.set(`${r[0].uid}:${r[1]}:${r[2]}`,r);const{count:i,delta:a}=this.iterate;for(let r=1;r<=i;r++){let o=0;for(const[l,c,u]of n){const d=l._chunk(c,u);if(d===void 0)continue;const p=c&x;if(!(d.kinds[p]&T))continue;const f=d.values[p];d.kinds[p]|=M,this.iterating=!0,this._run(l,c,u),this.iterating=!1;const h=Math.abs(d.values[p]-f);h>o&&(o=h)}if(this.onProgress?.({iteration:r,iterations:i}),o<a)break}for(const[r,o,l]of n)this._dirtyFrom(r,l,l,o,o);for(const[r,o,l]of n){const c=r._chunk(o,l);c!==void 0&&(c.kinds[o&x]&=~M)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&x]&T)||(n.kinds[e&x]|=M,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],a=n[n.length-2],r=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=et,this._calc(r,a,i),n.length-=3}catch(o){if(o!==tt)throw o;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&x,a=n.kinds[i];if(!(a&M))return;if(a&Y){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=ht)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,tt;const r=t.formula(e,s);if(r===void 0||!(a&T)){n.kinds[i]=a&~M;return}const o=this._templateFor(t,e,s,r);if(o.external){n.kinds[i]=a&~M;return}n.kinds[i]=a|Y;const l=this.evalTop;l+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[l]=t.uid,this.evalStack[l+1]=e,this.evalStack[l+2]=s,this.evalTop=l+3;const c=this.cycleLow;this.cycleLow=et;const u=this.legacy,d=this.frame,p=r.typed!==!0&&r.t!=="array";this.legacy=p,this.depth++;let f;try{f=o.fn(e,s,t),(f instanceof q||f instanceof $)&&(f=this.refAuto(f,e,s))}catch(y){if(n.kinds[i]&=~Y,this.depth--,this.legacy=u,this.frame=d,this.evalTop=l,this.cycleLow=c,y===tt)throw y;y instanceof C?f=y:(console.error("Formula evaluation failed",y),f=k.VALUE),this._store(t,n,i,e,s,f,r,p);return}this.depth--,this.legacy=u,this.frame=d,this.evalTop=l;const h=this.cycleLow;if(this.cycleLow=h<l&&h<c?h:c,h<=l){if(this.iterate!==null){n.kinds[i]=a&~(M|Y),this.cycleFound.push(t,e,s);return}f=0}this._store(t,n,i,e,s,f,r,p)}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,a,r,o){let l=a;l instanceof _t&&(l=k.CALC),l instanceof A?r.t==="array"&&!r.cm&&r.ref?l=this._fillFixedArray(t,n,i,r,l):o||l.rows===1&&l.cols===1?(l=l.data[0],t.spills&&this._releaseSpill(t,n,i)):l=this._spill(t,n,i,r,l):t.spills&&!(r.t==="array"&&!r.cm)&&this._releaseSpill(t,n,i),r.t==="array"&&!r.cm&&r.ref&&!(a instanceof A)&&(l=this._fillFixedArray(t,n,i,r,A.filled(1,1,l)));let c=T,u=0;typeof l=="number"?Number.isFinite(l)?(c|=F,u=l):(c|=E,u=k.NUM.index):typeof l=="string"?(c|=B,u=this.book.strings.add(l)):typeof l=="boolean"?(c|=H,u=l?1:0):l instanceof C?(c|=E,u=l.index):l instanceof O?(c|=E,u=k.VALUE.index):c|=F,l instanceof O?ft(t,n*w+i,at(this.book,l.index)):t.valueMeta!==null&&((e.kinds[s]&ot)!==c||e.values[s]!==u)&&!/IMAGE\(/i.test(r.f??r.sf??"")&&Et(t,n*w+i),e.kinds[s]=c,e.values[s]=u,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=K,a=0;typeof n=="number"?(i|=Number.isFinite(n)?F:E,a=Number.isFinite(n)?n:k.NUM.index):typeof n=="string"?(i|=B,a=this.book.strings.add(n)):typeof n=="boolean"?(i|=H,a=n?1:0):n instanceof C?(i|=E,a=n.index):n==null?i|=F:(i|=E,a=k.VALUE.index,n instanceof O&&ft(t,e*w+s,at(this.book,n.index))),t.setCell(e,s,i,a)}_fillFixedArray(t,e,s,n,i){const a=G(n.ref);if(a===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*w+s,{...a,blocked:!1,fixed:!0});const r=(l,c)=>{const u=i.rows===1?0:l,d=i.cols===1?0:c;return u>=i.rows||d>=i.cols?k.NA:i.get(u,d)};for(let l=a.r0;l<=a.r1;l++)for(let c=a.c0;c<=a.c1;c++)l===e&&c===s||this._writeArrayCell(t,l,c,r(l-a.r0,c-a.c0));this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1);const o=r(e-a.r0,s-a.c0);return o===null?0:o}_spill(t,e,s,n,i){const a=e*w+s;t.spills||(t.spills=new Map);const r=t.spills.get(a),o=e+i.rows-1,l=s+i.cols-1,c={r0:e,c0:s,r1:o,c1:l,blocked:!1,fixed:!1},u=(f,h)=>r&&f>=r.r0&&f<=r.r1&&h>=r.c0&&h<=r.c1;let d=o>=Z||l>=w;if(!d)t:for(let f=e;f<=o;f++)for(let h=s;h<=l;h++){if(f===e&&h===s)continue;const y=t.kind(f,h);if((y&ot)!==0&&!(y&K&&u(f,h))){d=!0;break t}if(t.merges.length>0&&t.mergeAt(f,h)){d=!0;break t}}if(d)return r&&!r.blocked&&this._clearSpill(t,r,e,s),c.blocked=!0,c.r1=Math.min(o,Z-1),c.c1=Math.min(l,w-1),t.spills.set(a,c),k.SPILL;if(r&&!r.blocked){for(let f=r.r0;f<=r.r1;f++)for(let h=r.c0;h<=r.c1;h++)f>=c.r0&&f<=c.r1&&h>=c.c0&&h<=c.c1||(t.kind(f,h)&K)!==0&&t.setCell(f,h,J,0);this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1)}t.spills.set(a,c);for(let f=e;f<=o;f++)for(let h=s;h<=l;h++)f===e&&h===s||this._writeArrayCell(t,f,h,i.get(f-e,h-s));n.t="array",n.ref=`${ut(s)}${e+1}:${ut(l)}${o+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,l,e,o);const p=i.data[0];return p===null?0:p}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let a=e.c0;a<=e.c1;a++)i===s&&a===n||(t.kind(i,a)&K)!==0&&t.setCell(i,a,J,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*w+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const a=t.formula(e,s);a&&a.typed&&(delete a.ref,delete a.cm,delete a.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const a=Math.floor(n/w);return{row:a,col:n-a*w,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*w+n);return!i||i.blocked?k.REF:new q(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>L];if(i===void 0)return null;const a=e&x;let r=i.kinds[a];if(r===0)return null;switch(r&M&&(this._calc(t,e,s),r=i.kinds[a]),r&V){case F:return i.values[a];case B:return this.book.strings.get(i.values[a]);case H:return i.values[a]!==0;case E:{if(t.valueMeta!==null&&this.book.richValues){const o=bt(this.book,t,e,s);if(o!==null)return o}return Q[i.values[a]]??k.NA}default:return null}}refToValue(t){return t instanceof $?t.refs.length===1?this.refToValue(t.refs[0]):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof $?t.refs.length===1?this.refAuto(t.refs[0],e,s):k.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):k.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof A)return t;if(t instanceof q){const{r0:e,c0:s,r1:n,c1:i}=this.trim(t),a=n-e+1,r=i-s+1,o=new Array(a*r);let l=0;for(let c=e;c<=n;c++)for(let u=s;u<=i;u++)o[l++]=this.read(t.sheet,c,u);return new A(a,r,o)}if(t instanceof $){if(t.refs.length===1)return this.toArr(t.refs[0]);throw k.VALUE}if(t instanceof C)throw t;return new A(1,1,[t])}scalar(t,e,s){return t instanceof q?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof $?k.VALUE:t instanceof A?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let a=t.c0;a<=n;a++){const r=s.columns[a];if(r!==void 0)for(let o=t.r0>>>L;o<=i>>>L;o++){const l=r[o];if(l===void 0)continue;const c=o<<L,u=Math.max(t.r0-c,0),d=Math.min(i-c,x),{kinds:p}=l;for(let f=u;f<=d;f++){if(p[f]===0)continue;const h=this.read(s,c+f,a);h!==null&&e(h,c+f,a)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:a,count:r}=e;for(let o=t.c0;o<=n;o++){const l=s.columns[o];if(l!==void 0)for(let c=t.r0>>>L;c<=i>>>L;c++){const u=l[c];if(u===void 0)continue;const d=c<<L,p=Math.max(t.r0-d,0),f=Math.min(i-d,x),{kinds:h,values:y}=u;for(let _=p;_<=f;_++){let g=h[_];if(g===0)continue;g&M&&(this._calc(s,d+_,o),g=h[_]);const b=g&V;if(b===F)a+=y[_],r++;else if(b===E)throw Q[y[_]]}}}e.sum=a,e.count=r}unary(t,e){if(t instanceof C)return t;if(t instanceof A)return new A(t.rows,t.cols,t.data.map(s=>{try{return s instanceof C?s:e(S(s))}catch(n){return n}}));try{return e(S(t))}catch(s){if(s instanceof C)return s;throw s}}slowBin(t,e,s){if(e instanceof A||s instanceof A)return this._binArr(t,e,s);if(e instanceof C)return e;if(s instanceof C)return s;try{return dt(t,e,s)}catch(n){if(n instanceof C)return n;throw n}}_binArr(t,e,s){const n=e instanceof A?e:null,i=s instanceof A?s:null,a=Math.max(n?n.rows:1,i?i.rows:1),r=Math.max(n?n.cols:1,i?i.cols:1),o=new Array(a*r);for(let l=0;l<a;l++)for(let c=0;c<r;c++){const u=nt(e,l,c),d=nt(s,l,c);let p;if(u instanceof C)p=u;else if(d instanceof C)p=d;else try{p=dt(t,u,d)}catch(f){p=f}o[l*r+c]=p}return new A(a,r,o)}liftArr(t,e,s){let n=1,i=1;for(const l of e)l instanceof A&&(l.rows>n&&(n=l.rows),l.cols>i&&(i=l.cols));const a=new Array(n*i),r=e.length,o=new Array(r);for(let l=0;l<n;l++)for(let c=0;c<i;c++){let u=null;for(let d=0;d<r;d++){const p=nt(e[d],l,c);o[d]=p,!s&&u===null&&p instanceof C&&(u=p)}if(u!==null){a[l*i+c]=u;continue}try{a[l*i+c]=t(...o)}catch(d){if(d instanceof C)a[l*i+c]=d;else throw d}}return new A(n,i,a)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const a=t.frame?t.frame.slice():[],{params:r}=t;if(e.length>r.length)return k.VALUE;for(let l=0;l<r.length;l++)a[r[l]]=l<e.length?e[l]:void 0;const o=this.frame;if(this.frame=a,this.depth++,this.depth>=ht*4)return this.depth--,this.frame=o,k.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=o}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return k.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(r=>()=>r),s,n,i);const a=e.map(r=>r instanceof q||r instanceof $?this.refToValue(r):r);if(a.some(r=>r instanceof A))return this.liftArr(t.fn,a,t.errors);if(!t.errors){for(const r of a)if(r instanceof C)return r}return t.fn(...a)}catch(a){if(a instanceof C)return a;throw a}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),a=this.names.get(`${i}!${s}`);if(a)return{key:`${i}!${s}`,entry:a}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new z(X(s.entry.text),0,0).parse())}catch(i){if(!(i instanceof P))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new lt(this).mayYieldRange(new z(X(n.text),0,0).parse())}catch(i){if(i instanceof P)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?k.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=mt(t,e,s);if(!(n instanceof q))return null;const i=/#This Row|^\[\s*@/i.test(e),a=(r,o)=>i?`${ct(o)}${r+1}`:`$${ct(o)}$${r+1}`;return n.isCell?a(n.r0,n.c0):`${a(n.r0,n.c0)}:${a(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let a=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const r of this.tables.values())if(r.sheet===i&&s>=r.r0&&s<=r.r1&&n>=r.c0&&n<=r.c1){a=r;break}}return a?mt(a,e,s):k.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,a,r)=>{const o=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof C)return;const l=n?a-t.r0:r-t.c0,c=s.get(o);(c===void 0||l<c)&&s.set(o,l)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,a)=>{const r=s._chunk(i,a);if(r===void 0)return;const o=i&x,l=r.kinds[o];if(!(l&T)){n.delete(i,a);return}l&M||(r.kinds[o]=l|M,this._enqueue(s,i,a)),this._dirtyFrom(s,a,a,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&T)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return At(t)}}function ut(m){let t="";for(let e=m+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function nt(m,t,e){if(!(m instanceof A))return m;const s=m.rows===1?0:t,n=m.cols===1?0:e;return s>=m.rows||n>=m.cols?k.NA:m.data[s*m.cols+n]}function dt(m,t,e){if((t instanceof O||e instanceof O)&&m!=="="&&m!=="<>"&&m!=="&")throw k.VALUE;switch(m){case"+":{const s=S(t),n=s+S(e);return Math.abs(n)<Math.abs(s)*pt?0:j(n)}case"-":{const s=S(t),n=s-S(e);return Math.abs(n)<Math.abs(s)*pt?0:j(n)}case"*":return j(S(t)*S(e));case"/":{const s=S(t),n=S(e);if(n===0)throw k.DIV0;return j(s/n)}case"^":{const s=S(t),n=S(e);if(s===0&&n===0)throw k.NUM;if(s===0&&n<0)throw k.DIV0;const i=gt(s,n);if(Number.isNaN(i))throw k.NUM;return j(i)}case"&":return rt(t)+rt(e);case"=":return v(t,e)===0;case"<>":return v(t,e)!==0;case"<":return v(t,e)<0;case">":return v(t,e)>0;case"<=":return v(t,e)<=0;case">=":return v(t,e)>=0;default:throw k.VALUE}}const pt=5e-16;function j(m){if(!Number.isFinite(m))throw k.NUM;return m}function mt(m,t,e){const s=kt(m,t,e);return s==="REF"?k.REF:s==="VALUE"?k.VALUE:new q(m.sheet,s.top,s.left,s.bottom,s.right)}const Ut={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function It(m,t){for(let e=0;e<m.length;e++){const s=m[e];if(s===t||s==="odd"&&t>=m[e+1]&&t%2===1||s==="even"&&t>=m[e+1]&&t%2===0)return!0}return!1}function it(m){if(!(m===null||typeof m!="object")){if(Array.isArray(m)){for(const t of m)it(t);return}if(m.t==="call"){const t=Ut[String(m.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&m.args.forEach((e,s)=>{if(e?.t==="array"&&It(t,s))throw new Error(`${m.name} takes a range here`)})}for(const t of Object.values(m))t!==null&&typeof t=="object"&&it(t)}}export{Kt as Engine};
|
|
1
|
+
import{resolveStructuredSpec as bt}from"../slicers/structured.js";import{Arr as A,compareValues as $,ERR as g,ERR_BY_INDEX as J,Lambda as wt,num as N,power as Mt,Ref as V,RefArray as st,RefList as O,RichValue as H,str as ot,XlError as C}from"./values.js";import{entityVm as ct,richValueAt as Rt}from"../cells/rich-values.js";import{Compiler as ht}from"./compile.js";import{formulaEntryLimit as At,FormulaSyntaxError as K,Parser as Z,templateKey as Ct,tokenize as tt,toDisplayFormula as xt}from"./parser.js";import{BOOL as W,CHUNK_BITS as T,CHUNK_MASK as x,CONTENT_MASK as X,DIRTY as w,EMPTY as D,EVALUATING as Y,FORMULA as L,KIND_MASK as S,NUM as U,SPILL as j,STR as B,ERR as I}from"../core/sheet.js";import{colName as ut,MAX_COLS as b,MAX_ROWS as v,parseRangeRef as P}from"../core/address.js";import{CellSet as Tt}from"./cell-set.js";import{isRowBelow as Lt}from"./fill-shape.js";import{FUNCS as St}from"./functions/registry.js";import"./functions/index.js";const Et=new Set(["range","rows","cols","rangeOp","intersect","union"]);function ft(p){for(;p.t==="paren";)p=p.e;if(Et.has(p.t))return!0;if(p.t!=="call")return!1;const t=St.get(p.name),e=t?.refResult;return(typeof e=="function"?e(p.args):e===!0)?!0:t?.passes!==void 0&&p.args.some((s,n)=>t.passes(n,p.args.length)&&ft(s))}const nt=Symbol("pending"),dt=200,It=1e6,Nt=4096,Ut=64,it=2147483647,G=4;class rt{constructor(){this.n=0,this.data=new Int32Array(G*8)}push(t,e,s,n){if((this.n+1)*G>this.data.length){const a=new Int32Array(this.data.length*2);a.set(this.data),this.data=a}const i=this.n++*G,r=this.data;r[i]=t,r[i+1]=e,r[i+2]=s,r[i+3]=n}}function Ft(p,t){if(!p.valueMeta.has(t))return;const e=new Map(p.valueMeta);e.delete(t),p.valueMeta=e.size>0?e:null}function pt(p,t,e){if(p.valueMeta?.get(t)===e)return;const s=new Map(p.valueMeta??[]);s.set(t,e),p.valueMeta=s}function z(p,t){let e=p.get(t);return e===void 0&&(e=new Tt,p.set(t,e)),e}class Vt{constructor(){this.buckets=[],this.wide=[],this.all=new rt,this.allCols=[]}}class jt{constructor(t){this.book=t,this.sheetGen=0,this.sheetMap=new Map,this.deps=new Map,this.templates=new Map,this.lastOwn={row:-2,col:-1,text:"",tpl:{cacheKey:void 0}},this.frame=null,this.depth=0,this.legacy=!1,this.pendingSheet=null,this.pendingRow=0,this.pendingCol=0,this.circular=null,this.evalStack=new Int32Array(3*256),this.evalTop=0,this.cycleLow=it,this.iterate=null,this.cycleFound=[],this.cycleMembers=null,this.iterating=!1,this.sliceMs=10,this.syncLimit=4e3,this.externalLinks=null,this.names=new Map,this.nameTemplates=new Map,this.tables=new Map,this.volatile=new Map,this.visibilityReaders=new Map,this.sheetReaders=new Map,this.styleReaders=new Map,this.wakePending=0,this.queue=new Int32Array(4096),this.qHead=0,this.qLen=0,this.sheetsByUid=new Map,this.running=!1,this.timer=0,this.manual=!1,this.graphReady=!0,this.pendingChanges=[],this.waiters=[],this.onChange=null,this.dataTables=[],this.tablesDirty=!1,this.inTables=!1,this.trial=null,this.tablesForced=!1,this.onProgress=null,this.lookupCache=new Map,this.colRevisions=new Map,this.channel=null,this.sheetsChanged()}orderChanged(){this.sheetsChanged(),this.has3D&&this.rebuild()}sheetsChanged(){this.sheetGen++,this.sheetMap.clear(),this.sheetsByUid.clear();for(const t of this.book.sheets)this.sheetMap.set(t.name.toUpperCase(),t),this.sheetsByUid.set(t.uid,t),t.rows.watcher=this,t.cols.watcher=this;this._wakeReaders(this.sheetReaders)}sheetByName(t){return this.sheetMap.get(t.toUpperCase())??null}externalSheet(t,e){return this.externalLinks?.sheet(t,e)??null}sheetsBetween(t,e){const{sheets:s}=this.book,n=s.findIndex(r=>r.name.toUpperCase()===t.toUpperCase()),i=s.findIndex(r=>r.name.toUpperCase()===e.toUpperCase());return n<0||i<0?null:s.slice(Math.min(n,i),Math.max(n,i)+1)}setNames(t){this.names.clear(),this.nameTemplates.clear();for(const e of t){const s=e.localSheetId!==void 0?`${e.localSheetId}!${e.name.toUpperCase()}`:e.name.toUpperCase();this.names.set(s,{text:e.text,name:e.name,hidden:e.hidden,comment:e.comment})}}setTables(t){this.tables.clear();for(const e of t)this.tables.set(e.name.toUpperCase(),e)}template(t,e,s){let n;try{n=tt(t)}catch(a){if(a instanceof K)return this._broken(t);throw a}const i=Ct(n,e,s);let r=this.templates.get(i);if(r===void 0){try{const a=new Z(n,e,s).parse();r=this._compile(a)}catch(a){if(!(a instanceof K))throw a;r=this._broken(t)}r.cacheKey=i,this.templates.set(i,r)}return r}_ownTemplate(t,e,s){const n=this.lastOwn;let i;return n.row===e-1&&n.col===s&&this.templates.get(n.tpl.cacheKey)===n.tpl&&Lt(n.text,t)?i=n.tpl:i=this.template(t,e,s),n.row=e,n.col=s,n.text=t,n.tpl=i,i}_compile(t,e=!1){const s=new ht(this,e);return{fn:s.compileTop(t),refs:s.refs,names:s.names,tables:s.tables,isVolatile:s.isVolatile,readsSheets:s.readsSheets,notInExcel:s.notInExcel===!0,mayArray:s.mayArray,rangeResult:ft(t),external:s.external,keepImportedResult:s.keepImportedResult}}_broken(){return{invalid:!0,fn:()=>g.NAME,refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1,external:!0}}validate(t){const e=At(t);if(e)throw new K(e);lt(new Z(tt(t),0,0).parse())}_templateFor(t,e,s,n){if(n.tpl!==void 0)return n.tpl;let i;return n.t==="dataTable"?i=this._dataTableTemplate():n.f!==void 0&&n.base===void 0?i=this._ownTemplate(n.f,e,s):n.f!==void 0?i=this.template(n.f,Math.floor(n.base/b),n.base%b):n.sf!==void 0?i=this.template(n.sf,Math.floor(n.base/b),n.base%b):i=this._broken(),n.tpl=i,i}_index(t){let e=this.deps.get(t);return e===void 0&&(e=new Vt,this.deps.set(t,e)),e}_addDep(t,e,s,n,i,r,a,l){const o=this._index(t),c=r.uid<<14|l;if(i-s>=Ut){o.all.push(a,c,e,n),o.allCols.push(s,i);return}if(n-e>=Nt){for(let m=s;m<=i;m++){let u=o.wide[m];u===void 0&&(u=new rt,o.wide[m]=u),u.push(a,c,e,n)}return}const f=e>>>T,h=n>>>T;for(let m=s;m<=i;m++){let u=o.buckets[m];u===void 0&&(u=[],o.buckets[m]=u);for(let y=f;y<=h;y++){let _=u[y];_===void 0&&(_=new rt,u[y]=_),_.push(a,c,e,n)}}}register(t,e,s,n){const i=this._templateFor(t,e,s,n);if(i.external||i.keepImportedResult&&!n.typed&&(t.kind(e,s)&S)!==D)return i;for(const r of i.refs)this._addRefDep(r,t,e,s);for(const r of i.names)this._addNameDeps(r,t,e,s);for(const r of i.tables)this._addTableDep(r,t,e,s);return i.readsSheets&&z(this.sheetReaders,t).add(e,s),i.isVolatile&&z(this.volatile,t).add(e,s),i.readsVisibility??=/SUBTOTAL|AGGREGATE|SPARK_/i.test(n.f??n.sf??""),i.readsVisibility&&z(this.visibilityReaders,t).add(e,s),i.readsStyles??=/SPARK_BLOCK/i.test(n.f??n.sf??""),i.readsStyles&&z(this.styleReaders,t).add(e,s),i}_addRefDep(t,e,s,n){const i=t.wrap?(t.rAbs0?t.r0:s+t.r0)%v:t.rAbs0?t.r0:s+t.r0,r=t.wrap?(t.rAbs1?t.r1:s+t.r1)%v:t.rAbs1?t.r1:s+t.r1,a=t.wrap?(t.cAbs0?t.c0:n+t.c0)%b:t.cAbs0?t.c0:n+t.c0,l=t.wrap?(t.cAbs1?t.c1:n+t.c1)%b:t.cAbs1?t.c1:n+t.c1,o=Math.max(0,Math.min(i,r)),c=Math.min(v-1,Math.max(i,r)),f=Math.max(0,Math.min(a,l)),h=Math.min(b-1,Math.max(a,l));if(o>c||f>h)return;if(t.sheet?.sheet2&&(t.sheet.book===null||t.sheet.book===void 0)){this.has3D=!0;for(const u of this.sheetsBetween(t.sheet.sheet,t.sheet.sheet2)??[])this._addDep(u,o,f,c,h,e,s,n);return}if(t.sheet?.book!==null&&t.sheet?.book!==void 0)return;const m=t.sheet?this.sheetByName(t.sheet.sheet):e;m&&this._addDep(m,o,f,c,h,e,s,n)}_addNameDeps(t,e,s,n){const i=this._nameTemplate(t,e);if(i!==null){i.readsSheets&&z(this.sheetReaders,e).add(s,n);for(const r of i.refs)this._addRefDep(r,e,s,n);for(const r of i.tables)this._addTableDep(r,e,s,n);for(const r of i.names)r.toUpperCase()!==t.toUpperCase()&&this._addNameDeps(r,e,s,n)}}_addTableDep(t,e,s,n){const i=this.resolveTable(t.name,t.spec,s,n,e);i instanceof V&&this._addDep(i.sheet,i.r0,i.c0,i.r1,i.c1,e,s,n)}rebuild(){this.has3D=!1,this.deps.clear(),this.volatile.clear(),this.visibilityReaders.clear(),this.styleReaders.clear(),this.sheetReaders.clear(),this.lookupCache.clear(),this.qHead=0,this.qLen=0,this.cycleFound=[],this.cycleMembers=null,this.sheetGen++,this.buildGraph({fullCalc:!0})}buildGraph({fullCalc:t=!1,onDone:e}={}){const s=this.buildGeneration=(this.buildGeneration??0)+1;this.running=!1,this.graphReady=!1,this.dataTables=[],t&&(this.tablesDirty=!0);const n=this,i=this.sheetGen,r=this.book.sheets.map(h=>[h,h.formulas]);let a=0,l=0,o=0,c=0;const f=()=>{if(n.buildGeneration!==s)return;const h=performance.now()+n.sliceMs;let m=0;for(;a<r.length;a++,l=0,o=0,c=0){const[y,_]=r[a],{columns:d}=_;for(;l<d.length;l++,o=0,c=0){const k=d[l];if(k!==void 0)for(;o<k.length;o++,c=0){const M=k[o];if(M===void 0)continue;const{ids:E}=M,R=o<<T;for(;c<=x;c++){const q=E[c];if(q===0)continue;const F=_.infos[q],et=R+c;F.t==="dataTable"&&n.dataTables.push({sheet:y,row:et,col:l,info:F});const gt=n.register(y,et,l,F);if(n._initFormula(y,et,l,F,gt,t),++m%256===0&&performance.now()>h){c++,n.onProgress?.({preparing:!0}),n.buildGeneration===s&&n._later(f);return}}}}}n.graphReady=!0,n.sheetGen!==i&&n._wakeReaders(n.sheetReaders);const u=n.pendingChanges;n.pendingChanges=[];for(const[y,_,d,k]of u)n.cellsChanged(y,_,d,k);n._schedule(),e?.()};f()}_initFormula(t,e,s,n,i,r){const a=t._chunk(e,s);if(a===void 0)return;const l=e&x;n.t==="array"&&n.ref&&this._markArrayChildren(t,e,s,n);const o=a.kinds[l];if(i.external||i.keepImportedResult&&!n.typed&&(o&S)!==D)return;const c=n.ca==="1"||n.ca==="true";(r||c||i.isVolatile||(o&S)===D||i.notInExcel&&(o&S)===I)&&(a.kinds[l]=o|w,this._enqueue(t,e,s))}_markArrayChildren(t,e,s,n){const i=P(n.ref);if(i!==null){t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...i,blocked:!1,fixed:!n.cm});for(let r=i.r0;r<=i.r1;r++)for(let a=i.c0;a<=i.c1;a++){if(r===e&&a===s)continue;const l=t._ensure(r,a);l.kinds[r&x]|=j}}}_enqueue(t,e,s){if(this.qLen+3>this.queue.length)if(this.qHead>this.queue.length>>>1)this.queue.copyWithin(0,this.qHead,this.qLen),this.qLen-=this.qHead,this.qHead=0;else{const n=new Int32Array(this.queue.length*2);n.set(this.queue),this.queue=n}this.queue[this.qLen++]=t.uid,this.queue[this.qLen++]=e,this.queue[this.qLen++]=s}_dirtyFrom(t,e,s,n,i){const r=[t,e,s,n,i];for(;r.length>0;){const a=r.pop(),l=r.pop(),o=r.pop(),c=r.pop(),f=r.pop(),h=this.deps.get(f);if(h===void 0)continue;const m=(_,d)=>{const k=this.sheetsByUid.get(d>>>14);if(k===void 0)return;const M=d&16383,E=k._chunk(_,M);if(E===void 0)return;const R=_&x,q=E.kinds[R];(q&L)===0||(q&w)!==0||(E.kinds[R]=q|w,this._enqueue(k,_,M),r.push(k,M,M,_,_))},u=l>>>T,y=a>>>T;for(let _=c;_<=o;_++){const d=h.buckets[_];if(d!==void 0)for(let M=u;M<=y;M++){const E=d[M];if(E===void 0)continue;const{data:R}=E,q=E.n*G;for(let F=0;F<q;F+=G)a>=R[F+2]&&l<=R[F+3]&&m(R[F],R[F+1])}const k=h.wide[_];if(k!==void 0){const{data:M}=k,E=k.n*G;for(let R=0;R<E;R+=G)a>=M[R+2]&&l<=M[R+3]&&m(M[R],M[R+1])}}if(h.all.n>0){const{data:_}=h.all;for(let d=0;d<h.all.n;d++){const k=d*G;a>=_[k+2]&&l<=_[k+3]&&o>=h.allCols[d*2]&&c<=h.allCols[d*2+1]&&m(_[k],_[k+1])}}}}cellsChanged(t,e,s,n){if(n===0)return;if(t.valueListeners)for(const r of t.valueListeners)for(let a=0;a<n;a++)r(e[a],s[a],e[a],s[a]);if(this.inTables||(this.tablesDirty=!0),!this.graphReady){this.pendingChanges.push([t,e.slice(0,n),s.slice(0,n),n]);return}this.lookupCache.clear();const i=new Map;for(let r=0;r<n;r++){const a=e[r],l=s[r],o=i.get(l);o===void 0?i.set(l,[a,a]):(a<o[0]&&(o[0]=a),a>o[1]&&(o[1]=a));const c=t._chunk(a,l);if(c===void 0)continue;const f=a&x,h=c.kinds[f];if(h&L){const m=t.formula(a,l);m&&(this.register(t,a,l,m),h&w||(c.kinds[f]=h|w,this._enqueue(t,a,l)))}t.spills&&this._spillTouched(t,a,l)}for(const[r,a]of i)this._dirtyFrom(t,r,r,a[0],a[1]);this._markVolatile(),this._schedule()}_spillTouched(t,e,s){const n=e*b+s;for(const[i,r]of t.spills){const a=Math.floor(i/b),l=i-a*b;if(i===n){(t.kind(a,l)&L)===0&&(this._clearSpill(t,r,a,l),t.spills.delete(i));continue}if(e>=r.r0&&e<=r.r1&&s>=r.c0&&s<=r.c1){const o=t._chunk(a,l);if(o===void 0)continue;const c=a&x,f=o.kinds[c];f&L&&!(f&w)&&(o.kinds[c]=f|w,this._enqueue(t,a,l),this._dirtyFrom(t,l,l,a,a))}}}_markVolatile(){for(const[t,e]of this.volatile)e.forEach((s,n)=>{const i=t._chunk(s,n);if(i===void 0)return;const r=s&x,a=i.kinds[r];if(!(a&L)){e.delete(s,n);return}a&w||(i.kinds[r]=a|w,this._enqueue(t,s,n),this._dirtyFrom(t,n,n,s,s))})}get pending(){return(this.qLen-this.qHead)/3}_later(t){if(this._next=t,typeof MessageChannel>"u"){setTimeout(()=>this._tick(),0);return}this.channel===null&&(this.channel=new MessageChannel,this.channel.port1.onmessage=()=>this._tick()),this.channel.port2.postMessage(0)}_tick(){const t=this._next;this._next=null,t?.(),this._next===null&&this.channel!==null&&(this.channel.port1.close(),this.channel=null)}_schedule(){if(this.manual&&!this.tablesForced||this.inTables||this.running||!this.graphReady)return;if(this.pending===0){this._finish();return}const t=this.pending,e=this.buildGeneration;if(t<=this.syncLimit){if(this._slice(this.syncLimit===1/0?1/0:this.sliceMs),this.buildGeneration!==e)return;if(this.pending===0){this._finish();return}}this.running=!0,this._total=t;const s=()=>{this.buildGeneration===e&&(this._slice(this.sliceMs),this.buildGeneration===e&&(this.pending>0?(this.onProgress?.({remaining:this.pending,total:Math.max(this._total,this.pending)}),this.buildGeneration===e&&this._later(s)):(this.running=!1,this._finish())))};this._later(s)}_slice(t){const e=t!==1/0;let s=e?performance.now():0;const n=s+t;let i=1,r=1;for(;this.qHead<this.qLen;){const a=this.queue[this.qHead++],l=this.queue[this.qHead++],o=this.queue[this.qHead++],c=this.sheetsByUid.get(a);if(c!==void 0&&(this._run(c,l,o),e&&--r===0)){const f=performance.now();if(f>n)break;i=f-s<.5?Math.min(i*2,16):1,r=i,s=f}}this.qHead>=this.qLen&&(this.qHead=0,this.qLen=0)}_finish(){for(;this.cycleFound.length>0;)this._iterateCycles();const t=this.tablesForced;this.tablesForced=!1,this.tablesDirty&&this.dataTables.length>0&&(!this.skipTables||t)&&(this.tablesDirty=!1,this._computeDataTables()),this.book.formatValueRevision=(this.book.formatValueRevision??0)+1,this.onChange?.();const e=this.waiters;this.waiters=[];for(const s of e)s()}_dataTableTemplate(){const t=this;return{fn:(s,n,i)=>t._plainValue(i,s,n),refs:[],names:[],tables:[],isVolatile:!1,mayArray:!1}}_plainValue(t,e,s){const n=t.value(e,s);switch(t.kind(e,s)&S){case U:return n;case B:return this.book.strings.get(n);case W:return n!==0;case I:return J[n];default:return null}}_writePlain(t,e,s,n){const i=t.kind(e,s)&L;n==null?t.setCell(e,s,i|U,0):typeof n=="number"?Number.isFinite(n)?t.setCell(e,s,i|U,n):t.setCell(e,s,i|I,g.NUM.index):typeof n=="boolean"?t.setCell(e,s,i|W,n?1:0):n instanceof C?t.setCell(e,s,i|I,n.index):t.setCell(e,s,i|B,this.book.strings.add(String(n)))}_setInputs(t,e){const s=new Uint32Array(e.length),n=new Uint32Array(e.length);e.forEach((i,r)=>{t.setCell(i.row,i.col,i.kind,i.value),s[r]=i.row,n[r]=i.col}),this.cellsChanged(t,s,n,e.length),this._slice(1/0)}evaluateWith(t,e,s){const n=e.map(({row:a,col:l})=>({row:a,col:l,kind:t.kind(a,l)&(S|L),value:t.value(a,l)})),i=this.inTables,r=this.trial;this.inTables=!0,this.trial??=new Map;try{return this._setInputs(t,e.map(({row:a,col:l,text:o})=>{const c=Number(o);return o!==""&&Number.isFinite(c)?{row:a,col:l,kind:U,value:c}:{row:a,col:l,kind:B,value:this.book.strings.add(String(o))}})),s()}finally{this._setInputs(t,n),this.inTables=i,this.trial=r}}_computeDataTables(){this.inTables=!0;const t=this.dataTables.filter(e=>e.sheet.formula(e.row,e.col)===e.info&&this.book.sheets.includes(e.sheet));this.dataTables=t;try{for(const e of t)this._computeDataTable(e)}finally{this.inTables=!1}}_computeDataTable({sheet:t,info:e}){const s=P(e.ref);if(!s)return;const n=P(e.r1??""),i=e.r2?P(e.r2):null,r=e.dt2D==="1"||e.dt2D==="true",a=e.dtr==="1"||e.dtr==="true",l=e.del1==="1"||e.del1==="true"||r&&(e.del2==="1"||e.del2==="true");if(!l&&(!n||r&&!i))return;const o=(d,k)=>({kind:t.kind(d,k)&S,value:t.value(d,k)}),f=(l?[]:[n,i].filter(Boolean)).map(d=>({row:d.r0,col:d.c0,kind:t.kind(d.r0,d.c0)&(S|L),value:t.value(d.r0,d.c0)})),h=[];this.trial=new Map;const m=(d,k,M,E)=>{const R=this.read(t,M,E);h.push(d,k,R instanceof A?R.data[0]:R)};try{if(l)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)h.push(d,k,g.REF);else if(r)for(let d=s.r0;d<=s.r1;d++)for(let k=s.c0;k<=s.c1;k++)this._setInputs(t,[{row:n.r0,col:n.c0,...o(s.r0-1,k)},{row:i.r0,col:i.c0,...o(d,s.c0-1)}]),m(d,k,s.r0-1,s.c0-1);else if(a)for(let d=s.c0;d<=s.c1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...o(s.r0-1,d)}]);for(let k=s.r0;k<=s.r1;k++)m(k,d,k,s.c0-1)}else for(let d=s.r0;d<=s.r1;d++){this._setInputs(t,[{row:n.r0,col:n.c0,...o(d,s.c0-1)}]);for(let k=s.c0;k<=s.c1;k++)m(d,k,s.r0-1,k)}}finally{f.length>0&&this._setInputs(t,f),this.trial=null}const u=h.length/3,y=new Uint32Array(u),_=new Uint32Array(u);for(let d=0;d<u;d++)y[d]=h[d*3],_[d]=h[d*3+1],this._writePlain(t,y[d],_[d],h[d*3+2]);this.cellsChanged(t,y,_,u),this._slice(1/0),t.revision++}dataTableAt(t,e,s){for(const n of this.dataTables){if(n.sheet!==t)continue;const i=P(n.info.ref);if(i&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1)return n}return null}calculateNow(){const{manual:t,skipTables:e}=this;this.manual=!1,this.skipTables=!1,this.tablesDirty=!0,this.tablesForced=!0,this._markVolatile(),this._markCycles(),this._schedule(),this.manual=t,this.skipTables=e}whenIdle(){return this.pending===0&&this.graphReady&&!this.running?Promise.resolve():new Promise(t=>{this.waiters.push(t),this._schedule()})}_iterateCycles(){const t=this.cycleFound;this.cycleFound=[];const e=new Map,s=(a,l,o)=>{let c=e.get(a.uid);c===void 0&&(c=new Map,e.set(a.uid,c)),c.set(l*b+o,[a,l,o])};for(let a=0;a<t.length;a+=3)s(t[a],t[a+1],t[a+2]);const n=[];for(const a of this.book.sheets){const l=e.get(a.uid);l&&n.push(...[...l.keys()].sort((o,c)=>o-c).map(o=>l.get(o)))}this.cycleMembers??=new Map;for(const a of n)this.cycleMembers.set(`${a[0].uid}:${a[1]}:${a[2]}`,a);const{count:i,delta:r}=this.iterate;for(let a=1;a<=i;a++){let l=0;for(const[o,c,f]of n){const h=o._chunk(c,f);if(h===void 0)continue;const m=c&x;if(!(h.kinds[m]&L))continue;const u=h.values[m];h.kinds[m]|=w,this.iterating=!0,this._run(o,c,f),this.iterating=!1;const y=Math.abs(h.values[m]-u);y>l&&(l=y)}if(this.onProgress?.({iteration:a,iterations:i}),l<r)break}for(const[a,l,o]of n)this._dirtyFrom(a,o,o,l,l);for(const[a,l,o]of n){const c=a._chunk(l,o);c!==void 0&&(c.kinds[l&x]&=~w)}this._slice(1/0)}_markCycles(){if(!(this.iterate===null||this.cycleMembers===null))for(const[t,e,s]of this.cycleMembers.values()){const n=t._chunk(e,s);n===void 0||!(n.kinds[e&x]&L)||(n.kinds[e&x]|=w,this._enqueue(t,e,s))}}_run(t,e,s){const n=[t,e,s];for(;n.length>0;){const i=n[n.length-1],r=n[n.length-2],a=n[n.length-3];try{this.depth=0,this.evalTop=0,this.cycleLow=it,this._calc(a,r,i),n.length-=3}catch(l){if(l!==nt)throw l;n.push(this.pendingSheet,this.pendingRow,this.pendingCol)}}}_calc(t,e,s){const n=t._chunk(e,s);if(n===void 0)return;const i=e&x,r=n.kinds[i];if(!(r&w))return;if(r&Y){this.circular={sheet:t,row:e,col:s},this.iterating||this._cycleHit(t.uid,e,s);return}if(this.depth>=dt)throw this.pendingSheet=t,this.pendingRow=e,this.pendingCol=s,nt;const a=t.formula(e,s);if(a===void 0||!(r&L)){n.kinds[i]=r&~w;return}const l=this._templateFor(t,e,s,a);if(l.external||l.keepImportedResult&&!a.typed&&(r&S)!==D){n.kinds[i]=r&~w;return}n.kinds[i]=r|Y;const o=this.evalTop;o+3>this.evalStack.length&&this._growEvalStack(),this.evalStack[o]=t.uid,this.evalStack[o+1]=e,this.evalStack[o+2]=s,this.evalTop=o+3;const c=this.cycleLow;this.cycleLow=it;const f=this.legacy,h=this.frame,m=a.typed!==!0&&a.t!=="array";this.legacy=m,this.depth++;let u;try{u=l.fn(e,s,t),(u instanceof V||u instanceof O)&&(u=this.refAuto(u,e,s)),u instanceof st&&(u=this.toArr(u))}catch(_){if(n.kinds[i]&=~Y,this.depth--,this.legacy=f,this.frame=h,this.evalTop=o,this.cycleLow=c,_===nt)throw _;_ instanceof C?u=_:(console.error("Formula evaluation failed",_),u=g.VALUE),this._store(t,n,i,e,s,u,a,m);return}this.depth--,this.legacy=f,this.frame=h,this.evalTop=o;const y=this.cycleLow;if(this.cycleLow=y<o&&y<c?y:c,y<=o){if(this.iterate!==null){n.kinds[i]=r&~(w|Y),this.cycleFound.push(t,e,s);return}if((r&S)!==D&&this._keepsInCycle(t,e,s,a)){n.kinds[i]=r&~(w|Y),this._dropTrialValue(t,n,i,e,s);return}u=0}this._store(t,n,i,e,s,u,a,m)}_keepsInCycle(t,e,s,n){return n.typed===void 0?!0:this.book.collab===void 0&&!t.spills?.has(e*b+s)}_dropTrialValue(t,e,s,n,i){const r=this.trial?.get(t)?.get(n*b+i);if(!(r===void 0||!((e.kinds[s]&X)!==r[0]||e.values[s]!==r[1]))&&(e.kinds[s]=r[0],e.values[s]=r[1],t.valueListeners))for(const l of t.valueListeners)l(n,i,n,i)}_saveTrialValue(t,e,s,n,i){let r=this.trial.get(t);r===void 0&&(r=new Map,this.trial.set(t,r));const a=n*b+i;if(r.has(a))return;const l=e.kinds[s]&X;r.set(a,(l&S)===D?[L|U,0]:[l,e.values[s]])}_cycleHit(t,e,s){const n=this.evalStack;for(let i=this.evalTop-3;i>=0;i-=3)if(n[i]===t&&n[i+1]===e&&n[i+2]===s){i<this.cycleLow&&(this.cycleLow=i);return}}_growEvalStack(){const t=new Int32Array(this.evalStack.length*2);t.set(this.evalStack),this.evalStack=t}_store(t,e,s,n,i,r,a,l){let o=r;o instanceof wt&&(o=g.CALC),o instanceof A?a.t==="array"&&!a.cm&&a.ref?o=this._fillFixedArray(t,n,i,a,o):l||o.spillRows===1&&o.spillCols===1?(o=o.data[0],t.spills&&this._releaseSpill(t,n,i)):o=this._spill(t,n,i,a,o):t.spills&&!(a.t==="array"&&!a.cm)&&this._releaseSpill(t,n,i),a.t==="array"&&!a.cm&&a.ref&&!(r instanceof A)&&(o=this._fillFixedArray(t,n,i,a,A.filled(1,1,o)));let c=L,f=0;if(typeof o=="number"?Number.isFinite(o)?(c|=U,f=o):(c|=I,f=g.NUM.index):typeof o=="string"?(c|=B,f=this.book.strings.add(o)):typeof o=="boolean"?(c|=W,f=o?1:0):o instanceof C?(c|=I,f=o.index):o instanceof H?(c|=I,f=g.VALUE.index):c|=U,o instanceof H?pt(t,n*b+i,ct(this.book,o.index)):t.valueMeta!==null&&((e.kinds[s]&X)!==c||e.values[s]!==f)&&!/IMAGE\(/i.test(a.f??a.sf??"")&&Ft(t,n*b+i),t.valueListeners&&((e.kinds[s]&X)!==c||e.values[s]!==f))for(const h of t.valueListeners)h(n,i,n,i);this.trial!==null&&this.iterate===null&&this._saveTrialValue(t,e,s,n,i),e.kinds[s]=c,e.values[s]=f,n>t.maxRow&&(t.maxRow=n),i>t.maxCol&&(t.maxCol=i)}_writeArrayCell(t,e,s,n){let i=j,r=0;typeof n=="number"?(i|=Number.isFinite(n)?U:I,r=Number.isFinite(n)?n:g.NUM.index):typeof n=="string"?(i|=B,r=this.book.strings.add(n)):typeof n=="boolean"?(i|=W,r=n?1:0):n instanceof C?(i|=I,r=n.index):n==null?i|=U:(i|=I,r=g.VALUE.index,n instanceof H&&pt(t,e*b+s,ct(this.book,n.index))),t.setCell(e,s,i,r)}_fillFixedArray(t,e,s,n,i){const r=P(n.ref);if(r===null)return i.data[0];t.spills||(t.spills=new Map),t.spills.set(e*b+s,{...r,blocked:!1,fixed:!0});const a=(o,c)=>{const f=i.rows===1?0:o,h=i.cols===1?0:c;return f>=i.rows||h>=i.cols?g.NA:i.get(f,h)};for(let o=r.r0;o<=r.r1;o++)for(let c=r.c0;c<=r.c1;c++)o===e&&c===s||this._writeArrayCell(t,o,c,a(o-r.r0,c-r.c0));(r.r0!==r.r1||r.c0!==r.c1)&&this._dirtyFrom(t,r.c0,r.c1,r.r0,r.r1);const l=a(e-r.r0,s-r.c0);return l===null?0:l}_spill(t,e,s,n,i){const r=e*b+s;t.spills||(t.spills=new Map);const a=t.spills.get(r),l=e+i.rows-1,o=s+i.cols-1,c={r0:e,c0:s,r1:l,c1:o,blocked:!1,fixed:!1},f=(u,y)=>a&&u>=a.r0&&u<=a.r1&&y>=a.c0&&y<=a.c1;let h=e+i.spillRows>v||s+i.spillCols>b;if(!h)t:for(let u=e;u<=l;u++)for(let y=s;y<=o;y++){if(u===e&&y===s)continue;const _=t.kind(u,y);if((_&X)!==0&&!(_&j&&f(u,y))){h=!0;break t}if(t.merges.length>0&&t.mergeAt(u,y)){h=!0;break t}}if(h)return a&&!a.blocked&&this._clearSpill(t,a,e,s),c.blocked=!0,c.r1=Math.min(l,v-1),c.c1=Math.min(o,b-1),t.spills.set(r,c),g.SPILL;if(a&&!a.blocked){for(let u=a.r0;u<=a.r1;u++)for(let y=a.c0;y<=a.c1;y++)u>=c.r0&&u<=c.r1&&y>=c.c0&&y<=c.c1||(t.kind(u,y)&j)!==0&&t.setCell(u,y,D,0);this._dirtyFrom(t,a.c0,a.c1,a.r0,a.r1)}t.spills.set(r,c);for(let u=e;u<=l;u++)for(let y=s;y<=o;y++)u===e&&y===s||this._writeArrayCell(t,u,y,i.get(u-e,y-s));n.t="array",n.ref=`${mt(s)}${e+1}:${mt(o)}${l+1}`,n.cm=1,delete n.raw,this._dirtyFrom(t,s,o,e,l);const m=i.data[0];return m===null?0:m}_clearSpill(t,e,s,n){for(let i=e.r0;i<=e.r1;i++)for(let r=e.c0;r<=e.c1;r++)i===s&&r===n||(t.kind(i,r)&j)!==0&&t.setCell(i,r,D,0);this._dirtyFrom(t,e.c0,e.c1,e.r0,e.r1)}_releaseSpill(t,e,s){const n=e*b+s,i=t.spills.get(n);if(i===void 0)return;i.blocked||this._clearSpill(t,i,e,s),t.spills.delete(n);const r=t.formula(e,s);r&&r.typed&&(delete r.ref,delete r.cm,delete r.t)}spillMaster(t,e,s){if(!t.spills)return null;for(const[n,i]of t.spills)if(!i.blocked&&e>=i.r0&&e<=i.r1&&s>=i.c0&&s<=i.c1){const r=Math.floor(n/b);return{row:r,col:n-r*b,rect:i}}return null}spillRange(t){const{sheet:e,r0:s,c0:n}=t;this.read(e,s,n);const i=e.spills?.get(s*b+n);return!i||i.blocked?g.REF:new V(e,i.r0,i.c0,i.r1,i.c1)}read(t,e,s){const n=t.columns[s];if(n===void 0)return null;const i=n[e>>>T];if(i===void 0)return null;const r=e&x;let a=i.kinds[r];if(a===0)return null;switch(a&w&&(this._calc(t,e,s),a=i.kinds[r]),a&S){case U:return i.values[r];case B:return this.book.strings.get(i.values[r]);case W:return i.values[r]!==0;case I:{if(t.valueMeta!==null&&this.book.richValues){const l=Rt(this.book,t,e,s);if(l!==null)return l}return J[i.values[r]]??g.NA}default:return null}}refToValue(t){return t instanceof O?t.refs.length===1?this.refToValue(t.refs[0]):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.toArr(t)}refAuto(t,e,s){return t instanceof O?t.refs.length===1?this.refAuto(t.refs[0],e,s):g.VALUE:t.isCell?this.read(t.sheet,t.r0,t.c0):this.legacy?this.intersect(t,e,s):this.toArr(t)}intersect(t,e,s){return t.cols===1&&e>=t.r0&&e<=t.r1?this.read(t.sheet,e,t.c0):t.rows===1&&s>=t.c0&&s<=t.c1?this.read(t.sheet,t.r0,s):g.VALUE}trim(t){const{sheet:e}=t;return{r0:t.r0,c0:t.c0,r1:Math.min(t.r1,Math.max(e.maxRow,t.r0)),c1:Math.min(t.c1,Math.max(e.maxCol,t.c0))}}toArr(t){if(t instanceof st)return new A(t.rows,t.cols,t.data.map(e=>e instanceof V?this.read(e.sheet,e.r0,e.c0):e));if(t instanceof A)return t;if(t instanceof V){const e=t.rows===v||t.cols===b,{r0:s,c0:n,r1:i,c1:r}=e||t.rows*t.cols>It?this.trim(t):t,a=i-s+1,l=r-n+1,o=new Array(a*l);let c=0;for(let f=s;f<=i;f++)for(let h=n;h<=r;h++)o[c++]=this.read(t.sheet,f,h);return new A(a,l,o,t.rows===v?v:a,t.cols===b?b:l)}if(t instanceof O){if(t.refs.length===1)return this.toArr(t.refs[0]);throw g.VALUE}if(t instanceof C)throw t;return new A(1,1,[t])}scalar(t,e,s){return t instanceof V?t.isCell?this.read(t.sheet,t.r0,t.c0):this.intersect(t,e,s):t instanceof O?g.VALUE:t instanceof st?this.scalar(t.data[0],e,s):t instanceof A?t.data[0]:t}scan(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);for(let r=t.c0;r<=n;r++){const a=s.columns[r];if(a!==void 0)for(let l=t.r0>>>T;l<=i>>>T;l++){const o=a[l];if(o===void 0)continue;const c=l<<T,f=Math.max(t.r0-c,0),h=Math.min(i-c,x),{kinds:m}=o;for(let u=f;u<=h;u++){if(m[u]===0)continue;const y=this.read(s,c+u,r);y!==null&&e(y,c+u,r)}}}}sumRange(t,e){const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow);let{sum:r,count:a}=e;for(let l=t.c0;l<=n;l++){const o=s.columns[l];if(o!==void 0)for(let c=t.r0>>>T;c<=i>>>T;c++){const f=o[c];if(f===void 0)continue;const h=c<<T,m=Math.max(t.r0-h,0),u=Math.min(i-h,x),{kinds:y,values:_}=f;for(let d=m;d<=u;d++){let k=y[d];if(k===0)continue;k&w&&(this._calc(s,h+d,l),k=y[d]);const M=k&S;if(M===U)r+=_[d],a++;else if(M===I)throw J[_[d]]}}}e.sum=r,e.count=a}averageRange(t,e){if(t.cols===1)return this.sumRange(t,e);const{sheet:s}=t,n=Math.min(t.c1,s.maxCol),i=Math.min(t.r1,s.maxRow),r=[],a=[];for(let l=t.r0>>>T;l<=i>>>T;l++){r.length=0,a.length=0;for(let h=t.c0;h<=n;h++){const m=s.columns[h]?.[l];m!==void 0&&(r.push(h),a.push(m))}if(a.length===0)continue;const o=l<<T,c=Math.max(t.r0-o,0),f=Math.min(i-o,x);for(let h=c;h<=f;h++)for(let m=0;m<a.length;m++){const{kinds:u,values:y}=a[m];u[h]&w&&this._calc(s,o+h,r[m]);const _=u[h]&S;if(_===U)e.sum+=y[h],e.count++;else if(_===I)throw J[y[h]]}}}unary(t,e){if(t instanceof C)return t;if(t instanceof A)return new A(t.rows,t.cols,t.data.map(s=>{try{return s instanceof C?s:e(N(s))}catch(n){return n}}),t.spillRows,t.spillCols);try{return e(N(t))}catch(s){if(s instanceof C)return s;throw s}}slowBin(t,e,s){if(e instanceof A||s instanceof A)return this._binArr(t,e,s);if(e instanceof C)return e;if(s instanceof C)return s;try{return yt(t,e,s)}catch(n){if(n instanceof C)return n;throw n}}_binArr(t,e,s){const n=e instanceof A?e:null,i=s instanceof A?s:null,r=Math.max(n?n.rows:1,i?i.rows:1),a=Math.max(n?n.cols:1,i?i.cols:1),l=new Array(r*a);for(let o=0;o<r;o++)for(let c=0;c<a;c++){const f=at(e,o,c),h=at(s,o,c);let m;if(f instanceof C)m=f;else if(h instanceof C)m=h;else try{m=yt(t,f,h)}catch(u){m=u}l[o*a+c]=m}return new A(r,a,l,Math.max(n?.spillRows??1,i?.spillRows??1),Math.max(n?.spillCols??1,i?.spillCols??1))}liftArr(t,e,s){let n=1,i=1,r=1,a=1;for(const f of e)f instanceof A&&(f.rows>n&&(n=f.rows),f.cols>i&&(i=f.cols),f.spillRows>r&&(r=f.spillRows),f.spillCols>a&&(a=f.spillCols));const l=new Array(n*i),o=e.length,c=new Array(o);for(let f=0;f<n;f++)for(let h=0;h<i;h++){let m=null;for(let u=0;u<o;u++){const y=at(e[u],f,h);c[u]=y,!s&&m===null&&y instanceof C&&(m=y)}if(m!==null){l[f*i+h]=m;continue}try{l[f*i+h]=t(...c)}catch(u){if(u instanceof C)l[f*i+h]=u;else throw u}}return new A(n,i,l,r,a)}invoke(t,e,s,n,i){if(t.native)return this._invokeNative(t.native,e,s,n,i);const r=t.frame?t.frame.slice():[],{params:a}=t;if(e.length>a.length)return g.VALUE;for(let o=0;o<a.length;o++)r[a[o]]=o<e.length?e[o]:void 0;const l=this.frame;if(this.frame=r,this.depth++,this.depth>=dt*4)return this.depth--,this.frame=l,g.NUM;try{return t.body(s,n,i)}finally{this.depth--,this.frame=l}}_invokeNative(t,e,s,n,i){if(e.length<t.min||e.length>t.max)return g.VALUE;try{if(t.kind==="raw")return t.fn(this,e,s,n,i);if(t.kind==="lazy")return t.fn(this,e.map(l=>()=>l),s,n,i);const r=t.dateSystem?(...l)=>t.fn(this.book.dateOffset,...l):t.fn,a=e.map(l=>l instanceof V||l instanceof O?this.refToValue(l):l);if(a.some(l=>l instanceof A))return this.liftArr(r,a,t.errors);if(!t.errors){for(const l of a)if(l instanceof C)return l}return r(...a)}catch(r){if(r instanceof C)return r;throw r}}_nameEntry(t,e){const s=t.toUpperCase();if(e){const i=this.book.sheets.indexOf(e),r=this.names.get(`${i}!${s}`);if(r)return{key:`${i}!${s}`,entry:r}}const n=this.names.get(s);return n?{key:s,entry:n}:null}_nameTemplate(t,e){const s=this._nameEntry(t,e);if(s===null)return null;let n=this.nameTemplates.get(s.key);if(n===void 0){try{n=this._compile(new Z(tt(s.entry.text,!0),0,0).parse(!0),!0)}catch(i){if(!(i instanceof K))throw i;n=this._broken()}this.nameTemplates.set(s.key,n)}return n}nameMayYieldRange(t){const e=t.toUpperCase(),s=[];for(const[n,i]of this.names)(n===e||n.endsWith(`!${e}`))&&s.push(i);if(s.length===0||(this._rangeNames??=new Set,this._rangeNames.has(e)))return!0;this._rangeNames.add(e);try{return s.some(n=>{try{return new ht(this).mayYieldRange(new Z(tt(n.text,!0),0,0).parse(!0))}catch(i){if(i instanceof K)return!1;throw i}})}finally{this._rangeNames.delete(e)}}evalName(t,e,s,n){const i=this._nameTemplate(t,n);return i===null?g.NAME:i.fn(e,s,n)}tableSpecToA1(t,e,s){const n=_t(t,e,s);if(!(n instanceof V))return null;const i=/#This Row|^\[\s*@/i.test(e),r=(a,l)=>i?`${ut(l)}${a+1}`:`$${ut(l)}$${a+1}`;return n.isCell?r(n.r0,n.c0):`${r(n.r0,n.c0)}:${r(n.r1,n.c1)}`}resolveTable(t,e,s,n,i){let r=t?this.tables.get(t.toUpperCase()):null;if(!t){for(const a of this.tables.values())if(a.sheet===i&&s>=a.r0&&s<=a.r1&&n>=a.c0&&n<=a.c1){r=a;break}}return r?_t(r,e,s):g.REF}exactIndex(t){const e=`${t.sheet.uid}:${t.r0}:${t.c0}:${t.r1}:${t.c1}`;let s=this.lookupCache.get(e);if(s!==void 0)return s;s=new Map;const n=t.cols===1;return this.scan(t,(i,r,a)=>{const l=typeof i=="string"?`s${i.toLowerCase()}`:typeof i=="number"?i:`b${i}`;if(i instanceof C)return;const o=n?r-t.r0:a-t.c0,c=s.get(l);(c===void 0||o<c)&&s.set(l,o)}),this.lookupCache.set(e,s),s}visibilityChanged(){this._wakeReaders(this.visibilityReaders)}presentationChanged(){this._wakeLater(2)}axisHiddenChanged(){this._wakeLater(1)}axisResized(){this._wakeLater(2)}_wakeLater(t){(t===1?this.visibilityReaders:this.styleReaders).size!==0&&(this.wakePending===0&&queueMicrotask(()=>{const e=this.wakePending;this.wakePending=0,e&1&&this._wakeReaders(this.visibilityReaders),e&2&&this._wakeReaders(this.styleReaders)}),this.wakePending|=t)}_wakeReaders(t){if(!this.graphReady||t.size===0)return;let e=!1;for(const[s,n]of t)n.forEach((i,r)=>{const a=s._chunk(i,r);if(a===void 0)return;const l=i&x,o=a.kinds[l];if(!(o&L)){n.delete(i,r);return}o&w||(a.kinds[l]=o|w,this._enqueue(s,i,r)),this._dirtyFrom(s,r,r,i,i),e=!0});e&&this._schedule()}isSubtotalCell(t,e,s){if((t.kind(e,s)&L)===0)return!1;const n=t.formula(e,s),i=n?.f??n?.sf??"";return/^\s*(_xlfn\.)?(SUBTOTAL|AGGREGATE)\(/i.test(i)}displayFormula(t){return xt(t)}}function mt(p){let t="";for(let e=p+1;e>0;e=Math.floor((e-1)/26))t=String.fromCharCode(65+(e-1)%26)+t;return t}function at(p,t,e){if(!(p instanceof A))return p;const s=p.rows===1?0:t,n=p.cols===1?0:e;return s>=p.rows||n>=p.cols?g.NA:p.data[s*p.cols+n]}function yt(p,t,e){if((t instanceof H||e instanceof H)&&p!=="="&&p!=="<>"&&p!=="&")throw g.VALUE;switch(p){case"+":{const s=N(t),n=s+N(e);return Math.abs(n)<Math.abs(s)*kt?0:Q(n)}case"-":{const s=N(t),n=s-N(e);return Math.abs(n)<Math.abs(s)*kt?0:Q(n)}case"*":return Q(N(t)*N(e));case"/":{const s=N(t),n=N(e);if(n===0)throw g.DIV0;return Q(s/n)}case"^":{const s=N(t),n=N(e);if(s===0&&n===0)throw g.NUM;if(s===0&&n<0)throw g.DIV0;const i=Mt(s,n);if(Number.isNaN(i))throw g.NUM;return Q(i)}case"&":return ot(t)+ot(e);case"=":return $(t,e)===0;case"<>":return $(t,e)!==0;case"<":return $(t,e)<0;case">":return $(t,e)>0;case"<=":return $(t,e)<=0;case">=":return $(t,e)>=0;default:throw g.VALUE}}const kt=5e-16;function Q(p){if(!Number.isFinite(p))throw g.NUM;return p}function _t(p,t,e){const s=bt(p,t,e);return s==="REF"?g.REF:s==="VALUE"?g.VALUE:new V(p.sheet,s.top,s.left,s.bottom,s.right)}const qt={COUNTIF:[0],COUNTIFS:["even",0],SUMIF:[0,2],SUMIFS:[0,"odd",1],AVERAGEIF:[0,2],AVERAGEIFS:[0,"odd",1],MAXIFS:[0,"odd",1],MINIFS:[0,"odd",1],COUNTBLANK:[0],RANK:[1],"RANK.EQ":[1],"RANK.AVG":[1]};function Dt(p,t){for(let e=0;e<p.length;e++){const s=p[e];if(s===t||s==="odd"&&t>=p[e+1]&&t%2===1||s==="even"&&t>=p[e+1]&&t%2===0)return!0}return!1}function lt(p){if(!(p===null||typeof p!="object")){if(Array.isArray(p)){for(const t of p)lt(t);return}if(p.t==="call"){const t=qt[String(p.name).replace(/^_xl(?:fn|ws)\./i,"").toUpperCase()];t&&p.args.forEach((e,s)=>{if(e?.t==="array"&&Dt(t,s))throw new Error(`${p.name} takes a range here`)})}for(const t of Object.values(p))t!==null&&typeof t=="object"&<(t)}}export{jt as Engine};
|
package/calc/functions/array.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCategory as X}from"./registry.js";import{lift as D,raw as m}from"./registry.js";import{Arr as p,bool as _,compareValues as j,ERR as d,num as
|
|
1
|
+
import{setCategory as X}from"./registry.js";import{lift as D,raw as m}from"./registry.js";import{Arr as p,bool as _,compareValues as j,ERR as d,num as g,OMITTED as E,Ref as N,str as G,XlError as L}from"../values.js";import{MAX_COLS as K,MAX_ROWS as Y}from"../../core/address.js";X("Lookup & Reference");const C=o=>o===void 0||o===E,R=(o,t,s,c,r)=>C(t)?r:Math.trunc(g(o.scalar(t,s,c))),S=(o,t,s,c,r)=>C(t)?r:_(o.scalar(t,s,c)),O=o=>Array.from({length:o.rows},(t,s)=>o.data.slice(s*o.cols,(s+1)*o.cols)),T=o=>Array.from({length:o.cols},(t,s)=>Array.from({length:o.rows},(c,r)=>o.get(r,s))),y=o=>o===null?0:o;D("SEQUENCE",1,4,(o,t,s,c)=>{const r=Math.trunc(g(o)),n=t===void 0||t===E?1:Math.trunc(g(t)),e=s===void 0||s===E?1:g(s),f=c===void 0||c===E?1:g(c);if(r<0||n<0)throw d.VALUE;if(r===0||n===0)throw d.CALC;if(r*n>1<<27)throw d.NUM;const a=new Array(r*n);for(let l=0;l<a.length;l++)a[l]=e+l*f;return new p(r,n,a)}),D("RANDARRAY",0,5,(o,t,s,c,r)=>{const n=o===void 0||o===E?1:Math.trunc(g(o)),e=t===void 0||t===E?1:Math.trunc(g(t)),f=s===void 0||s===E?0:g(s),a=c===void 0||c===E?1:g(c),l=r===void 0||r===E?!1:_(r);if(n<0||e<0||f>a)throw d.VALUE;if(n===0||e===0)throw d.CALC;const i=new Array(n*e);for(let u=0;u<i.length;u++)i[u]=l?Math.ceil(f)+Math.floor(Math.random()*(Math.floor(a)-Math.ceil(f)+1)):f+Math.random()*(a-f);return new p(n,e,i)},{volatile:!0}),m("FILTER",2,3,(o,t,s,c)=>{const r=o.toArr(t[0]),n=o.toArr(t[1]),e=n.cols===1&&n.rows===r.rows,f=n.rows===1&&n.cols===r.cols;if(!e&&!f)throw d.VALUE;const a=n.data.map(h=>{if(h instanceof L)throw h;return h===null?!1:_(h)}),l=e?O(r).filter((h,w)=>a[w]):null,i=e?null:T(r).filter((h,w)=>a[w]);if(e?l.length===0:i.length===0){if(C(t[2]))throw d.CALC;return t[2]}if(e)return p.of2D(l.map(h=>h.map(y)));const A=new p(r.rows,i.length,new Array(r.rows*i.length));return i.forEach((h,w)=>h.forEach((M,V)=>{A.data[V*i.length+w]=y(M)})),A},{array:!0,passes:o=>o===2});function b(o,t){const s=o[0].length,c=Array.from({length:s},(r,n)=>n);return c.sort((r,n)=>{for(let e=0;e<o.length;e++){const f=o[e][r],a=o[e][n],l=f==null||f instanceof L,i=a==null||a instanceof L;if(l||i){if(l&&i)continue;return l?1:-1}const u=j(f,a);if(u!==0)return u*t[e]}return r-n}),c}m("SORT",1,4,(o,t,s,c)=>{const r=o.toArr(t[0]),n=S(o,t[3],s,c,!1),e=C(t[1])?[1]:o.toArr(t[1]).data.map(w=>Math.trunc(g(w))),f=C(t[2])?e.map(()=>1):o.toArr(t[2]).data.map(w=>g(w));if(f.length!==e.length||f.some(w=>w!==1&&w!==-1))throw d.VALUE;const a=n?T(r):O(r),l=n?r.rows:r.cols;for(const w of e)if(w<1||w>l)throw d.VALUE;const i=e.map(w=>a.map(M=>M[w-1])),A=b(i,f).map(w=>a[w]);if(!n)return p.of2D(A.map(w=>w.map(y)));const h=new Array(r.rows*r.cols);return A.forEach((w,M)=>w.forEach((V,$)=>{h[$*r.cols+M]=y(V)})),new p(r.rows,r.cols,h)},{array:!0}),m("SORTBY",2,255,(o,t,s,c)=>{const r=o.toArr(t[0]),n=[],e=[];for(let u=1;u<t.length;u+=2){const A=o.toArr(t[u]),h=C(t[u+1])?1:g(o.scalar(t[u+1],s,c));if(h!==1&&h!==-1)throw d.VALUE;n.push(A),e.push(h)}const f=n[0].cols===1;for(const u of n)if(f?u.rows!==r.rows||u.cols!==1:u.cols!==r.cols||u.rows!==1)throw d.VALUE;const a=b(n.map(u=>u.data),e);if(f){const u=O(r);return p.of2D(a.map(A=>u[A].map(y)))}const l=T(r),i=new Array(r.rows*r.cols);return a.forEach((u,A)=>l[u].forEach((h,w)=>{i[w*r.cols+A]=y(h)})),new p(r.rows,r.cols,i)},{array:!0});const k=o=>o.map(t=>t===null?"\0":typeof t=="string"?`s${t.toLowerCase()}`:t instanceof L?`e${t.code}`:`${typeof t}${t}`).join("");m("UNIQUE",1,3,(o,t,s,c)=>{const r=o.toArr(t[0]),n=S(o,t[1],s,c,!1),e=S(o,t[2],s,c,!1),f=n?T(r):O(r),a=new Map;for(const A of f){const h=k(A);a.set(h,(a.get(h)??0)+1)}const l=new Set,i=[];for(const A of f){const h=k(A);(e?a.get(h)!==1:l.has(h))||(l.add(h),i.push(A))}if(i.length===0)throw d.CALC;if(!n)return p.of2D(i.map(A=>A.map(y)));const u=new Array(r.rows*i.length);return i.forEach((A,h)=>A.forEach((w,M)=>{u[M*i.length+h]=y(w)})),new p(r.rows,i.length,u)},{array:!0}),m("TRANSPOSE",1,1,(o,t)=>{const s=o.toArr(t[0]),c=new Array(s.data.length);for(let r=0;r<s.rows;r++)for(let n=0;n<s.cols;n++)c[n*s.rows+r]=y(s.get(r,n));return new p(s.cols,s.rows,c)},{array:!0});function I(o,t,s){const c=t.map(a=>o.toArr(a));if(!s){const a=Math.max(...c.map(i=>i.cols)),l=[];for(const i of c)for(let u=0;u<i.rows;u++){const A=new Array(a);for(let h=0;h<a;h++)A[h]=h<i.cols?y(i.get(u,h)):d.NA;l.push(A)}return p.of2D(l)}const r=Math.max(...c.map(a=>a.rows)),n=c.reduce((a,l)=>a+l.cols,0),e=new Array(r*n);let f=0;for(const a of c){for(let l=0;l<a.cols;l++)for(let i=0;i<r;i++)e[i*n+f+l]=i<a.rows?y(a.get(i,l)):d.NA;f+=a.cols}return new p(r,n,e)}m("VSTACK",1,254,(o,t)=>I(o,t,!1),{array:!0}),m("HSTACK",1,254,(o,t)=>I(o,t,!0),{array:!0});function H(o,t,s,c,r){const n=s-t+1,e=r-c+1,f=new Array(n*e);for(let a=0;a<n;a++)for(let l=0;l<e;l++)f[a*e+l]=y(o.get(t+a,c+l));return new p(n,e,f)}m("TAKE",2,3,(o,t,s,c)=>{const r=o.toArr(t[0]),n=R(o,t[1],s,c,r.rows),e=R(o,t[2],s,c,r.cols);if(n===0||e===0)throw d.CALC;const f=Math.min(Math.abs(n),r.rows),a=Math.min(Math.abs(e),r.cols),l=n<0?r.rows-f:0,i=e<0?r.cols-a:0;return H(r,l,l+f-1,i,i+a-1)},{array:!0}),m("DROP",2,3,(o,t,s,c)=>{const r=o.toArr(t[0]),n=R(o,t[1],s,c,0),e=R(o,t[2],s,c,0),f=r.rows-Math.abs(n),a=r.cols-Math.abs(e);if(f<=0||a<=0)throw d.CALC;const l=n>0?n:0,i=e>0?e:0;return H(r,l,l+f-1,i,i+a-1)},{array:!0}),m("EXPAND",2,4,(o,t,s,c)=>{const r=o.toArr(t[0]),n=R(o,t[1],s,c,r.rows),e=R(o,t[2],s,c,r.cols),f=C(t[3])?d.NA:o.scalar(t[3],s,c);if(n<r.rows||e<r.cols||n>Y||e>K)throw d.VALUE;const a=new Array(n*e);for(let l=0;l<n;l++)for(let i=0;i<e;i++)a[l*e+i]=l<r.rows&&i<r.cols?y(r.get(l,i)):f;return new p(n,e,a)},{array:!0});function F(o,t,s,c,r){const n=o.toArr(t[0]),e=r?O(n):T(n),f=[];for(let l=1;l<t.length;l++)for(const i of o.toArr(t[l]).data){const u=Math.trunc(g(i)),A=u<0?e.length+u:u-1;if(u===0||A<0||A>=e.length)throw d.VALUE;f.push(e[A])}if(r)return p.of2D(f.map(l=>l.map(y)));const a=new Array(n.rows*f.length);return f.forEach((l,i)=>l.forEach((u,A)=>{a[A*f.length+i]=y(u)})),new p(n.rows,f.length,a)}m("CHOOSEROWS",2,255,(o,t,s,c)=>F(o,t,s,c,!0),{array:!0}),m("CHOOSECOLS",2,255,(o,t,s,c)=>F(o,t,s,c,!1),{array:!0});function P(o,t,s,c){const r=o.toArr(t[0]),n=R(o,t[1],s,c,0),e=S(o,t[2],s,c,!1);if(n<0||n>3)throw d.VALUE;const f=[],a=l=>{(n===1||n===3)&&l===null||(n===2||n===3)&&l instanceof L||f.push(y(l))};if(e)for(let l=0;l<r.cols;l++)for(let i=0;i<r.rows;i++)a(r.get(i,l));else for(const l of r.data)a(l);if(f.length===0)throw d.CALC;return f}m("TOCOL",1,3,(o,t,s,c)=>p.column(P(o,t,s,c)),{array:!0}),m("TOROW",1,3,(o,t,s,c)=>p.row(P(o,t,s,c)),{array:!0});function W(o,t,s,c,r){const n=o.toArr(t[0]);if(n.rows>1&&n.cols>1)throw d.VALUE;const e=R(o,t[1],s,c,0);if(e<1)throw d.NUM;const f=C(t[2])?d.NA:o.scalar(t[2],s,c),a=n.data.length,l=Math.ceil(a/e),i=r?l:e,u=r?e:l,A=new Array(i*u);for(let h=0;h<i*u;h++){const w=h<a?y(n.data[h]):f;r?A[h]=w:A[h%e*u+Math.floor(h/e)]=w}return new p(i,u,A)}m("WRAPROWS",2,3,(o,t,s,c)=>W(o,t,s,c,!0),{array:!0}),m("WRAPCOLS",2,3,(o,t,s,c)=>W(o,t,s,c,!1),{array:!0});function U(o,t,s,c){if(!(t instanceof N))return t;const r=o.trim(t);let{r0:n,c0:e}=t,f=s&2?r.r1:t.r1,a=c&2?r.c1:t.c1;s&2&&r.r1<n&&(f=n),c&2&&r.c1<e&&(a=e);const l=(h,w)=>t.sheet.kind(h,w)!==0,i=h=>{for(let w=e;w<=a;w++)if(l(h,w))return!0;return!1},u=h=>{for(let w=n;w<=f;w++)if(l(w,h))return!0;return!1};if(s&1)for(;n<f&&!i(n);)n++;if(s&2)for(;f>n&&!i(f);)f--;if(c&1)for(;e<a&&!u(e);)e++;if(c&2)for(;a>e&&!u(a);)a--;if(s?n===f&&!i(n):c?e===a&&!u(e):!1)throw d.REF;return new N(t.sheet,n,e,f,a)}m("TRIMRANGE",1,3,(o,t,s,c)=>{const r=n=>{const e=t[n]===void 0||t[n]===null?3:R(o,t[n],s,c,3);if(e<0||e>3)throw d.VALUE;return e};return U(o,t[0],r(1),r(2))},{refResult:!0}),m("_TRO_ALL",1,1,(o,t)=>U(o,t[0],3,3),{refResult:!0,category:"Hidden"}),m("_TRO_LEADING",1,1,(o,t)=>U(o,t[0],1,1),{refResult:!0,category:"Hidden"}),m("_TRO_TRAILING",1,1,(o,t)=>U(o,t[0],2,2),{refResult:!0,category:"Hidden"}),m("ARRAYTOTEXT",1,2,(o,t,s,c)=>{const r=o.toArr(t[0]),n=R(o,t[1],s,c,0)===1,e=f=>f===null?"":typeof f=="string"?n?`"${f.replace(/"/g,'""')}"`:f:f instanceof L?f.code:G(f);return n?`{${O(r).map(f=>f.map(e).join(",")).join(";")}}`:r.data.map(e).join(", ")},{array:!0}),m("PERCENTOF",2,2,(o,t)=>{const s=r=>{if(!(r instanceof N)&&!(r instanceof p)){if(r instanceof L)throw r;return r===null||r===E?0:g(r)}let n=0;for(const e of o.toArr(r).data){if(e instanceof L)throw e;typeof e=="number"&&(n+=e)}return n},c=s(t[1]);if(c===0)throw d.DIV0;return s(t[0])/c},{array:!0}),m("SINGLE",1,1,(o,t,s,c)=>{const r=o.scalar(t[0],s,c);return r===null?0:r}),m("ANCHORARRAY",1,1,(o,t)=>t[0]instanceof N?o.spillRange(t[0]):d.REF,{refResult:!0});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCategory as
|
|
1
|
+
import{setCategory as O}from"./registry.js";import{raw as y}from"./registry.js";import{checked as I,ERR as m,OMITTED as T,Ref as S,RefList as P,textToNumber as q,XlError as R}from"../values.js";import{makeCriteria as G,scalarOf as X}from"./helpers.js";O("Database");function M(e){if(e instanceof R)throw e;const t=e instanceof P&&e.refs.length===1?e.refs[0]:e;if(!(t instanceof S))throw m.VALUE;return t}function b(e){return e===null||e instanceof R?"":(typeof e=="string"?e:String(e)).toLowerCase()}function $(e,t){const n=new Map,{c1:s}=e.trim(t);for(let r=t.c0;r<=s;r++){const o=b(e.read(t.sheet,t.r0,r));o!==""&&!n.has(o)&&n.set(o,r)}return n}function F(e,t,n,s,r,o,f){if(s===T||s===void 0){if(f)return null;throw m.VALUE}const u=X(e,s,r,o);if(typeof u=="number"){const l=Math.trunc(u);if(l<1||l>t.cols)throw m.VALUE;return t.c0+l-1}const d=typeof u=="string"?n.get(u.toLowerCase()):void 0;if(d===void 0)throw m.VALUE;return d}function K(e){const t=typeof e=="string"&&!/^[<>=]/.test(e)&&q(e)===null&&!/^(true|false)$/i.test(e);return G(t?`${e}*`:e)}function _(e,t,n,s){const{sheet:r,r0:o,c0:f}=t,u=e.trim(t),d=[];for(let i=f;i<=u.c1;i++){const a=b(e.read(r,o,i));d.push([i,s.get(a),a])}if(t.r1>u.r1)return null;const l=[];for(let i=o+1;i<=u.r1;i++){const a=[];let w=!0;for(const[p,c,V]of d){if(c===void 0){const g=r.formula(i,p);if(g&&g.t!=="dataTable"){const k=e._templateFor(r,i,p,g);a.push(N=>{const U=i+N-n.r0-1,C=e.scalar(k.fn(U,p,r),U,p);return C===!0||typeof C=="number"&&C!==0});continue}if(V==="")continue}const D=e.read(r,i,p);if(D===null)continue;if(c===void 0){if(D===!0||typeof D=="number"&&D!==0)continue;w=!1;break}const L=K(D);a.push(g=>L(e.read(n.sheet,g,c)))}if(w){if(a.length===0)return null;l.push(a)}}return l}function E(e,t,n,s,r,o){const f=M(t[0]),u=M(t[2]),d=$(e,f),l=F(e,f,d,t[1],n,s,r),i=_(e,u,f,d),{sheet:a}=f,w=e.trim(f).r1,p=c=>i===null||i.some(V=>V.every(D=>D(c)));for(let c=f.r0+1;c<=w;c++)p(c)&&o(l===null?null:e.read(a,c,l))}function j(e,t,n,s){const r=[];return E(e,t,n,s,!1,o=>{if(o instanceof R)throw o;typeof o=="number"&&r.push(o)}),r}const h=(e,t)=>y(e,3,3,(n,s,r,o)=>I(t(j(n,s,r,o))));function A(e,t){const n=e.length;if(n<(t?1:2))throw m.DIV0;const s=e.reduce((r,o)=>r+o,0)/n;return e.reduce((r,o)=>r+(o-s)**2,0)/(t?n:n-1)}h("DAVERAGE",e=>{if(e.length===0)throw m.DIV0;return e.reduce((t,n)=>t+n,0)/e.length}),h("DMAX",e=>e.length===0?0:e.reduce((t,n)=>n>t?n:t)),h("DMIN",e=>e.length===0?0:e.reduce((t,n)=>n<t?n:t)),h("DPRODUCT",e=>e.length===0?0:e.reduce((t,n)=>t*n,1)),h("DSTDEV",e=>Math.sqrt(A(e,!1))),h("DSTDEVP",e=>Math.sqrt(A(e,!0))),h("DSUM",e=>e.reduce((t,n)=>t+n,0)),h("DVAR",e=>A(e,!1)),h("DVARP",e=>A(e,!0)),y("DCOUNT",3,3,(e,t,n,s)=>{const r=t[1]===T;let o=0;return E(e,t,n,s,!0,f=>{(r||typeof f=="number")&&o++}),o}),y("DCOUNTA",3,3,(e,t,n,s)=>{const r=t[1]===T;let o=0;return E(e,t,n,s,!0,f=>{(r||f!==null)&&o++}),o}),y("DGET",3,3,(e,t,n,s)=>{let r=0,o=null;if(E(e,t,n,s,!1,f=>{r++,o=f}),r===0)throw m.VALUE;if(r>1)throw m.NUM;return o===null?0:o});
|
package/calc/functions/date.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCategory as
|
|
1
|
+
import{setCategory as K}from"./registry.js";import{alias as $,lift as p,raw as E}from"./registry.js";import{Arr as F,ERR as f,num as u,OMITTED as H,Ref as j,RefList as z,str as Z,XlError as B}from"../values.js";import{partsToSerial as M,serialToParts as d}from"../../core/numfmt.js";import{eachValue as X,toolpakScalar as T}from"./helpers.js";import{parseInput as k}from"../../core/input.js";import{NUM as S}from"../../core/sheet.js";import{days360 as q,yearFrac as v}from"./financial.js";K("Date & Time");const w=t=>t===void 0||t===H,l=(t,e,o,r,n)=>p(t,e,o,r,{...n,dateSystem:!0}),L=2958465;function c(t,e){const o=Math.floor(u(t));if(o<0||o>L-e)throw f.NUM;return o+e}function P(t,e,o,r){let n=t;if(n>=0&&n<1900&&(n+=1900),n<0||n>9999)throw f.NUM;if(e<-32767||e>32766)throw f.NUM;const a=n*12+(e-1),s=Math.floor(a/12),i=a-s*12+1,m=M(s,i,1)+o-1;if(m<r||m>L)throw f.NUM;return m-r}l("DATE",3,3,(t,e,o,r)=>P(Math.trunc(u(e)),Math.trunc(u(o)),Math.trunc(u(r)),t)),l("YEAR",1,1,(t,e)=>d(c(e,t)).year),l("MONTH",1,1,(t,e)=>d(c(e,t)).month),l("DAY",1,1,(t,e)=>d(c(e,t)).day);const b=t=>{const e=u(t);if(e<0)throw f.NUM;return Math.round((e-Math.floor(e))*86400)};p("HOUR",1,1,t=>Math.floor(b(t)/3600)%24),p("MINUTE",1,1,t=>Math.floor(b(t)%3600/60)),p("SECOND",1,1,t=>b(t)%60),p("TIME",3,3,(t,e,o)=>{const r=Math.trunc(u(t))*3600+Math.trunc(u(e))*60+Math.trunc(u(o));if(r<0)throw f.NUM;return r%86400/86400});const R=()=>{const t=new Date;return{whole:M(t.getFullYear(),t.getMonth()+1,t.getDate()),frac:(t.getHours()*3600+t.getMinutes()*60+t.getSeconds()+t.getMilliseconds()/1e3)/86400}};l("NOW",0,0,t=>{const e=R();return e.whole-t+e.frac},{volatile:!0}),l("TODAY",0,0,t=>R().whole-t,{volatile:!0});const V={jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12};function O(t){const e=t.trim(),o=/^(\d{1,2})([A-Za-z]{3,})(\d{4})$/.exec(e);if(o){const[,a,s,i]=o,m=k(`${a}-${s}-${i}`);return m.kind===S?m.value:null}const r=k(e);if(r.kind===S&&r.format&&/[ymd]/i.test(r.format))return r.value;let n=/^(\d{1,2})[-\s]([A-Za-z]{3,})[-\s,]*(\d{2,4})?$/.exec(e);if(n){const a=V[n[2].slice(0,3).toLowerCase()];if(a){const s=n[3]?Number(n[3])<100?2e3+Number(n[3]):Number(n[3]):new Date().getFullYear();return M(s,a,Number(n[1]))}}if(n=/^([A-Za-z]{3,})\s+(\d{1,2})(?:,?\s*(\d{2,4}))?$/.exec(e),n){const a=V[n[1].slice(0,3).toLowerCase()];if(a){const s=n[3]?Number(n[3])<100?2e3+Number(n[3]):Number(n[3]):new Date().getFullYear();return M(s,a,Number(n[2]))}}return null}l("DATEVALUE",1,1,(t,e)=>{if(typeof e!="string")throw f.VALUE;const o=e.split(/\s+\d{1,2}:\d{2}/)[0],r=O(o);if(r===null||r<t)throw f.VALUE;return Math.floor(r)-t}),p("TIMEVALUE",1,1,t=>{if(typeof t!="string")throw f.VALUE;const e=/\b(\d+):(\d+)(?::(\d+(?:\.\d+)?))?\s*(am|pm|a|p)?/i.exec(t);if(!e)throw f.VALUE;let o=Number(e[1]);if(e[4]){const r=e[4][0].toLowerCase()==="p";if(o>12)throw f.VALUE;o=o%12+(r?12:0)}return(o*3600+Number(e[2])*60+Number(e[3]??0))/86400%1}),l("DAYS",2,2,(t,e,o)=>c(e,t)-c(o,t)),l("DAYS360",2,3,(t,e,o,r)=>q(c(e,t),c(o,t),w(r)?!1:!!u(r)));function _(t,e){const o=d(t),r=o.year*12+(o.month-1)+e,n=Math.floor(r/12),a=r-n*12+1;if(n<1900||n>9999)throw f.NUM;const s=A(n,a);return M(n,a,Math.min(o.day,s))}function A(t,e){return e===2?t===1900||t%4===0&&(t%100!==0||t%400===0)?29:28:[31,28,31,30,31,30,31,31,30,31,30,31][e-1]}l("EDATE",2,2,(t,e,o)=>_(c(e,t),Math.trunc(u(o)))-t),l("EOMONTH",2,2,(t,e,o)=>{const r=d(c(e,t)),n=r.year*12+(r.month-1)+Math.trunc(u(o)),a=Math.floor(n/12),s=n-a*12+1;if(a<1900||a>9999)throw f.NUM;return M(a,s,A(a,s))-t}),l("WEEKDAY",1,2,(t,e,o)=>{const r=c(e,t),n=w(o)?1:Math.trunc(u(o)),a=d(r).weekday,s={1:0,2:1,3:1,11:1,12:2,13:3,14:4,15:5,16:6,17:0}[n];if(s===void 0)throw f.NUM;const i=(a-s+7)%7;return n===3?i:i+1}),l("ISOWEEKNUM",1,1,(t,e)=>W(c(e,t)));function W(t){const e=(d(t).weekday+6)%7,o=t-e+3,r=d(o).year;return Math.floor((o-M(r,1,1))/7)+1}l("WEEKNUM",1,2,(t,e,o)=>{const r=c(e,t),n=w(o)?1:Math.trunc(u(o));if(n===21)return W(r);const a={1:0,2:1,11:1,12:2,13:3,14:4,15:5,16:6,17:0}[n];if(a===void 0)throw f.NUM;const s=M(d(r).year,1,1),i=(d(s).weekday-a+7)%7;return Math.floor((r-s+i)/7)+1});function U(t){if(w(t)||t===null)return[!1,!1,!1,!1,!1,!0,!0];if(typeof t=="string"){if(!/^[01]{7}$/.test(t))throw f.VALUE;return[...t].map(r=>r==="1")}const e=Math.trunc(u(t)),o=new Array(7).fill(!1);if(e>=1&&e<=7)o[(e+4)%7]=!0,o[(e+5)%7]=!0;else if(e>=11&&e<=17)o[(e-5)%7]=!0;else throw f.NUM;return o}function D(t,e){const o=new Set;return w(e)||e===null||X(t,e,r=>{if(r instanceof B)throw r;if(typeof r=="number")o.add(Math.floor(r)+t.book.dateOffset);else if(typeof r=="string"){const n=O(r);if(n===null)throw f.VALUE;o.add(Math.floor(n))}}),o}const Y=(t,e)=>e[(d(t).weekday+6)%7];function g(t,e,o,r){const n=e>=t?1:-1,a=Math.min(t,e),s=Math.max(t,e),i=o.filter(h=>!h).length,m=s-a+1;let y=Math.floor(m/7)*i;for(let h=a+Math.floor(m/7)*7;h<=s;h++)Y(h,o)||y++;for(const h of r)h>=a&&h<=s&&!Y(h,o)&&y--;return y*n}const N=(t,e,o,r)=>{const n=T(t,e,o,r);if(typeof n=="string"){const a=O(n);if(a===null)throw f.VALUE;return Math.floor(a)}return c(n,t.book.dateOffset)};E("NETWORKDAYS",2,3,(t,e,o,r)=>g(N(t,e[0],o,r),N(t,e[1],o,r),U(void 0),D(t,e[2]))),E("NETWORKDAYS.INTL",2,4,(t,e,o,r)=>g(N(t,e[0],o,r),N(t,e[1],o,r),U(w(e[2])?void 0:t.scalar(e[2],o,r)),D(t,e[3])));function I(t,e,o,r){const n=Math.trunc(e),a=n<0?-1:1;let s=Math.abs(n),i=t;if(o.every(Boolean))throw f.VALUE;for(;s>0;){if(i+=a,i<0||i>L)throw f.NUM;!Y(i,o)&&!r.has(i)&&s--}return i}E("WORKDAY",2,3,(t,e,o,r)=>I(N(t,e[0],o,r),u(T(t,e[1],o,r)),U(void 0),D(t,e[2]))-t.book.dateOffset),E("WORKDAY.INTL",2,4,(t,e,o,r)=>I(N(t,e[0],o,r),u(T(t,e[1],o,r)),U(w(e[2])?void 0:t.scalar(e[2],o,r)),D(t,e[3]))-t.book.dateOffset),l("YEARFRAC",2,3,(t,e,o,r)=>{const n=w(r)?0:Math.trunc(u(r));if(n<0||n>4)throw f.NUM;return v(c(e,t),c(o,t),n)}),l("DATEDIF",3,3,(t,e,o,r)=>{const n=c(e,t),a=c(o,t);if(n>a)throw f.NUM;const s=d(n),i=d(a),m=Z(r).toUpperCase();let y=(i.year-s.year)*12+i.month-s.month;switch(i.day<s.day&&y--,m){case"D":return a-n;case"M":return y;case"Y":return Math.floor(y/12);case"YM":return y%12;case"YD":{let h=i.year;return(i.month<s.month||i.month===s.month&&i.day<s.day)&&h--,a-M(h,s.month,Math.min(s.day,A(h,s.month)))}case"MD":{if(i.day>=s.day)return i.day-s.day;const h=i.month===1?12:i.month-1,C=i.month===1?i.year-1:i.year;return A(C,h)-s.day+i.day}default:throw f.NUM}});export{F as Arr,j as Ref,z as RefList,$ as alias};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{setCategory as Ot}from"./registry.js";import{lift as Nt,raw as B}from"./registry.js";import{Arr as vt,bool as mt,checked as X,ERR as N,num as h,opt as R,Ref as Ut,RefList as Ft,XlError as Vt}from"../values.js";import{scalarOf as kt,toolpakScalar as dt}from"./helpers.js";import{partsToSerial as rt,serialToParts as x}from"../../core/numfmt.js";Ot("Financial");const St=2958465,pt=1e-7,yt=200,y=(t,n,s,o)=>Nt(t,n,s,(...e)=>X(o(...e))),m=t=>{if(!t)throw N.NUM},d=t=>{if(typeof t=="boolean")throw N.VALUE;return h(t)},G=t=>h(R(t,0))!==0?1:0;function D(t){const n=Math.trunc(d(t));if(n<0||n>St)throw N.VALUE;return n}function F(t){const n=Math.trunc(d(R(t,0)));return m(n>=0&&n<=4),n}function j(t){const n=Math.trunc(d(t));return m(n===1||n===2||n===4),n}const z=t=>t%4===0&&(t%100!==0||t%400===0),ct=(t,n)=>n===2?z(t)?29:28:n===4||n===6||n===9||n===11?30:31;function Z(t){const n=x(t);return n.day>=ct(n.year,n.month)}function P(t,n,s){const o=x(t),e=o.year*12+o.month-1+n,r=Math.floor(e/12),a=e-r*12+1,c=ct(r,a);return rt(r,a,s?c:Math.min(o.day,c))}function $(t,n,s=!1){const o=x(t),e=x(n);let r=o.day,a=e.day;if(s)r===31&&(r=30),a===31&&(a=30);else{const c=f=>f.month===2&&f.day>=ct(f.year,2);c(o)&&(c(e)&&(a=30),r=30),a===31&&r>=30&&(a=30),r===31&&(r=30)}return(e.year-o.year)*360+(e.month-o.month)*30+a-r}const V=(t,n,s)=>s===0?$(t,n):s===4?$(t,n,!0):n-t;function Yt(t,n){const s=x(t),o=x(n);if(s.year===o.year)return(n-t)/(z(s.year)?366:365);if(o.year===s.year+1&&(s.month>o.month||s.month===o.month&&s.day>=o.day)){const r=z(s.year)&&t<=rt(s.year,2,29)||z(o.year)&&n>=rt(o.year,2,29);return(n-t)/(r?366:365)}let e=0;for(let r=s.year;r<=o.year;r++)e+=z(r)?366:365;return(n-t)/(e/(o.year-s.year+1))}function _(t,n,s=0){const o=Math.trunc(Math.min(t,n)),e=Math.trunc(Math.max(t,n));switch(s){case 1:return Yt(o,e);case 2:return(e-o)/360;case 3:return(e-o)/365;case 4:return $(o,e,!0)/360;default:return $(o,e)/360}}function at(t,n,s,o){const e=Z(n),r=12/s;let a=1;for(;P(n,-a*r,e)>t;)a++;const c=P(n,-a*r,e),f=P(n,(1-a)*r,e),i=V(c,t,o),u=o===1?f-c:(o===3?365:360)/s,l=o===0||o===4?u-i:f-t;return{n:a,pcd:c,ncd:f,a:i,e:u,dsc:l,f:s}}function tt(t,n,s,o,e=!1){const r=D(t),a=D(n);e&&m(r<a);const c=j(s),f=F(o);return m(r<a),at(r,a,c,f)}function nt(t,n,s=-1){const o=.001*Math.max(1,Math.abs(t(n))),e=u=>Math.abs(t(u))<=o;let r=n;for(let u=0;u<yt;u++){const l=t(r);if(l===0)return r;const M=Math.min(1e-6*(1+Math.abs(r)),(r-s)/2),p=r-l*2*M/(t(r+M)-t(r-M));if(!Number.isFinite(p)||p<=s)break;if(Math.abs(p-r)<pt&&e(p))return p;r=p}let a=n,c=n+.01*(1+Math.abs(n)),f=t(a),i=t(c);for(let u=0;u<yt;u++){if(i===0)return c;let l=c-i*(c-a)/(i-f);if(l<=s&&(l=(c+s)/2),!Number.isFinite(l))break;if(Math.abs(l-c)<pt&&e(l))return l;a=c,f=i,c=l,i=t(c)}throw N.NUM}const J=(t,n)=>(1+t)**n,ot=(t,n)=>t===0?n:(t>-1?Math.expm1(n*Math.log1p(t)):J(t,n)-1)/t,ft=(t,n,s,o,e)=>-(o*J(t,n)+s*(1+t*e)*ot(t,n)),Bt=(t,n,s,o,e)=>-(o+s*(1+t*e)*ot(t,n))/J(t,n),et=(t,n,s,o,e)=>-(o+s*J(t,n))/((1+t*e)*ot(t,n));function st(t,n,s,o,e,r){const a=et(t,s,o,e,r);return n===1?r?0:-o*t:(r?ft(t,n-2,a,o,1)-a:ft(t,n-1,a,o,0))*t}function It(t,n,s,o,e,r){const a=[h(t),h(n),h(s),h(o),h(R(e,0)),G(r)];return m(a[1]>=1&&a[1]<a[2]+1),a}y("PMT",3,5,(t,n,s,o,e)=>et(h(t),h(n),h(s),h(R(o,0)),G(e))),y("PV",3,5,(t,n,s,o,e)=>Bt(h(t),h(n),h(s),h(R(o,0)),G(e))),y("FV",3,5,(t,n,s,o,e)=>ft(h(t),h(n),h(s),h(R(o,0)),G(e))),y("IPMT",4,6,(...t)=>st(...It(...t))),y("PPMT",4,6,(...t)=>{const[n,s,o,e,r,a]=It(...t);return et(n,o,e,r,a)-st(n,s,o,e,r,a)}),y("NPER",3,5,(t,n,s,o,e)=>{const r=h(t),a=h(n),c=h(s),f=h(R(o,0)),i=G(e);if(r===0){if(a===0)throw N.DIV0;return-(c+f)/a}const u=a*(1+r*i);return Math.log((u-f*r)/(u+c*r))/Math.log1p(r)}),y("RATE",3,6,(t,n,s,o,e,r)=>{const a=h(t),c=h(n),f=h(s),i=h(R(o,0)),u=G(e),l=h(R(r,.1));m(a>0&&l>-1);const M=nt(p=>f*J(p,a)+c*(1+p*u)*ot(p,a)+i,l);return m(M>-1+1e-6),M}),y("ISPMT",4,4,(t,n,s,o)=>{const e=h(s);if(e===0)throw N.DIV0;return h(o)*h(t)*(h(n)/e-1)}),y("PDURATION",3,3,(t,n,s)=>{const[o,e,r]=[h(t),h(n),h(s)];return m(o>0&&e>0&&r>0),(Math.log(r)-Math.log(e))/Math.log1p(o)}),y("RRI",3,3,(t,n,s)=>{const[o,e,r]=[h(t),h(n),h(s)];return m(o>0&&e!==0&&e*r>=0),(r/e)**(1/o)-1});function Dt(t,n,s,o,e,r,a){const c=d(t),f=Math.trunc(d(n)),i=d(s),u=Math.trunc(d(o)),l=Math.trunc(d(e)),M=Math.trunc(d(r));m(c>0&&f>0&&i>0&&u>=1&&l>=u&&l<=f&&(M===0||M===1));let p=0;for(let I=u;I<=l;I++)p+=a(c,I,f,i,M);return p}y("CUMIPMT",6,6,(...t)=>Dt(...t,(n,s,o,e,r)=>st(n,s,o,e,0,r))),y("CUMPRINC",6,6,(...t)=>Dt(...t,(n,s,o,e,r)=>et(n,o,e,0,r)-st(n,s,o,e,0,r)));function q(t,n){const s=[],o=e=>{for(const r of t.toArr(e).data)if(typeof r=="number")s.push(r);else if(r instanceof Vt)throw r};return n instanceof Ft?n.refs.forEach(o):n instanceof Ut||n instanceof vt?o(n):s.push(h(n)),s}const K=(t,n,s,o)=>h(kt(t,n,s,o)),it=t=>t.some(n=>n>0)&&t.some(n=>n<0),bt=99;function Et(t,n,s){const o=q(t,n),e=q(t,s).map(D);return m(o.length===e.length&&o.length>0),m(e.every(r=>r>=e[0])),[o,e.map(r=>(r-e[0])/365)]}function H(t,n,s){let o=0;for(let e=0;e<t.length;e++)o+=t[e]/(1+s)**n[e];return o}B("NPV",2,255,(t,n,s,o)=>{const e=K(t,n[0],s,o);if(e===-1)throw N.DIV0;let r=0,a=1;for(let c=1;c<n.length;c++)for(const f of q(t,n[c]))r+=f/(1+e)**a++;return X(r)},{array:!0}),B("IRR",1,2,(t,n,s,o)=>{const e=q(t,n[0]),r=K(t,R(n[1],.1),s,o);return m(r>-1&&it(e)),nt(a=>{let c=0;for(let f=0;f<e.length;f++)c+=e[f]/(1+a)**f;return c},r)},{array:!0}),B("MIRR",3,3,(t,n,s,o)=>{const e=q(t,n[0]),r=K(t,n[1],s,o),a=K(t,n[2],s,o);if(r===-1||a===-1||!it(e))throw N.DIV0;const c=e.length-1;let f=0,i=0;return e.forEach((u,l)=>{u>0?f+=u*(1+a)**(c-l):i+=u/(1+r)**l}),X((f/-i)**(1/c)-1)},{array:!0}),B("XNPV",3,3,(t,n,s,o)=>{const e=h(dt(t,n[0],s,o)),[r,a]=Et(t,n[1],n[2]);return m(e>=0),X(H(r,a,e))},{array:!0});function Xt(t,n,s){const o=t[0],e=u=>u*o>=0,r=s===0?1e-5:s,a=H(t,n,0)*o>0;let c=0,f=r,i=0;if(a){m(Math.abs(r)<1);const u=-Math.abs(r);e(H(t,n,u))?[c,f]=[-1,u]:[c,f]=[u,0]}else for(m(r>0),e(H(t,n,f))||(i=1);!e(H(t,n,f));)c=f,f*=2,i++,m(i<=bt);for(;++i<=bt;){const u=(c+f)/2,l=H(t,n,u);if(e(l)?f=u:c=u,f-c<=1e-8*(Math.abs(u)+.5)&&(!a||Math.abs(l)<=2e-8*Math.abs(o)))return u}throw N.NUM}B("XIRR",2,3,(t,n,s,o)=>{const[e,r]=Et(t,n[0],n[1]),a=K(t,R(n[2],.1),s,o);return m(a>-1&&it(e)),X(Xt(e,r,a))},{array:!0}),B("FVSCHEDULE",2,2,(t,n,s,o)=>{let e=h(dt(t,n[0],s,o));for(const r of q(t,n[1]))e*=1+r;return X(e)},{array:!0}),y("SLN",3,3,(t,n,s)=>{const o=h(s);if(o===0)throw N.DIV0;return(h(t)-h(n))/o}),y("SYD",4,4,(t,n,s,o)=>{const[e,r]=[h(s),h(o)];return m(e>0&&r>0&&r<=e),(h(t)-h(n))*(e-r+1)*2/(e*(e+1))}),y("DB",4,5,(t,n,s,o,e)=>{const r=h(t),a=h(n),c=h(s),f=Math.trunc(h(o)),i=Math.trunc(h(R(e,12)));if(m(r>=0&&a>=0&&c>0&&f>=1&&i>=1&&i<=12),m(f<=(i===12?c:c+1)),r===0)return 0;const u=Math.round((1-(a/r)**(1/c))*1e3)/1e3;let l=r*u*i/12;if(f===1)return l;let M=0;for(let p=2;p<=Math.min(f,c);p++)M=(r-l)*u,l+=M;return f>c?(r-l)*u*(12-i)/12:M});function ut(t,n,s,o,e){let r=e/s,a;r>=1?(r=1,a=o===1?t:0):a=t*(1-r)**(o-1);const c=t*(1-r)**o;return Math.max(a-Math.max(c,n),0)}y("DDB",4,5,(t,n,s,o,e)=>{const[r,a,c,f]=[h(t),h(n),h(s),h(o)],i=h(R(e,2));return m(r>=0&&a>=0&&c>0&&f>0&&f<=c&&i>0),ut(r,a,c,f,i)});function Rt(t,n,s,o,e,r){const a=Math.ceil(e);let c=t-n,f=0,i=!1,u=0;for(let l=1;l<=a;l++){let M=f;if(!i){const p=ut(t,n,s,l,r);f=c/(o-(l-1)),i=f>p,M=i?f:p,i||(c-=p)}u+=l===a?M*(e+1-a):M}return u}y("VDB",5,7,(t,n,s,o,e,r,a)=>{let c=h(t);const f=h(n),i=h(s);let u=h(o),l=h(e);const M=h(R(r,2)),p=mt(R(a,!1));if(m(c>=0&&f>=0&&i>0&&u>=0&&l>=u&&l<=i&&M>=0),p){const E=Math.floor(u),b=Math.ceil(l);let g=0;for(let A=E+1;A<=b;A++){let C=ut(c,f,i,A,M);A===E+1?C*=Math.min(l,E+1)-u:A===b&&(C*=l+1-b),g+=C}return g}let I=i;return u!==Math.floor(u)&&M>1&&u>=i/2&&(l-=u-i/2,u=i/2,I+=1),c-=Rt(c,f,i,I,u,M),Rt(c,f,i,i-u,l-u,M)});function At(t,n,s,o,e,r,a){const c={cost:d(t),bought:D(n),firstEnd:D(s),salvage:d(o),per:Math.trunc(d(e)),rate:d(r),basis:F(a)};return m(c.basis!==2&&c.cost>=0&&c.salvage>=0&&c.salvage<=c.cost),m(c.per>=0&&c.rate>0&&c.bought<=c.firstEnd),c.frac=_(c.bought,c.firstEnd,c.basis),c}y("AMORLINC",6,7,(...t)=>{const{cost:n,salvage:s,per:o,rate:e,frac:r}=At(...t),a=n*e,c=r*a,f=Math.trunc((n-s-c)/a);return o===0?c:o<=f?a:o===f+1?n-s-a*f-c:0}),y("AMORDEGRC",6,7,(...t)=>{const{cost:n,salvage:s,per:o,rate:e,frac:r}=At(...t),a=1/e,c=(M,p)=>a>=M&&a<=p;m(c(3,4)||c(5,6)||a>6);const f=e*(c(3,4)?1.5:c(5,6)?2:2.5);let i=Math.round(r*f*n),u=n-i,l=u-s;for(let M=0;M<o;M++){if(i=Math.round(f*u),l-=i,l<0)return o-M===1?Math.round(u*.5):0;u-=i}return i}),y("EFFECT",2,2,(t,n)=>{const s=d(t),o=Math.trunc(d(n));return m(s>0&&o>=1),(1+s/o)**o-1}),y("NOMINAL",2,2,(t,n)=>{const s=d(t),o=Math.trunc(d(n));return m(s>0&&o>=1),o*((1+s)**(1/o)-1)});function Ct(t,n,s){const o=d(t),e=Math.trunc(d(n));if(m(e>=0),e===0)throw N.DIV0;const r=Math.trunc(o);return r+s(o-r,e,10**Math.ceil(Math.log10(e)))}y("DOLLARDE",2,2,(t,n)=>Ct(t,n,(s,o,e)=>s*e/o)),y("DOLLARFR",2,2,(t,n)=>Ct(t,n,(s,o,e)=>s*o/e));function lt(t,n,s,o){const e=D(t),r=D(n),a=d(s);return m(e<r&&r<=P(e,12,!1)&&a>0),o(a,r-e)}y("TBILLEQ",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>365*o/(360-o*e))),y("TBILLPRICE",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>100*(1-o*e/360))),y("TBILLYIELD",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>(100-o)/o*360/e)),y("ACCRINT",6,8,(t,n,s,o,e,r,a,c)=>{const f=D(t),i=D(n),u=D(s),l=d(o),M=d(R(e,1e3)),p=j(r),I=F(a),E=mt(R(c,!0));m(l>0&&M>0&&f<u);const b=!E&&u>i?i:f,g=12/p,A=Z(i);let C=0;for(;P(i,C*g,A)>b;)C--;for(;P(i,(C+1)*g,A)<=b;)C++;let U=0;for(;P(i,C*g,A)<u;C++){const L=P(i,C*g,A),v=P(i,(C+1)*g,A),T=I===1?v-L:(I===3?365:360)/p;U+=V(Math.max(L,b),Math.min(v,u),I)/T}return M*l*U/p}),y("ACCRINTM",4,5,(t,n,s,o,e)=>{const r=D(t),a=D(n),c=d(s),f=d(R(o,1e3)),i=F(e);return m(c>0&&f>0&&r<a),f*c*_(r,a,i)});const Q=(t,n)=>y(t,3,4,(s,o,e,r)=>n(tt(s,o,e,r,!0)));Q("COUPDAYBS",t=>t.a),Q("COUPDAYS",t=>t.e),Q("COUPDAYSNC",t=>t.dsc),Q("COUPNCD",t=>t.ncd),Q("COUPNUM",t=>t.n),Q("COUPPCD",t=>t.pcd);const W=(t,n)=>y(t,4,5,(s,o,e,r,a)=>{const c=D(s),f=D(o),i=d(e),u=d(r),l=F(a);return m(c<f&&i>0&&u>0),n(i,u,_(c,f,l))});W("DISC",(t,n,s)=>(n-t)/n/s),W("INTRATE",(t,n,s)=>(n-t)/t/s),W("RECEIVED",(t,n,s)=>{const o=1-n*s;return m(o>0),t/o}),W("PRICEDISC",(t,n,s)=>n*(1-t*s)),W("YIELDDISC",(t,n,s)=>(n/t-1)/s);const gt=(t,n,s)=>y(t,5,6,(o,e,r,a,c,f)=>{const i=D(o),u=D(e),l=D(r),M=d(a),p=d(c),I=F(f);return m(i<u&&l<i&&M>=0&&n(p)),s(M,p,_(l,u,I),_(l,i,I),_(i,u,I))});gt("PRICEMAT",t=>t>=0,(t,n,s,o,e)=>(100+s*t*100)/(1+e*n)-o*t*100),gt("YIELDMAT",t=>t>0,(t,n,s,o,e)=>{const r=n/100+o*t;return(1+s*t-r)/r/e});function Pt(t,n,s,o){const e=100*n/t.f,r=t.dsc/t.e;if(t.n===1)return(o+e)/(1+s/t.f*r)-e*t.a/t.e;const a=1+s/t.f;let c=o/a**(t.n-1+r);for(let f=0;f<t.n;f++)c+=e/a**(f+r);return c-e*t.a/t.e}y("PRICE",6,7,(t,n,s,o,e,r,a)=>{const c=d(s),f=d(o),i=d(e),u=tt(t,n,r,a);return m(c>=0&&f>=0&&i>0),Pt(u,c,f,i)}),y("YIELD",6,7,(t,n,s,o,e,r,a)=>{const c=d(s),f=d(o),i=d(e),u=tt(t,n,r,a);if(m(c>=0&&f>0&&i>0),u.n===1){const l=c/u.f,M=f/100+u.a/u.e*l;return(i/100+l-M)/M*(u.f*u.e/u.dsc)}return nt(l=>Pt(u,c,l,i)-f,.1,-u.f)});function Lt(t,n,s,o,e,r){const a=d(s),c=d(o),f=tt(t,n,e,r);m(a>=0&&c>=0);const i=1+c/f.f,u=100*a/f.f,l=f.dsc/f.e;let M=0,p=0;for(let I=0;I<f.n;I++){const E=I+l,b=(I===f.n-1?u+100:u)/i**E;M+=E*b,p+=b}return[M/p/f.f,i]}y("DURATION",5,6,(...t)=>Lt(...t)[0]),y("MDURATION",5,6,(...t)=>{const[n,s]=Lt(...t);return n/s});function Tt(t,n,s,o,e,r,a,c){const f=D(t),i=D(n),u=D(s),l=D(o),M=d(e),p=d(r),I=j(a),E=F(c);m(i>l&&l>f&&f>u&&M>=0&&p>0);const b=at(f,l,I,E),g=b.n===1?V(f,l,E):b.dsc,A=at(l,i,I,E).n,C=Z(l),U=12/I;let L=0,v=0;for(let k=0,w=l;;k++){const O=P(l,-(k+1)*U,C),S=E===1?w-O:b.e;L+=(O>u?S:V(u,w,E))/S;const ht=Math.max(u,O),Mt=Math.min(f,w);if(Mt>ht&&(v+=V(ht,Mt,E)/S),O<=u)break;w=O}const T=100*M/I,Y=b.n-1+g/b.e;return k=>{const w=1+k/I;let O=p/w**(A+Y)+T*L/w**Y;for(let S=1;S<=A;S++)O+=T/w**(S+Y);return O-T*v}}y("ODDFPRICE",8,9,(t,n,s,o,e,r,a,c,f)=>{const i=d(r),u=Tt(t,n,s,o,e,a,c,f);return m(i>=0),u(i)}),y("ODDFYIELD",8,9,(t,n,s,o,e,r,a,c,f)=>{const i=d(r),u=Tt(t,n,s,o,e,a,c,f);return m(i>0),nt(l=>u(l)-i,.1,-j(c))});function wt(t,n,s,o,e,r,a){const c=D(t),f=D(n),i=D(s),u=d(o),l=d(e),M=j(r),p=F(a);m(f>c&&c>i&&u>=0&&l>0);const I=12/M,E=Z(i);let b=0,g=0,A=0;for(let U=0;;U++){const L=P(i,U*I,E),v=P(i,(U+1)*I,E),T=p===0||p===4?360/M:v-L,Y=v>=f,k=Y?V(L,f,p):T;b+=k/T,v<c?g+=k/T:L<c&&(g+=V(L,c,p)/T);const w=Math.max(c,L),O=Math.min(f,v);if(O>w&&(A+=V(w,O,p)/T),Y)break}const C=100*u/M;return{income:l+b*C,interest:g*C,toGo:A,f:M}}y("ODDLPRICE",7,8,(t,n,s,o,e,r,a,c)=>{const f=d(e),i=wt(t,n,s,o,r,a,c);return m(f>=0),i.income/(1+i.toGo*f/i.f)-i.interest}),y("ODDLYIELD",7,8,(t,n,s,o,e,r,a,c)=>{const f=d(e),i=wt(t,n,s,o,r,a,c);m(f>0);const u=f+i.interest;return(i.income-u)/u*(i.f/i.toGo)});export{$ as days360,_ as yearFrac};
|
|
1
|
+
import{setCategory as Ot}from"./registry.js";import{lift as Nt,raw as B}from"./registry.js";import{Arr as vt,bool as mt,checked as X,ERR as N,num as h,opt as E,Ref as Ut,RefList as Ft,XlError as Vt}from"../values.js";import{liftReferenceArgs as kt,scalarOf as St,toolpakScalar as dt}from"./helpers.js";import{partsToSerial as rt,serialToParts as x}from"../../core/numfmt.js";Ot("Financial");const Yt=2958465,pt=1e-7,yt=200,y=(t,n,s,o)=>Nt(t,n,s,(...e)=>X(o(...e))),d=t=>{if(!t)throw N.NUM},p=t=>{if(typeof t=="boolean")throw N.VALUE;return h(t)},G=t=>h(E(t,0))!==0?1:0;function D(t){const n=Math.trunc(p(t));if(n<0||n>Yt)throw N.VALUE;return n}function F(t){const n=Math.trunc(p(E(t,0)));return d(n>=0&&n<=4),n}function j(t){const n=Math.trunc(p(t));return d(n===1||n===2||n===4),n}const z=t=>t%4===0&&(t%100!==0||t%400===0),ct=(t,n)=>n===2?z(t)?29:28:n===4||n===6||n===9||n===11?30:31;function Z(t){const n=x(t);return n.day>=ct(n.year,n.month)}function P(t,n,s){const o=x(t),e=o.year*12+o.month-1+n,r=Math.floor(e/12),a=e-r*12+1,c=ct(r,a);return rt(r,a,s?c:Math.min(o.day,c))}function $(t,n,s=!1){const o=x(t),e=x(n);let r=o.day,a=e.day;if(s)r===31&&(r=30),a===31&&(a=30);else{const c=f=>f.month===2&&f.day>=ct(f.year,2);c(o)&&(c(e)&&(a=30),r=30),a===31&&r>=30&&(a=30),r===31&&(r=30)}return(e.year-o.year)*360+(e.month-o.month)*30+a-r}const V=(t,n,s)=>s===0?$(t,n):s===4?$(t,n,!0):n-t;function Bt(t,n){const s=x(t),o=x(n);if(s.year===o.year)return(n-t)/(z(s.year)?366:365);if(o.year===s.year+1&&(s.month>o.month||s.month===o.month&&s.day>=o.day)){const r=z(s.year)&&t<=rt(s.year,2,29)||z(o.year)&&n>=rt(o.year,2,29);return(n-t)/(r?366:365)}let e=0;for(let r=s.year;r<=o.year;r++)e+=z(r)?366:365;return(n-t)/(e/(o.year-s.year+1))}function _(t,n,s=0){const o=Math.trunc(Math.min(t,n)),e=Math.trunc(Math.max(t,n));switch(s){case 1:return Bt(o,e);case 2:return(e-o)/360;case 3:return(e-o)/365;case 4:return $(o,e,!0)/360;default:return $(o,e)/360}}function at(t,n,s,o){const e=Z(n),r=12/s;let a=1;for(;P(n,-a*r,e)>t;)a++;const c=P(n,-a*r,e),f=P(n,(1-a)*r,e),i=V(c,t,o),u=o===1?f-c:(o===3?365:360)/s,l=o===0||o===4?u-i:f-t;return{n:a,pcd:c,ncd:f,a:i,e:u,dsc:l,f:s}}function tt(t,n,s,o,e=!1){const r=D(t),a=D(n);e&&d(r<a);const c=j(s),f=F(o);return d(r<a),at(r,a,c,f)}function nt(t,n,s=-1){const o=.001*Math.max(1,Math.abs(t(n))),e=u=>Math.abs(t(u))<=o;let r=n;for(let u=0;u<yt;u++){const l=t(r);if(l===0)return r;const M=Math.min(1e-6*(1+Math.abs(r)),(r-s)/2),m=r-l*2*M/(t(r+M)-t(r-M));if(!Number.isFinite(m)||m<=s)break;if(Math.abs(m-r)<pt&&e(m))return m;r=m}let a=n,c=n+.01*(1+Math.abs(n)),f=t(a),i=t(c);for(let u=0;u<yt;u++){if(i===0)return c;let l=c-i*(c-a)/(i-f);if(l<=s&&(l=(c+s)/2),!Number.isFinite(l))break;if(Math.abs(l-c)<pt&&e(l))return l;a=c,f=i,c=l,i=t(c)}throw N.NUM}const J=(t,n)=>(1+t)**n,ot=(t,n)=>t===0?n:(t>-1?Math.expm1(n*Math.log1p(t)):J(t,n)-1)/t,ft=(t,n,s,o,e)=>{const r=J(t,n),a=Math.abs(t)<1e-6?ot(t,n):(r-1)/t;return-(o*r+s*(1+t*e)*a)},Xt=(t,n,s,o,e)=>-(o+s*(1+t*e)*ot(t,n))/J(t,n),et=(t,n,s,o,e)=>-(o+s*J(t,n))/((1+t*e)*ot(t,n));function st(t,n,s,o,e,r){const a=et(t,s,o,e,r);return n===1?r?0:-o*t:(r?ft(t,n-2,a,o,1)-a:ft(t,n-1,a,o,0))*t}function It(t,n,s,o,e,r){const a=[h(t),h(n),h(s),h(o),h(E(e,0)),G(r)];return d(a[1]>=1&&a[1]<a[2]+1),a}y("PMT",3,5,(t,n,s,o,e)=>et(h(t),h(n),h(s),h(E(o,0)),G(e))),y("PV",3,5,(t,n,s,o,e)=>Xt(h(t),h(n),h(s),h(E(o,0)),G(e))),y("FV",3,5,(t,n,s,o,e)=>ft(h(t),h(n),h(s),h(E(o,0)),G(e))),y("IPMT",4,6,(...t)=>st(...It(...t))),y("PPMT",4,6,(...t)=>{const[n,s,o,e,r,a]=It(...t);return et(n,o,e,r,a)-st(n,s,o,e,r,a)}),y("NPER",3,5,(t,n,s,o,e)=>{const r=h(t),a=h(n),c=h(s),f=h(E(o,0)),i=G(e);if(r===0){if(a===0)throw N.DIV0;return-(c+f)/a}const u=a*(1+r*i);return Math.log((u-f*r)/(u+c*r))/Math.log1p(r)}),y("RATE",3,6,(t,n,s,o,e,r)=>{const a=h(t),c=h(n),f=h(s),i=h(E(o,0)),u=G(e),l=h(E(r,.1));d(a>0&&l>-1);const M=nt(m=>f*J(m,a)+c*(1+m*u)*ot(m,a)+i,l);return d(M>-1+1e-6),M}),y("ISPMT",4,4,(t,n,s,o)=>{const e=h(s);if(e===0)throw N.DIV0;return h(o)*h(t)*(h(n)/e-1)}),y("PDURATION",3,3,(t,n,s)=>{const[o,e,r]=[h(t),h(n),h(s)];return d(o>0&&e>0&&r>0),(Math.log(r)-Math.log(e))/Math.log1p(o)}),y("RRI",3,3,(t,n,s)=>{const[o,e,r]=[h(t),h(n),h(s)];return d(o>0&&e!==0&&e*r>=0),(r/e)**(1/o)-1});function Dt(t,n,s,o,e,r,a){const c=p(t),f=Math.trunc(p(n)),i=p(s),u=Math.trunc(p(o)),l=Math.trunc(p(e)),M=Math.trunc(p(r));d(c>0&&f>0&&i>0&&u>=1&&l>=u&&l<=f&&(M===0||M===1));let m=0;for(let I=u;I<=l;I++)m+=a(c,I,f,i,M);return m}y("CUMIPMT",6,6,(...t)=>Dt(...t,(n,s,o,e,r)=>st(n,s,o,e,0,r))),y("CUMPRINC",6,6,(...t)=>Dt(...t,(n,s,o,e,r)=>et(n,o,e,0,r)-st(n,s,o,e,0,r)));function q(t,n){const s=[],o=e=>{for(const r of t.toArr(e).data)if(typeof r=="number")s.push(r);else if(r instanceof Vt)throw r};return n instanceof Ft?n.refs.forEach(o):n instanceof Ut||n instanceof vt?o(n):s.push(h(n)),s}const K=(t,n,s,o)=>h(St(t,n,s,o)),it=t=>t.some(n=>n>0)&&t.some(n=>n<0),Rt=99;function bt(t,n,s){const o=q(t,n),e=q(t,s).map(D);return d(o.length===e.length&&o.length>0),d(e.every(r=>r>=e[0])),[o,e.map(r=>(r-e[0])/365)]}function H(t,n,s){let o=0;for(let e=0;e<t.length;e++)o+=t[e]/(1+s)**n[e];return o}function xt(t,n,s,o){const e=K(t,n[0],s,o);if(e===-1)throw N.DIV0;let r=0,a=1;for(let c=1;c<n.length;c++)for(const f of q(t,n[c]))r+=f/(1+e)**a++;return X(r)}B("NPV",2,255,(t,n,s,o)=>kt(n,e=>xt(t,e,s,o)),{array:!0}),B("IRR",1,2,(t,n,s,o)=>{const e=q(t,n[0]),r=K(t,E(n[1],.1),s,o);return d(r>-1&&it(e)),nt(a=>{let c=0;for(let f=0;f<e.length;f++)c+=e[f]/(1+a)**f;return c},r)},{array:!0}),B("MIRR",3,3,(t,n,s,o)=>{const e=q(t,n[0]),r=K(t,n[1],s,o),a=K(t,n[2],s,o);if(r===-1||a===-1||!it(e))throw N.DIV0;const c=e.length-1;let f=0,i=0;return e.forEach((u,l)=>{u>0?f+=u*(1+a)**(c-l):i+=u/(1+r)**l}),X((f/-i)**(1/c)-1)},{array:!0}),B("XNPV",3,3,(t,n,s,o)=>{const e=h(dt(t,n[0],s,o)),[r,a]=bt(t,n[1],n[2]);return d(e>=0),X(H(r,a,e))},{array:!0});function Gt(t,n,s){const o=t[0],e=u=>u*o>=0,r=s===0?1e-5:s,a=H(t,n,0)*o>0;let c=0,f=r,i=0;if(a){d(Math.abs(r)<1);const u=-Math.abs(r);e(H(t,n,u))?[c,f]=[-1,u]:[c,f]=[u,0]}else for(d(r>0),e(H(t,n,f))||(i=1);!e(H(t,n,f));)c=f,f*=2,i++,d(i<=Rt);for(;++i<=Rt;){const u=(c+f)/2,l=H(t,n,u);if(e(l)?f=u:c=u,f-c<=1e-8*(Math.abs(u)+.5)&&(!a||Math.abs(l)<=2e-8*Math.abs(o)))return u}throw N.NUM}B("XIRR",2,3,(t,n,s,o)=>{const[e,r]=bt(t,n[0],n[1]),a=K(t,E(n[2],.1),s,o);return d(a>-1&&it(e)),X(Gt(e,r,a))},{array:!0}),B("FVSCHEDULE",2,2,(t,n,s,o)=>{let e=h(dt(t,n[0],s,o));for(const r of q(t,n[1]))e*=1+r;return X(e)},{array:!0}),y("SLN",3,3,(t,n,s)=>{const o=h(s);if(o===0)throw N.DIV0;return(h(t)-h(n))/o}),y("SYD",4,4,(t,n,s,o)=>{const[e,r]=[h(s),h(o)];return d(e>0&&r>0&&r<=e),(h(t)-h(n))*(e-r+1)*2/(e*(e+1))}),y("DB",4,5,(t,n,s,o,e)=>{const r=h(t),a=h(n),c=h(s),f=Math.trunc(h(o)),i=Math.trunc(h(E(e,12)));if(d(r>=0&&a>=0&&c>0&&f>=1&&i>=1&&i<=12),d(f<=(i===12?c:c+1)),r===0)return 0;const u=Math.round((1-(a/r)**(1/c))*1e3)/1e3;let l=r*u*i/12;if(f===1)return l;let M=0;for(let m=2;m<=Math.min(f,c);m++)M=(r-l)*u,l+=M;return f>c?(r-l)*u*(12-i)/12:M});function ut(t,n,s,o,e){let r=e/s,a;r>=1?(r=1,a=o===1?t:0):a=t*(1-r)**(o-1);const c=t*(1-r)**o;return Math.max(a-Math.max(c,n),0)}y("DDB",4,5,(t,n,s,o,e)=>{const[r,a,c,f]=[h(t),h(n),h(s),h(o)],i=h(E(e,2));return d(r>=0&&a>=0&&c>0&&f>0&&f<=c&&i>0),ut(r,a,c,f,i)});function Et(t,n,s,o,e,r){const a=Math.ceil(e);let c=t-n,f=0,i=!1,u=0;for(let l=1;l<=a;l++){let M=f;if(!i){const m=ut(t,n,s,l,r);f=c/(o-(l-1)),i=f>m,M=i?f:m,i||(c-=m)}u+=l===a?M*(e+1-a):M}return u}y("VDB",5,7,(t,n,s,o,e,r,a)=>{let c=h(t);const f=h(n),i=h(s);let u=h(o),l=h(e);const M=h(E(r,2)),m=mt(E(a,!1));if(d(c>=0&&f>=0&&i>0&&u>=0&&l>=u&&l<=i&&M>=0),m){const b=Math.floor(u),R=Math.ceil(l);let g=0;for(let A=b+1;A<=R;A++){let C=ut(c,f,i,A,M);A===b+1?C*=Math.min(l,b+1)-u:A===R&&(C*=l+1-R),g+=C}return g}let I=i;return u!==Math.floor(u)&&M>1&&u>=i/2&&(l-=u-i/2,u=i/2,I+=1),c-=Et(c,f,i,I,u,M),Et(c,f,i,i-u,l-u,M)});function At(t,n,s,o,e,r,a){const c={cost:p(t),bought:D(n),firstEnd:D(s),salvage:p(o),per:Math.trunc(p(e)),rate:p(r),basis:F(a)};return d(c.basis!==2&&c.cost>=0&&c.salvage>=0&&c.salvage<=c.cost),d(c.per>=0&&c.rate>0&&c.bought<=c.firstEnd),c.frac=_(c.bought,c.firstEnd,c.basis),c}y("AMORLINC",6,7,(...t)=>{const{cost:n,salvage:s,per:o,rate:e,frac:r}=At(...t),a=n*e,c=r*a,f=Math.trunc((n-s-c)/a);return o===0?c:o<=f?a:o===f+1?n-s-a*f-c:0}),y("AMORDEGRC",6,7,(...t)=>{const{cost:n,salvage:s,per:o,rate:e,frac:r}=At(...t),a=1/e,c=(M,m)=>a>=M&&a<=m;d(c(3,4)||c(5,6)||a>6);const f=e*(c(3,4)?1.5:c(5,6)?2:2.5),i=Math.ceil(a)-1;if(o>i)return 0;let u=Math.round(r*f*n),l=n-u;for(let M=1;M<=o;M++){if(l<s)return 0;u=(M===i?1:M===i-1?.5:f)*l,l-=u}return Math.round(u)}),y("EFFECT",2,2,(t,n)=>{const s=p(t),o=Math.trunc(p(n));return d(s>0&&o>=1),(1+s/o)**o-1}),y("NOMINAL",2,2,(t,n)=>{const s=p(t),o=Math.trunc(p(n));return d(s>0&&o>=1),o*((1+s)**(1/o)-1)});function Ct(t,n,s){const o=p(t),e=Math.trunc(p(n));if(d(e>=0),e===0)throw N.DIV0;const r=Math.trunc(o);return r+s(o-r,e,10**Math.ceil(Math.log10(e)))}y("DOLLARDE",2,2,(t,n)=>Ct(t,n,(s,o,e)=>s*e/o)),y("DOLLARFR",2,2,(t,n)=>Ct(t,n,(s,o,e)=>s*o/e));function lt(t,n,s,o){const e=D(t),r=D(n),a=p(s);return d(e<r&&r<=P(e,12,!1)&&a>0),o(a,r-e)}y("TBILLEQ",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>365*o/(360-o*e))),y("TBILLPRICE",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>100*(1-o*e/360))),y("TBILLYIELD",3,3,(t,n,s)=>lt(t,n,s,(o,e)=>(100-o)/o*360/e)),y("ACCRINT",6,8,(t,n,s,o,e,r,a,c)=>{const f=D(t),i=D(n),u=D(s),l=p(o),M=p(E(e,1e3)),m=j(r),I=F(a),b=mt(E(c,!0));d(l>0&&M>0&&f<u);const R=!b&&u>i?i:f,g=12/m,A=Z(i);let C=0;for(;P(i,C*g,A)>R;)C--;for(;P(i,(C+1)*g,A)<=R;)C++;let U=0;for(;P(i,C*g,A)<u;C++){const L=P(i,C*g,A),v=P(i,(C+1)*g,A),T=I===1?v-L:(I===3?365:360)/m;U+=V(Math.max(L,R),Math.min(v,u),I)/T}return M*l*U/m}),y("ACCRINTM",4,5,(t,n,s,o,e)=>{const r=D(t),a=D(n),c=p(s),f=p(E(o,1e3)),i=F(e);return d(c>0&&f>0&&r<a),f*c*_(r,a,i)});const Q=(t,n)=>y(t,3,4,(s,o,e,r)=>n(tt(s,o,e,r,!0)));Q("COUPDAYBS",t=>t.a),Q("COUPDAYS",t=>t.e),Q("COUPDAYSNC",t=>t.dsc),Q("COUPNCD",t=>t.ncd),Q("COUPNUM",t=>t.n),Q("COUPPCD",t=>t.pcd);const W=(t,n)=>y(t,4,5,(s,o,e,r,a)=>{const c=D(s),f=D(o),i=p(e),u=p(r),l=F(a);return d(c<f&&i>0&&u>0),n(i,u,_(c,f,l))});W("DISC",(t,n,s)=>(n-t)/n/s),W("INTRATE",(t,n,s)=>(n-t)/t/s),W("RECEIVED",(t,n,s)=>{const o=1-n*s;return d(o>0),t/o}),W("PRICEDISC",(t,n,s)=>n*(1-t*s)),W("YIELDDISC",(t,n,s)=>(n/t-1)/s);const gt=(t,n,s)=>y(t,5,6,(o,e,r,a,c,f)=>{const i=D(o),u=D(e),l=D(r),M=p(a),m=p(c),I=F(f);return d(i<u&&l<i&&M>=0&&n(m)),s(M,m,_(l,u,I),_(l,i,I),_(i,u,I))});gt("PRICEMAT",t=>t>=0,(t,n,s,o,e)=>(100+s*t*100)/(1+e*n)-o*t*100),gt("YIELDMAT",t=>t>0,(t,n,s,o,e)=>{const r=n/100+o*t;return(1+s*t-r)/r/e});function Pt(t,n,s,o){const e=100*n/t.f,r=t.dsc/t.e;if(t.n===1)return(o+e)/(1+s/t.f*r)-e*t.a/t.e;const a=1+s/t.f;let c=o/a**(t.n-1+r);for(let f=0;f<t.n;f++)c+=e/a**(f+r);return c-e*t.a/t.e}y("PRICE",6,7,(t,n,s,o,e,r,a)=>{const c=p(s),f=p(o),i=p(e),u=tt(t,n,r,a);return d(c>=0&&f>=0&&i>0),Pt(u,c,f,i)}),y("YIELD",6,7,(t,n,s,o,e,r,a)=>{const c=p(s),f=p(o),i=p(e),u=tt(t,n,r,a);if(d(c>=0&&f>0&&i>0),u.n===1){const l=c/u.f,M=f/100+u.a/u.e*l;return(i/100+l-M)/M*(u.f*u.e/u.dsc)}return nt(l=>Pt(u,c,l,i)-f,.1,-u.f)});function Lt(t,n,s,o,e,r){const a=p(s),c=p(o),f=tt(t,n,e,r);d(a>=0&&c>=0);const i=1+c/f.f,u=100*a/f.f,l=f.dsc/f.e;let M=0,m=0;for(let I=0;I<f.n;I++){const b=I+l,R=(I===f.n-1?u+100:u)/i**b;M+=b*R,m+=R}return[M/m/f.f,i]}y("DURATION",5,6,(...t)=>Lt(...t)[0]),y("MDURATION",5,6,(...t)=>{const[n,s]=Lt(...t);return n/s});function Tt(t,n,s,o,e,r,a,c){const f=D(t),i=D(n),u=D(s),l=D(o),M=p(e),m=p(r),I=j(a),b=F(c);d(i>l&&l>f&&f>u&&M>=0&&m>0);const R=at(f,l,I,b),g=R.n===1?V(f,l,b):R.dsc,A=at(l,i,I,b).n,C=Z(l),U=12/I;let L=0,v=0;for(let k=0,w=l;;k++){const O=P(l,-(k+1)*U,C),S=b===1?w-O:R.e;L+=(O>u?S:V(u,w,b))/S;const ht=Math.max(u,O),Mt=Math.min(f,w);if(Mt>ht&&(v+=V(ht,Mt,b)/S),O<=u)break;w=O}const T=100*M/I,Y=R.n-1+g/R.e;return k=>{const w=1+k/I;let O=m/w**(A+Y)+T*L/w**Y;for(let S=1;S<=A;S++)O+=T/w**(S+Y);return O-T*v}}y("ODDFPRICE",8,9,(t,n,s,o,e,r,a,c,f)=>{const i=p(r),u=Tt(t,n,s,o,e,a,c,f);return d(i>=0),u(i)}),y("ODDFYIELD",8,9,(t,n,s,o,e,r,a,c,f)=>{const i=p(r),u=Tt(t,n,s,o,e,a,c,f);return d(i>0),nt(l=>u(l)-i,.1,-j(c))});function wt(t,n,s,o,e,r,a){const c=D(t),f=D(n),i=D(s),u=p(o),l=p(e),M=j(r),m=F(a);d(f>c&&c>i&&u>=0&&l>0);const I=12/M,b=Z(i);let R=0,g=0,A=0;for(let U=0;;U++){const L=P(i,U*I,b),v=P(i,(U+1)*I,b),T=m===0||m===4?360/M:v-L,Y=v>=f,k=Y?V(L,f,m):T;R+=k/T,v<c?g+=k/T:L<c&&(g+=V(L,c,m)/T);const w=Math.max(c,L),O=Math.min(f,v);if(O>w&&(A+=V(w,O,m)/T),Y)break}const C=100*u/M;return{income:l+R*C,interest:g*C,toGo:A,f:M}}y("ODDLPRICE",7,8,(t,n,s,o,e,r,a,c)=>{const f=p(e),i=wt(t,n,s,o,r,a,c);return d(f>=0),i.income/(1+i.toGo*f/i.f)-i.interest}),y("ODDLYIELD",7,8,(t,n,s,o,e,r,a,c)=>{const f=p(e),i=wt(t,n,s,o,r,a,c);d(f>0);const u=f+i.interest;return(i.income-u)/u*(i.f/i.toGo)});export{$ as days360,_ as yearFrac};
|