-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathArrayPlugin.ts
More file actions
262 lines (234 loc) · 9.57 KB
/
Copy pathArrayPlugin.ts
File metadata and controls
262 lines (234 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/**
* @license
* Copyright (c) 2025 Handsoncode. All rights reserved.
*/
import {ArraySize} from '../../ArraySize'
import {CellError, ErrorType} from '../../Cell'
import {ErrorMessage} from '../../error-message'
import {AstNodeType, ProcedureAst} from '../../parser'
import {coerceScalarToBoolean} from '../ArithmeticHelper'
import {InterpreterState} from '../InterpreterState'
import {InternalScalarValue, InterpreterValue} from '../InterpreterValue'
import {SimpleRangeValue} from '../../SimpleRangeValue'
import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin'
export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypecheck<ArrayPlugin> {
public static implementedFunctions: ImplementedFunctions = {
'ARRAYFORMULA': {
method: 'arrayformula',
sizeOfResultArrayMethod: 'arrayformulaArraySize',
enableArrayArithmeticForArguments: true,
parameters: [
{argumentType: FunctionArgumentType.ANY}
],
},
'ARRAY_CONSTRAIN': {
method: 'arrayconstrain',
sizeOfResultArrayMethod: 'arrayconstrainArraySize',
parameters: [
{argumentType: FunctionArgumentType.RANGE},
{argumentType: FunctionArgumentType.INTEGER, minValue: 1},
{argumentType: FunctionArgumentType.INTEGER, minValue: 1},
],
vectorizationForbidden: true,
},
'FILTER': {
method: 'filter',
sizeOfResultArrayMethod: 'filterArraySize',
enableArrayArithmeticForArguments: true,
parameters: [
{argumentType: FunctionArgumentType.RANGE},
{argumentType: FunctionArgumentType.RANGE},
],
repeatLastArgs: 1,
},
'VSTACK': {
method: 'vstack',
sizeOfResultArrayMethod: 'vstackArraySize',
enableArrayArithmeticForArguments: true,
parameters: [
{argumentType: FunctionArgumentType.RANGE},
],
repeatLastArgs: 1,
},
'HSTACK': {
method: 'hstack',
sizeOfResultArrayMethod: 'hstackArraySize',
enableArrayArithmeticForArguments: true,
parameters: [
{argumentType: FunctionArgumentType.RANGE},
],
repeatLastArgs: 1,
},
}
public arrayformula(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('ARRAYFORMULA'), (value) => value)
}
public arrayformulaArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize {
if (ast.args.length !== 1) {
return ArraySize.error()
}
const metadata = this.metadata('ARRAYFORMULA')
const subChecks = ast.args.map((arg) => this.arraySizeForAst(arg, new InterpreterState(state.formulaAddress, state.arraysFlag || (metadata?.enableArrayArithmeticForArguments ?? false))))
return subChecks[0]
}
public arrayconstrain(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('ARRAY_CONSTRAIN'), (range: SimpleRangeValue, numRows: number, numCols: number) => {
numRows = Math.min(numRows, range.height())
numCols = Math.min(numCols, range.width())
const data: InternalScalarValue[][] = range.data
const ret: InternalScalarValue[][] = []
for (let i = 0; i < numRows; i++) {
ret.push(data[i].slice(0, numCols))
}
return SimpleRangeValue.onlyValues(ret)
})
}
public arrayconstrainArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize {
if (ast.args.length !== 3) {
return ArraySize.error()
}
const metadata = this.metadata('ARRAY_CONSTRAIN')
const subChecks = ast.args.map((arg) => this.arraySizeForAst(arg, new InterpreterState(state.formulaAddress, state.arraysFlag || (metadata?.enableArrayArithmeticForArguments ?? false))))
let {height, width} = subChecks[0]
if (ast.args[1].type === AstNodeType.NUMBER) {
height = Math.min(height, ast.args[1].value)
}
if (ast.args[2].type === AstNodeType.NUMBER) {
width = Math.min(width, ast.args[2].value)
}
if (height < 1 || width < 1 || !Number.isInteger(height) || !Number.isInteger(width)) {
return ArraySize.error()
}
return new ArraySize(width, height)
}
public filter(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('FILTER'), (rangeVals: SimpleRangeValue, ...rangeFilters: SimpleRangeValue[]) => {
for (const filter of rangeFilters) {
if (rangeVals.width() !== filter.width() || rangeVals.height() !== filter.height()) {
return new CellError(ErrorType.NA, ErrorMessage.EqualLength)
}
}
if (rangeVals.width() > 1 && rangeVals.height() > 1) {
return new CellError(ErrorType.NA, ErrorMessage.WrongDimension)
}
const vals = rangeVals.data
const ret = []
for (let i = 0; i < rangeVals.height(); i++) {
const row = []
for (let j = 0; j < rangeVals.width(); j++) {
let ok = true
for (const filter of rangeFilters) {
const val = coerceScalarToBoolean(filter.data[i][j])
if (val !== true) {
ok = false
break
}
}
if (ok) {
row.push(vals[i][j])
}
}
if (row.length > 0) {
ret.push(row)
}
}
if (ret.length > 0) {
return SimpleRangeValue.onlyValues(ret)
} else {
return new CellError(ErrorType.NA, ErrorMessage.EmptyRange)
}
})
}
public filterArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize {
if (ast.args.length <= 1) {
return ArraySize.error()
}
const metadata = this.metadata('FILTER')
const subChecks = ast.args.map((arg) => this.arraySizeForAst(arg, new InterpreterState(state.formulaAddress, state.arraysFlag || (metadata?.enableArrayArithmeticForArguments ?? false))))
const width = Math.max(...(subChecks).map(val => val.width))
const height = Math.max(...(subChecks).map(val => val.height))
return new ArraySize(width, height)
}
/**
* Corresponds to VSTACK(array1, [array2], ...)
*
* Stacks the input arrays vertically, one on top of another, into a single array.
* The result has as many rows as the inputs combined and as many columns as the
* widest input. Cells of narrower inputs are padded on the right with the #N/A
* error, matching the behaviour of Excel and Google Sheets.
*
* @param ast
* @param state
*/
public vstack(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('VSTACK'), (...ranges: SimpleRangeValue[]) => {
const width = Math.max(...ranges.map(range => range.width()))
const result: InternalScalarValue[][] = []
for (const range of ranges) {
for (const row of range.data) {
result.push(this.padRowToWidth(row, width))
}
}
return SimpleRangeValue.onlyValues(result)
})
}
public vstackArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize {
if (ast.args.length < 1) {
return ArraySize.error()
}
const subChecks = this.stackSubChecks(ast, state, 'VSTACK')
const width = Math.max(...subChecks.map(size => size.width))
const height = subChecks.reduce((total, size) => total + size.height, 0)
return new ArraySize(width, height)
}
/**
* Corresponds to HSTACK(array1, [array2], ...)
*
* Stacks the input arrays horizontally, side by side, into a single array.
* The result has as many columns as the inputs combined and as many rows as the
* tallest input. Cells of shorter inputs are padded at the bottom with the #N/A
* error, matching the behaviour of Excel and Google Sheets.
*
* @param ast
* @param state
*/
public hstack(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('HSTACK'), (...ranges: SimpleRangeValue[]) => {
const height = Math.max(...ranges.map(range => range.height()))
const result: InternalScalarValue[][] = [...Array(height).keys()].map(() => [])
for (const range of ranges) {
const data = range.data
for (let row = 0; row < height; row++) {
const sourceRow = row < data.length ? data[row] : undefined
for (let col = 0; col < range.width(); col++) {
result[row].push(sourceRow !== undefined ? sourceRow[col] : new CellError(ErrorType.NA, ErrorMessage.ValueNotFound))
}
}
}
return SimpleRangeValue.onlyValues(result)
})
}
public hstackArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize {
if (ast.args.length < 1) {
return ArraySize.error()
}
const subChecks = this.stackSubChecks(ast, state, 'HSTACK')
const width = subChecks.reduce((total, size) => total + size.width, 0)
const height = Math.max(...subChecks.map(size => size.height))
return new ArraySize(width, height)
}
private stackSubChecks(ast: ProcedureAst, state: InterpreterState, functionName: 'VSTACK' | 'HSTACK'): ArraySize[] {
const metadata = this.metadata(functionName)
return ast.args.map((arg) => this.arraySizeForAst(arg, new InterpreterState(state.formulaAddress, state.arraysFlag || (metadata?.enableArrayArithmeticForArguments ?? false))))
}
private padRowToWidth(row: InternalScalarValue[], width: number): InternalScalarValue[] {
if (row.length >= width) {
return row.slice(0, width)
}
const padded = row.slice()
while (padded.length < width) {
padded.push(new CellError(ErrorType.NA, ErrorMessage.ValueNotFound))
}
return padded
}
}