diff --git a/CHANGELOG.md b/CHANGELOG.md index 0490fef05..63948009d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Added the `CHOOSECOLS` dynamic-array function. [#1734](https://github.com/handsontable/hyperformula/pull/1734) - Added the `CHOOSEROWS` dynamic-array function. [#1827](https://github.com/handsontable/hyperformula/pull/1827) - Added the `ACCRINTM`, `DISC`, `INTRATE`, `PRICEDISC`, `RECEIVED` and `YIELDDISC` functions, which return the accrued interest, discount rate, interest rate, price, amount received and yield of discounted securities and securities that pay interest at maturity. [#1799](https://github.com/handsontable/hyperformula/pull/1799) +- Added the `TAKE` dynamic-array function. [#1722](https://github.com/handsontable/hyperformula/pull/1722) ### Changed diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index 319b1f3f4..ca00d2eac 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -126,6 +126,12 @@ To remove the differences, create [custom implementations](custom-functions.md) | CHOOSECOLS | =COLUMNS(CHOOSECOLS(A1:C3, {1,2})) | 1 (only the first index of an array is used) | 2 | 2 | | CHOOSEROWS | =CHOOSEROWS(Data!1:1, 1) | Spills the source sheet's used columns from column A; returns SPILL outside column A. | Returns every column of the source sheet's row. | Returns all 16,384 columns of the row. | | CHOOSEROWS | =CHOOSEROWS(Data!A:A, -1) | Returns the source sheet's last used row. | Returns the source sheet's last row. | Returns row 1,048,576. | +| TAKE | =TAKE(A1:A3, 0) | N/A | No such function. | CALC | +| TAKE | =TAKE(Data!A:A, , 1) | Spills to the source sheet's current height from row 1; returns SPILL below row 1. | No such function. | Spills all 1,048,576 rows from row 1, with blank source cells as 0; returns SPILL below row 1. | +| TAKE | =SUM(TAKE(A:A, -2))
where A1:A5: 1, 2, 3, 4, 5 | 9 (counts back from the last used row) | No such function. | 0 (counts back from the last row of the sheet) | +| TAKE | =SUM(TAKE(1:1, , -2))
where A1:C1: 1, 2, 3 | 5 (counts back from the last used column) | No such function. | 0 (counts back from the last column of the sheet) | +| TAKE | =TAKE(A:A, B1) in C5,
where A1:A5: 1, 2, 3, 4, 5 and B1 = 6 | Returns SPILL: the result is taller than the area reserved for it below row 1 (5 rows, the source's height). A count that fits, such as 2, spills 1, 2. A negative count, such as -2, counts back from the end of the reserved area and returns 2 empty cells. | No such function. | Spills 1, 2, 3, 4, 5, 0 into C5:C10. With B1 = -2, spills 0, 0. | +| TAKE | =TAKE(A1:C3, NA()) | Fills the whole area reserved for the array (here 3x3) with N/A. | No such function. | A single N/A error. | | INT | =INT(-8.9) | -8 | -9 | -9 | | ISEVEN | =ISEVEN(2.5) | FALSE | TRUE | TRUE | | ISODD | =ISODD(3.5) | FALSE | TRUE | TRUE | diff --git a/hyperformula/src/error-message.ts b/hyperformula/src/error-message.ts index 9f0ef381d..46773a8b5 100644 --- a/hyperformula/src/error-message.ts +++ b/hyperformula/src/error-message.ts @@ -70,6 +70,7 @@ export class ErrorMessage { public static IncorrectDateTime = 'String does not represent correct DateTime.' public static CharacterCodeBounds = 'Character code out of bounds.' public static NonZero = 'Argument cannot be 0.' + public static ZeroRowOrColumnCount = 'Row or column count cannot be zero.' public static LessThanOne = 'Argument cannot be less than 1.' public static WeekendString = 'Incorrect weekend bitmask string.' public static InvalidRoman = 'Invalid roman numeral.' diff --git a/hyperformula/src/i18n/languages/csCZ.ts b/hyperformula/src/i18n/languages/csCZ.ts index 84680279a..1ff1a4173 100644 --- a/hyperformula/src/i18n/languages/csCZ.ts +++ b/hyperformula/src/i18n/languages/csCZ.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'ODPIS.NELIN', T: 'T', + TAKE: 'VZÍT', TAN: 'TG', TANH: 'TGH', TBILLEQ: 'TBILLEQ', diff --git a/hyperformula/src/i18n/languages/daDK.ts b/hyperformula/src/i18n/languages/daDK.ts index f038bacff..ffddc6428 100644 --- a/hyperformula/src/i18n/languages/daDK.ts +++ b/hyperformula/src/i18n/languages/daDK.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'ÅRSAFSKRIVNING', T: 'T', + TAKE: 'TAG', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'STATSOBLIGATION', diff --git a/hyperformula/src/i18n/languages/deDE.ts b/hyperformula/src/i18n/languages/deDE.ts index 281d7bee7..c40ef92f0 100644 --- a/hyperformula/src/i18n/languages/deDE.ts +++ b/hyperformula/src/i18n/languages/deDE.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'DIA', T: 'T', + TAKE: 'ÜBERNEHMEN', TAN: 'TAN', TANH: 'TANHYP', TBILLEQ: 'TBILLÄQUIV', diff --git a/hyperformula/src/i18n/languages/enGB.ts b/hyperformula/src/i18n/languages/enGB.ts index 261dc13a7..8e402f105 100644 --- a/hyperformula/src/i18n/languages/enGB.ts +++ b/hyperformula/src/i18n/languages/enGB.ts @@ -238,6 +238,7 @@ const dictionary: RawTranslationPackage = { SWITCH: 'SWITCH', SYD: 'SYD', T: 'T', + TAKE: 'TAKE', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'TBILLEQ', diff --git a/hyperformula/src/i18n/languages/esES.ts b/hyperformula/src/i18n/languages/esES.ts index e8dfeb686..3607c1df6 100644 --- a/hyperformula/src/i18n/languages/esES.ts +++ b/hyperformula/src/i18n/languages/esES.ts @@ -236,6 +236,7 @@ export const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'SYD', T: 'T', + TAKE: 'TOMAR', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'LETRA.DE.TEST.EQV.A.BONO', diff --git a/hyperformula/src/i18n/languages/fiFI.ts b/hyperformula/src/i18n/languages/fiFI.ts index 33b280490..5006d8c8a 100644 --- a/hyperformula/src/i18n/languages/fiFI.ts +++ b/hyperformula/src/i18n/languages/fiFI.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'VUOSIPOISTO', T: 'T', + TAKE: 'OTA', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'OBLIG.TUOTTOPROS', diff --git a/hyperformula/src/i18n/languages/frFR.ts b/hyperformula/src/i18n/languages/frFR.ts index d0dbfa97b..232a3e9f6 100644 --- a/hyperformula/src/i18n/languages/frFR.ts +++ b/hyperformula/src/i18n/languages/frFR.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'SYD', T: 'T', + TAKE: 'PRENDRE', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'TAUX.ESCOMPTE.R', diff --git a/hyperformula/src/i18n/languages/huHU.ts b/hyperformula/src/i18n/languages/huHU.ts index d65fb9d3e..0ef7bd8d6 100644 --- a/hyperformula/src/i18n/languages/huHU.ts +++ b/hyperformula/src/i18n/languages/huHU.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'ÉSZÖ', T: 'T', + TAKE: 'ÁTHELYEZ', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'KJEGY.EGYENÉRT', diff --git a/hyperformula/src/i18n/languages/idID.ts b/hyperformula/src/i18n/languages/idID.ts index 54a722318..db6fb0b3b 100644 --- a/hyperformula/src/i18n/languages/idID.ts +++ b/hyperformula/src/i18n/languages/idID.ts @@ -238,6 +238,7 @@ const dictionary: RawTranslationPackage = { SWITCH: 'BERALIH', SYD: 'SYD', T: 'T', + TAKE: 'TAKE', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'TBILL.SAMA', diff --git a/hyperformula/src/i18n/languages/itIT.ts b/hyperformula/src/i18n/languages/itIT.ts index b8d53a947..e3a777451 100644 --- a/hyperformula/src/i18n/languages/itIT.ts +++ b/hyperformula/src/i18n/languages/itIT.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'AMMORT.ANNUO', T: 'T', + TAKE: 'INCLUDI', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'BOT.EQUIV', diff --git a/hyperformula/src/i18n/languages/nbNO.ts b/hyperformula/src/i18n/languages/nbNO.ts index 77d1e1c0d..bee10a35c 100644 --- a/hyperformula/src/i18n/languages/nbNO.ts +++ b/hyperformula/src/i18n/languages/nbNO.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'ÅRSAVS', T: 'T', + TAKE: 'TA', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'TBILLEKV', diff --git a/hyperformula/src/i18n/languages/nlNL.ts b/hyperformula/src/i18n/languages/nlNL.ts index ab9c6ddb7..35664fb92 100644 --- a/hyperformula/src/i18n/languages/nlNL.ts +++ b/hyperformula/src/i18n/languages/nlNL.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'SYD', T: 'T', + TAKE: 'NEMEN', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'SCHATK.OBL', diff --git a/hyperformula/src/i18n/languages/plPL.ts b/hyperformula/src/i18n/languages/plPL.ts index 0dcb5d974..a92df4bc9 100644 --- a/hyperformula/src/i18n/languages/plPL.ts +++ b/hyperformula/src/i18n/languages/plPL.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: 'PRZEŁĄCZ', SYD: 'SYD', T: 'T', + TAKE: 'WYCINEK', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'RENT.EKW.BS', diff --git a/hyperformula/src/i18n/languages/ptPT.ts b/hyperformula/src/i18n/languages/ptPT.ts index e9b35c70f..cbb0e50e7 100644 --- a/hyperformula/src/i18n/languages/ptPT.ts +++ b/hyperformula/src/i18n/languages/ptPT.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'SDA', T: 'T', + TAKE: 'INCLUIR', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'OTN', diff --git a/hyperformula/src/i18n/languages/ruRU.ts b/hyperformula/src/i18n/languages/ruRU.ts index e56d54c14..5d6864db9 100644 --- a/hyperformula/src/i18n/languages/ruRU.ts +++ b/hyperformula/src/i18n/languages/ruRU.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'АСЧ', T: 'Т', + TAKE: 'ВЗЯТЬ', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'РАВНОКЧЕК', diff --git a/hyperformula/src/i18n/languages/svSE.ts b/hyperformula/src/i18n/languages/svSE.ts index 2b8430480..f47ffcd99 100644 --- a/hyperformula/src/i18n/languages/svSE.ts +++ b/hyperformula/src/i18n/languages/svSE.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'ÅRSAVSKR', T: 'T', + TAKE: 'TA', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'SSVXEKV', diff --git a/hyperformula/src/i18n/languages/trTR.ts b/hyperformula/src/i18n/languages/trTR.ts index 26a86de4a..da2796342 100644 --- a/hyperformula/src/i18n/languages/trTR.ts +++ b/hyperformula/src/i18n/languages/trTR.ts @@ -236,6 +236,7 @@ const dictionary: RawTranslationPackage = { SWITCH: '', SYD: 'YAT', T: 'T', + TAKE: 'AL', TAN: 'TAN', TANH: 'TANH', TBILLEQ: 'HTAHEŞ', diff --git a/hyperformula/src/interpreter/Interpreter.ts b/hyperformula/src/interpreter/Interpreter.ts index 8cc40d8f3..ab6a60a4f 100644 --- a/hyperformula/src/interpreter/Interpreter.ts +++ b/hyperformula/src/interpreter/Interpreter.ts @@ -31,6 +31,7 @@ import { import {CriterionBuilder} from './Criterion' import {FunctionRegistry} from './FunctionRegistry' import {InterpreterState} from './InterpreterState' +import {FunctionPluginDefinition} from './plugin/FunctionPlugin' import { cloneNumber, EmptyValue, @@ -65,6 +66,18 @@ export class Interpreter { this.functionCallLicenseGate = new FunctionCallLicenseGate(config, functionRegistry) } + /** + * Checks whether a function is implemented by a specific plugin in this interpreter's engine instance. + * + * @param {string} functionId - The canonical function identifier. + * @param {FunctionPluginDefinition} plugin - The plugin class to compare with the registered implementation. + * @returns {boolean} `true` when the function is implemented by the given plugin class. + * @internal + */ + public isFunctionImplementedBy(functionId: string, plugin: FunctionPluginDefinition): boolean { + return this.functionRegistry.getFunctionPlugin(functionId) === plugin + } + public evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { let val = this.evaluateAstWithoutPostprocessing(ast, state) if (isExtendedNumber(val)) { diff --git a/hyperformula/src/interpreter/functionMetadata/categories/lookup-and-reference.ts b/hyperformula/src/interpreter/functionMetadata/categories/lookup-and-reference.ts index eadb3e9bf..d424eaa20 100644 --- a/hyperformula/src/interpreter/functionMetadata/categories/lookup-and-reference.ts +++ b/hyperformula/src/interpreter/functionMetadata/categories/lookup-and-reference.ts @@ -135,6 +135,13 @@ export const LOOKUP_AND_REFERENCE_DOCS: Record = { documentationUrl: 'https://hyperformula.handsontable.com/docs/guide/built-in-functions.html', examples: ['=SORT(A1:A10)', '=SORT(A1:B10, 2, -1)'], }, + TAKE: { + category: 'Lookup and reference', + shortDescription: 'Returns specified rows or columns from the beginning or end of an array.', + parameters: [{name: 'array', description: 'The array or range from which to take rows or columns.'}, {name: 'rows', description: 'The number of rows to take; a negative value takes rows from the end. An empty argument keeps all rows.'}, {name: 'columns', description: 'The number of columns to take; a negative value takes columns from the end. When omitted or empty, all columns are kept.'}], + documentationUrl: 'https://hyperformula.handsontable.com/docs/guide/built-in-functions.html', + examples: ['=TAKE(A1:C5, 2)', '=TAKE(A1:C5, -2, -1)', '=TAKE(A1:C5, , 2)'], + }, TRANSPOSE: { category: 'Lookup and reference', shortDescription: 'Transposes the rows and columns of an array.', diff --git a/hyperformula/src/interpreter/plugin/ArrayPlugin.ts b/hyperformula/src/interpreter/plugin/ArrayPlugin.ts index 5e88e5200..11faebea6 100644 --- a/hyperformula/src/interpreter/plugin/ArrayPlugin.ts +++ b/hyperformula/src/interpreter/plugin/ArrayPlugin.ts @@ -12,6 +12,7 @@ import {coerceScalarToBoolean} from '../ArithmeticHelper' import {InterpreterState} from '../InterpreterState' import {getRawValue, InternalScalarValue, InterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../../SimpleRangeValue' +import {BooleanPlugin} from './BooleanPlugin' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' /** A CHOOSECOLS or CHOOSEROWS index classified without evaluating a formula expression. */ @@ -26,6 +27,24 @@ type ChooseAxis = 'columns' | 'rows' /** The functions that share the CHOOSECOLS and CHOOSEROWS implementation. */ type ChooseFunctionName = 'CHOOSECOLS' | 'CHOOSEROWS' +/** + * Classifies a TAKE count expression whose value may be known before evaluation. + * + * @internal + */ +type TakeLiteralNumber = + | {kind: 'value', value: number} + | {kind: 'invalid'} + | {kind: 'unresolved'} + +/** + * Distinguishes an omitted or empty TAKE count from an expression whose value + * cannot be resolved during static result-size prediction. + * + * @internal + */ +type TakeLiteralDimension = TakeLiteralNumber | {kind: 'unbounded'} + export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypecheck { /** * Classifies an index literal for static CHOOSECOLS and CHOOSEROWS result-size prediction. @@ -68,6 +87,141 @@ export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypeche return {kind: 'unresolved'} } + /** + * Evaluates the dependency-free subset of TAKE count expressions used for + * static result-size prediction. + * + * @param {Ast | undefined} argument - The count expression to inspect before evaluation. + * @returns {TakeLiteralNumber} The constant value, an invalid-literal marker, or an unresolved marker. + * @internal + */ + private parseTakeLiteralNumber(argument: Ast | undefined): TakeLiteralNumber { + if (argument?.type === AstNodeType.NUMBER) { + return {kind: 'value', value: argument.value} + } + + if (argument?.type === AstNodeType.STRING) { + const coercedValue = this.arithmeticHelper.coerceToMaybeNumber(argument.value) + if (coercedValue === undefined) { + return {kind: 'invalid'} + } + return {kind: 'value', value: getRawValue(coercedValue)} + } + + if (argument?.type === AstNodeType.ERROR || argument?.type === AstNodeType.ERROR_WITH_RAW_INPUT) { + return {kind: 'invalid'} + } + + if (argument?.type === AstNodeType.PLUS_UNARY_OP || argument?.type === AstNodeType.MINUS_UNARY_OP) { + const dimension = this.parseTakeLiteralNumber(argument.value) + if (dimension.kind !== 'value') { + return dimension + } + return {kind: 'value', value: argument.type === AstNodeType.MINUS_UNARY_OP ? -dimension.value : dimension.value} + } + + if (argument?.type === AstNodeType.PARENTHESIS) { + return this.parseTakeLiteralNumber(argument.expression) + } + + if (argument?.type === AstNodeType.PERCENT_OP) { + const dimension = this.parseTakeLiteralNumber(argument.value) + if (dimension.kind !== 'value') { + return dimension + } + return {kind: 'value', value: getRawValue(this.arithmeticHelper.unaryPercent(dimension.value))} + } + + if ( + argument?.type === AstNodeType.FUNCTION_CALL + && argument.args.length === 0 + && (argument.procedureName === 'TRUE' || argument.procedureName === 'FALSE') + && this.interpreter.isFunctionImplementedBy(argument.procedureName, BooleanPlugin) + ) { + return {kind: 'value', value: argument.procedureName === 'TRUE' ? 1 : 0} + } + + if ( + argument?.type === AstNodeType.PLUS_OP + || argument?.type === AstNodeType.MINUS_OP + || argument?.type === AstNodeType.TIMES_OP + || argument?.type === AstNodeType.DIV_OP + || argument?.type === AstNodeType.POWER_OP + ) { + const left = this.parseTakeLiteralNumber(argument.left) + const right = this.parseTakeLiteralNumber(argument.right) + if (left.kind === 'invalid' || right.kind === 'invalid') { + return {kind: 'invalid'} + } + if (left.kind === 'value' && right.kind === 'value') { + let value: number + switch (argument.type) { + case AstNodeType.PLUS_OP: + value = this.arithmeticHelper.addWithEpsilonRaw(left.value, right.value) + break + case AstNodeType.MINUS_OP: + value = getRawValue(this.arithmeticHelper.subtract(left.value, right.value)) + break + case AstNodeType.TIMES_OP: + value = getRawValue(this.arithmeticHelper.multiply(left.value, right.value)) + break + case AstNodeType.DIV_OP: { + const quotient = this.arithmeticHelper.divide(left.value, right.value) + if (quotient instanceof CellError) { + return {kind: 'invalid'} + } + value = getRawValue(quotient) + break + } + case AstNodeType.POWER_OP: + value = this.arithmeticHelper.pow(left.value, right.value) + break + } + return Number.isFinite(value) ? {kind: 'value', value} : {kind: 'invalid'} + } + } + + return {kind: 'unresolved'} + } + + /** + * Converts a statically resolved TAKE count into its output dimension. + * + * @param {Ast | undefined} argument - The count expression to classify. + * @returns {TakeLiteralDimension} The non-negative truncated dimension or its invalid, unresolved, or unbounded classification. + * @internal + */ + private parseTakeLiteralDimension(argument: Ast | undefined): TakeLiteralDimension { + if (argument === undefined || argument.type === AstNodeType.EMPTY) { + return {kind: 'unbounded'} + } + + const dimension = this.parseTakeLiteralNumber(argument) + return dimension.kind === 'value' + ? {kind: 'value', value: Math.abs(Math.trunc(dimension.value))} + : dimension + } + + /** + * Resolves a direct TAKE source reference without evaluating its values. + * The range supplies materialized dimensions only; spill placement never + * depends on its sheet. + * + * @param {Ast} argument - The source expression to inspect. + * @param {InterpreterState} state - The formula state used to resolve relative addresses. + * @returns {AbsoluteCellRange | undefined} The source range, or `undefined` for a computed array. + * @internal + */ + private takeSourceRange(argument: Ast, state: InterpreterState): AbsoluteCellRange | undefined { + if (argument.type === AstNodeType.PARENTHESIS) { + return this.takeSourceRange(argument.expression, state) + } + if (argument.type === AstNodeType.CELL_RANGE || argument.type === AstNodeType.COLUMN_RANGE || argument.type === AstNodeType.ROW_RANGE) { + return AbsoluteCellRange.fromAstOrUndef(argument, state.formulaAddress) + } + return undefined + } + public static implementedFunctions: ImplementedFunctions = { 'ARRAYFORMULA': { method: 'arrayformula', @@ -119,6 +273,17 @@ export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypeche repeatLastArgs: 1, vectorizationForbidden: true, }, + 'TAKE': { + method: 'take', + sizeOfResultArrayMethod: 'takeArraySize', + enableArrayArithmeticForArguments: true, + parameters: [ + {argumentType: FunctionArgumentType.RANGE}, + {argumentType: FunctionArgumentType.NUMBER}, + {argumentType: FunctionArgumentType.NUMBER, optionalArg: true, defaultValue: Number.POSITIVE_INFINITY, emptyAsDefault: true}, + ], + vectorizationForbidden: true, + }, 'VSTACK': { method: 'vstack', sizeOfResultArrayMethod: 'vstackArraySize', @@ -457,6 +622,126 @@ export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypeche && sourceAst.type !== AstNodeType.CELL_RANGE } + /** + * Corresponds to TAKE(array, rows, [columns]). + * + * Returns rows and columns from the beginning or end of the source array. + * Syntactically empty dimensions keep all rows or columns. Counts that + * evaluate to zero return a #N/A error. + * + * @param {ProcedureAst} ast - The parsed TAKE call. + * @param {InterpreterState} state - The current formula evaluation state. + * @returns {InterpreterValue} The selected source values or a spreadsheet error. + */ + public take(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + // rows is required but may be left empty, as in TAKE(array, , columns), which keeps + // every row; a default would make the metadata report it as optional. + const rowsLeftEmpty = ast.args[1]?.type === AstNodeType.EMPTY + + return this.runFunction(ast.args, state, this.metadata('TAKE'), + (range: SimpleRangeValue, rows: number, columns: number) => { + const sourceHeight = range.height() + const sourceWidth = range.width() + const requestedRows = rowsLeftEmpty ? Number.POSITIVE_INFINITY : Math.trunc(rows) + const requestedColumns = Math.trunc(columns) + + if (requestedRows === 0 || requestedColumns === 0) { + return new CellError(ErrorType.NA, ErrorMessage.ZeroRowOrColumnCount) + } + + if (sourceHeight === 0 || sourceWidth === 0) { + return new CellError(ErrorType.NA, ErrorMessage.EmptyRange) + } + + const rowsToTake = Math.min(Math.abs(requestedRows), sourceHeight) + const columnsToTake = Math.min(Math.abs(requestedColumns), sourceWidth) + const startRow = requestedRows > 0 ? 0 : sourceHeight - rowsToTake + const startColumn = requestedColumns > 0 ? 0 : sourceWidth - columnsToTake + const sourceRange = range.range + + if (sourceRange !== undefined) { + // Keep address-backed ranges lazy to avoid materializing cells outside the TAKE result. + const resultRange = AbsoluteCellRange.spanFrom( + sourceRange.getAddress(startColumn, startRow), + columnsToTake, + rowsToTake, + ) + const result = SimpleRangeValue.onlyRange(resultRange, this.dependencyGraph).data + return SimpleRangeValue.onlyValues(result) + } + + const result = range.data + .slice(startRow, startRow + rowsToTake) + .map(row => row.slice(startColumn, startColumn + columnsToTake)) + + return SimpleRangeValue.onlyValues(result) + } + ) + } + + /** + * Calculates the spilled array size of TAKE using the source dimensions as + * the upper bound. Finite counts are capped at the configured sheet limits. + * Direct references that remain unbounded use their effective dimensions, + * while computed sources use the configured limit. Unbounded dimensions are + * valid only at the corresponding output-sheet edge. + * + * An unbounded result anchored away from the required sheet edge retains its + * unbounded predicted dimension so array-space validation returns a spill + * error without evaluating TAKE as a scalar formula. + * + * @param {ProcedureAst} ast - The parsed TAKE call. + * @param {InterpreterState} state - The formula state whose address anchors the spill. + * @returns {ArraySize} The predicted result dimensions or an invalid size. + */ + public takeArraySize(ast: ProcedureAst, state: InterpreterState): ArraySize { + if (ast.args.length < 2 || ast.args.length > 3) { + return ArraySize.error() + } + + const metadata = this.metadata('TAKE') + const sourceSize = this.arraySizeForAst( + ast.args[0], + new InterpreterState(state.formulaAddress, state.arraysFlag || (metadata?.enableArrayArithmeticForArguments ?? false)), + ) + + const rowDimension = this.parseTakeLiteralDimension(ast.args[1]) + const columnDimension = this.parseTakeLiteralDimension(ast.args[2]) + + const hasZeroDimension = (rowDimension.kind === 'value' && rowDimension.value === 0) + || (columnDimension.kind === 'value' && columnDimension.value === 0) + + if (rowDimension.kind === 'invalid' || columnDimension.kind === 'invalid' || hasZeroDimension) { + return ArraySize.error() + } + + const height = rowDimension.kind === 'value' + ? Math.min(sourceSize.height, rowDimension.value, this.config.maxRows) + : sourceSize.height + const width = columnDimension.kind === 'value' + ? Math.min(sourceSize.width, columnDimension.value, this.config.maxColumns) + : sourceSize.width + const sourceRange = this.takeSourceRange(ast.args[0], state) + const startsBelowFirstRow = rowDimension.kind === 'unbounded' && !Number.isFinite(height) && state.formulaAddress.row !== 0 + const startsRightOfFirstColumn = columnDimension.kind === 'unbounded' && !Number.isFinite(width) && state.formulaAddress.col !== 0 + const effectiveHeight = !Number.isFinite(height) + ? sourceRange?.effectiveHeight(this.dependencyGraph) ?? this.config.maxRows + : height + const effectiveWidth = !Number.isFinite(width) + ? sourceRange?.effectiveWidth(this.dependencyGraph) ?? this.config.maxColumns + : width + + if (startsBelowFirstRow || startsRightOfFirstColumn) { + return new ArraySize(width, height) + } + + if (effectiveHeight < 1 || effectiveWidth < 1) { + return ArraySize.error() + } + + return new ArraySize(effectiveWidth, effectiveHeight) + } + /** * Corresponds to VSTACK(array1, [array2], ...) * diff --git a/hyperformula/src/license/functionCapabilities.ts b/hyperformula/src/license/functionCapabilities.ts index 73852dc95..b394b86d8 100644 --- a/hyperformula/src/license/functionCapabilities.ts +++ b/hyperformula/src/license/functionCapabilities.ts @@ -97,8 +97,8 @@ const UNGROUPED_FUNCTIONS = [ 'RSQ', 'SEC', 'SECH', 'SERIESSUM', 'SHEET', 'SHEETS', 'SINH', 'SKEW', 'SKEW.P', 'SLOPE', 'SPLIT', 'SQRTPI', 'STANDARDIZE', 'STEYX', 'SUMX2MY2', 'SUMX2PY2', 'SYD', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', - 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TIMEVALUE', 'TYPE', 'UNICODE', 'VALUETOTEXT', - 'VARA', 'VARPA', 'WEIBULL.DIST', 'WORKDAY.INTL', 'YIELDDISC', 'Z.TEST', + 'TAKE', 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TIMEVALUE', 'TYPE', 'UNICODE', 'VALUETOTEXT', 'VARA', + 'VARPA', 'WEIBULL.DIST', 'WORKDAY.INTL', 'YIELDDISC', 'Z.TEST', ] /**