From 2889c31a91b7bd48d288dd0f5b2aedd3e2003d49 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 23 Nov 2022 10:26:11 +0100 Subject: [PATCH 01/29] Start writing a custom function example for GREET() --- docs/guide/custom-functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 2c29bad571..5243492e86 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -7,7 +7,7 @@ Expand the function library of your application, by adding custom functions. ## Add a custom function -As an example, let's create a function that returns the number of letters in the word "HyperFormula". +As an example, let's create a function that accepts a username as a string argument and returns a personalized greeting. - ### 1. Create a function plugin Import `FunctionPlugin`, and extend it with a new class. For example: @@ -108,10 +100,6 @@ export class MyCustomPlugin extends FunctionPlugin { state, this.metadata('GREET'), (firstName) => { - if (!firstName) { - return new CellError('VALUE', 'The argument of the GREET function must be a non-empty string.'); - } - return `👋 Hello, ${firstName}!`; }, ); @@ -149,6 +137,8 @@ console.log(result); ### Full example +The complete implementation of this custom function is also included in the [demo](#working-demo). + ```js import { FunctionPlugin, CellError } from 'hyperformula'; @@ -159,10 +149,6 @@ export class MyCustomPlugin extends FunctionPlugin { state, this.metadata('GREET'), (firstName) => { - if (!firstName) { - return new CellError('VALUE', 'The argument of the GREET function must be a non-empty string.'); - } - return `👋 Hello, ${firstName}!`; }, ); @@ -173,7 +159,7 @@ MyCustomPlugin.implementedFunctions = { GREET: { method: 'greet', parameters: [ - {argumentType: 'STRING'} + { argumentType: 'STRING' } ], } }; @@ -187,31 +173,52 @@ MyCustomPlugin.translations = { } }; - HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); ``` +## Advanced custom function example + +In more advanced example we'll create a function that takes a range of numbers and returns the range of the same size with all the numbers doubled. + +### Accept a range argument + +`SimpleRangeValue` + +### Work with different value types + +`InternalScalarValue` + +### Validate the arguments + +`CellError` + +[error handling](#returning-errors) + +### Return an array of data + +`arraySizeMethod` +`ArraySize` + ### Test your function -You may add some unit tests to make sure that your custom function works correctly using one of the javascript testing libraries. +You may add unit tests to make sure that your custom function works correctly using one of the javascript testing libraries. ```js -describe('GREET function', () => { - it('works for a non-empty string', () => { - HyperFormula.registerFunctionPlugin(GreetingsPlugin, GreetingsPlugin.translations); - const engine = HyperFormula.buildFromArray([['Anthony', '=GREET(A1)']], { licenseKey: 'gpl-v3' }); - expect(engine.getCellValue({ sheet: 0, row: 0, col: 1 })).toEqual('👋 Hello, Anthony!'); - }); - - it('returns #VALUE! error for empty string', () => { - HyperFormula.registerFunctionPlugin(GreetingsPlugin, GreetingsPlugin.translations); - const engine = HyperFormula.buildFromArray([['', '=GREET(A1)']], { licenseKey: 'gpl-v3' }); - expect(engine.getCellValueType({ sheet: 0, row: 0, col: 1 })).toEqual('ERROR'); - expect(engine.getCellValue({ sheet: 0, row: 0, col: 1 }).value).toEqual('#VALUE!'); - }); -}); +// TODO: unit tests for DOUBLE_RANGE ``` +## Working demo + +This demo contains the implementation of both `GREET` and `DOUBLE_RANGE` custom functions. + + + ## Custom function options You can set the following options for your function: @@ -315,6 +322,8 @@ MyFunctionPlugin.translations = { ## Function name translations +// TODO: merge this section with the simple custom function tutorial + You can configure the name of your function with multiple translations. Your end users call your function by referring to those translations. From f1615da8da43f7fa7fe754dfde96d15fa94aa71d Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 13 Dec 2022 14:11:22 +0100 Subject: [PATCH 12/29] Move SimpleRangeValue from ./src/interpreter to ./src so that the typedoc documentation is generated for it --- src/ArrayValue.ts | 2 +- src/Cell.ts | 2 +- src/ContentChanges.ts | 2 +- src/DependencyGraph/DependencyGraph.ts | 2 +- src/Evaluator.ts | 2 +- src/Exporter.ts | 2 +- src/Lookup/AdvancedFind.ts | 2 +- src/Lookup/ColumnBinarySearch.ts | 2 +- src/Lookup/ColumnIndex.ts | 2 +- src/Lookup/RowSearchStrategy.ts | 2 +- src/Lookup/SearchStrategy.ts | 2 +- src/{interpreter => }/SimpleRangeValue.ts | 13 +++++++------ src/index.ts | 2 +- src/interpreter/ArithmeticHelper.ts | 2 +- src/interpreter/CriterionFunctionCompute.ts | 2 +- src/interpreter/Interpreter.ts | 2 +- src/interpreter/InterpreterValue.ts | 2 +- src/interpreter/plugin/ArrayPlugin.ts | 2 +- .../plugin/ConditionalAggregationPlugin.ts | 2 +- src/interpreter/plugin/DateTimePlugin.ts | 2 +- src/interpreter/plugin/FinancialPlugin.ts | 2 +- src/interpreter/plugin/FunctionPlugin.ts | 2 +- src/interpreter/plugin/InformationPlugin.ts | 2 +- src/interpreter/plugin/LookupPlugin.ts | 2 +- src/interpreter/plugin/MathPlugin.ts | 2 +- src/interpreter/plugin/MatrixPlugin.ts | 2 +- src/interpreter/plugin/MedianPlugin.ts | 2 +- src/interpreter/plugin/NumericAggregationPlugin.ts | 2 +- .../plugin/StatisticalAggregationPlugin.ts | 2 +- src/interpreter/plugin/SumprodPlugin.ts | 2 +- test/content-changes.spec.ts | 2 +- 31 files changed, 37 insertions(+), 36 deletions(-) rename src/{interpreter => }/SimpleRangeValue.ts (94%) diff --git a/src/ArrayValue.ts b/src/ArrayValue.ts index b87007c340..d42ff0c999 100644 --- a/src/ArrayValue.ts +++ b/src/ArrayValue.ts @@ -6,7 +6,7 @@ import {ArraySize} from './ArraySize' import {CellError} from './Cell' import {EmptyValue, InternalScalarValue, InterpreterValue} from './interpreter/InterpreterValue' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' export interface IArray { size: ArraySize, diff --git a/src/Cell.ts b/src/Cell.ts index 1b572aa92e..e5dfdf214b 100644 --- a/src/Cell.ts +++ b/src/Cell.ts @@ -14,7 +14,7 @@ import { isExtendedNumber, NumberType, } from './interpreter/InterpreterValue' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' import {Maybe} from './Maybe' import {CellAddress} from './parser' import {AddressWithSheet} from './parser/Address' diff --git a/src/ContentChanges.ts b/src/ContentChanges.ts index 3e3a46dfd1..d22cc9e092 100644 --- a/src/ContentChanges.ts +++ b/src/ContentChanges.ts @@ -5,7 +5,7 @@ import {addressKey, SimpleCellAddress} from './Cell' import {InterpreterValue} from './interpreter/InterpreterValue' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' export interface CellValueChange { address: SimpleCellAddress, diff --git a/src/DependencyGraph/DependencyGraph.ts b/src/DependencyGraph/DependencyGraph.ts index 2f6c2e9aeb..fe19794996 100644 --- a/src/DependencyGraph/DependencyGraph.ts +++ b/src/DependencyGraph/DependencyGraph.ts @@ -20,7 +20,7 @@ import { InterpreterValue, RawScalarValue } from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {LazilyTransformingAstService} from '../LazilyTransformingAstService' import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' diff --git a/src/Evaluator.ts b/src/Evaluator.ts index e6877ca572..650b6c3e45 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -13,7 +13,7 @@ import {FormulaVertex} from './DependencyGraph/FormulaCellVertex' import {Interpreter} from './interpreter/Interpreter' import {InterpreterState} from './interpreter/InterpreterState' import {EmptyValue, getRawValue, InterpreterValue} from './interpreter/InterpreterValue' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' import {LazilyTransformingAstService} from './LazilyTransformingAstService' import {ColumnSearchStrategy} from './Lookup/SearchStrategy' import {Ast, RelativeDependency} from './parser' diff --git a/src/Exporter.ts b/src/Exporter.ts index 08ea03ebba..c4ab725f51 100644 --- a/src/Exporter.ts +++ b/src/Exporter.ts @@ -9,7 +9,7 @@ import {Config} from './Config' import {CellValueChange, ChangeExporter} from './ContentChanges' import {ErrorMessage} from './error-message' import {EmptyValue, getRawValue, InterpreterValue, isExtendedNumber} from './interpreter/InterpreterValue' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' import {LazilyTransformingAstService} from './LazilyTransformingAstService' import {NamedExpressions} from './NamedExpressions' import {SheetIndexMappingFn, simpleCellAddressToString} from './parser/addressRepresentationConverters' diff --git a/src/Lookup/AdvancedFind.ts b/src/Lookup/AdvancedFind.ts index e42404da9f..fb85689503 100644 --- a/src/Lookup/AdvancedFind.ts +++ b/src/Lookup/AdvancedFind.ts @@ -10,7 +10,7 @@ import { RawInterpreterValue, RawNoErrorScalarValue } from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {SearchOptions} from './SearchStrategy' import {forceNormalizeString} from '../interpreter/ArithmeticHelper' import {findLastOccurrenceInOrderedRange} from '../interpreter/binarySearch' diff --git a/src/Lookup/ColumnBinarySearch.ts b/src/Lookup/ColumnBinarySearch.ts index 7e6b640856..3426445e52 100644 --- a/src/Lookup/ColumnBinarySearch.ts +++ b/src/Lookup/ColumnBinarySearch.ts @@ -7,7 +7,7 @@ import {SimpleCellAddress} from '../Cell' import {CellValueChange} from '../ContentChanges' import {DependencyGraph} from '../DependencyGraph' import {RawNoErrorScalarValue, RawScalarValue} from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {ColumnsSpan} from '../Span' import {AdvancedFind} from './AdvancedFind' import {ColumnSearchStrategy, SearchOptions} from './SearchStrategy' diff --git a/src/Lookup/ColumnIndex.ts b/src/Lookup/ColumnIndex.ts index da71080e93..e7cc65c298 100644 --- a/src/Lookup/ColumnIndex.ts +++ b/src/Lookup/ColumnIndex.ts @@ -18,7 +18,7 @@ import { RawNoErrorScalarValue, RawScalarValue } from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {LazilyTransformingAstService} from '../LazilyTransformingAstService' import {ColumnsSpan, RowsSpan} from '../Span' import {Statistics, StatType} from '../statistics' diff --git a/src/Lookup/RowSearchStrategy.ts b/src/Lookup/RowSearchStrategy.ts index 0a73c6d7b0..6b70c432ca 100644 --- a/src/Lookup/RowSearchStrategy.ts +++ b/src/Lookup/RowSearchStrategy.ts @@ -5,7 +5,7 @@ import {DependencyGraph} from '../DependencyGraph' import {RawNoErrorScalarValue} from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {AdvancedFind} from './AdvancedFind' import {SearchOptions, SearchStrategy} from './SearchStrategy' diff --git a/src/Lookup/SearchStrategy.ts b/src/Lookup/SearchStrategy.ts index 0672d6247d..d658d75584 100644 --- a/src/Lookup/SearchStrategy.ts +++ b/src/Lookup/SearchStrategy.ts @@ -8,7 +8,7 @@ import {Config} from '../Config' import {CellValueChange} from '../ContentChanges' import {DependencyGraph} from '../DependencyGraph' import {RawInterpreterValue, RawNoErrorScalarValue, RawScalarValue} from '../interpreter/InterpreterValue' -import {SimpleRangeValue} from '../interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import {ColumnsSpan} from '../Span' import {Statistics} from '../statistics' import {ColumnBinarySearch} from './ColumnBinarySearch' diff --git a/src/interpreter/SimpleRangeValue.ts b/src/SimpleRangeValue.ts similarity index 94% rename from src/interpreter/SimpleRangeValue.ts rename to src/SimpleRangeValue.ts index bd95294e5a..62b2f6f6b1 100644 --- a/src/interpreter/SimpleRangeValue.ts +++ b/src/SimpleRangeValue.ts @@ -3,12 +3,13 @@ * Copyright (c) 2022 Handsoncode. All rights reserved. */ -import {AbsoluteCellRange} from '../AbsoluteCellRange' -import {ArraySize} from '../ArraySize' -import {CellError, ErrorType, simpleCellAddress, SimpleCellAddress} from '../Cell' -import {DependencyGraph} from '../DependencyGraph' -import {ErrorMessage} from '../error-message' -import {InternalScalarValue, isExtendedNumber} from './InterpreterValue' +import {AbsoluteCellRange} from './AbsoluteCellRange' +import {ArraySize} from './ArraySize' +import {CellError, ErrorType, simpleCellAddress, SimpleCellAddress} from './Cell' +import {DependencyGraph} from './DependencyGraph' +import {ErrorMessage} from './error-message' +import {InternalScalarValue, isExtendedNumber} from './interpreter/InterpreterValue' + export class SimpleRangeValue { public readonly size: ArraySize diff --git a/src/index.ts b/src/index.ts index b03777058b..ec48bc779c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -51,7 +51,7 @@ import enGB from './i18n/languages/enGB' import {FunctionArgument, FunctionPlugin, FunctionPluginDefinition, FunctionArgumentType, ImplementedFunctions, FunctionMetadata} from './interpreter' import {FormatInfo} from './interpreter/InterpreterValue' import * as plugins from './interpreter/plugin' -import {SimpleRangeValue} from './interpreter/SimpleRangeValue' +import {SimpleRangeValue} from './SimpleRangeValue' import {NamedExpression, NamedExpressionOptions} from './NamedExpressions' import {SerializedNamedExpression} from './Serialization' import {Sheet, SheetDimensions, Sheets} from './Sheet' diff --git a/src/interpreter/ArithmeticHelper.ts b/src/interpreter/ArithmeticHelper.ts index 6a447051bc..73afc4f7b6 100644 --- a/src/interpreter/ArithmeticHelper.ts +++ b/src/interpreter/ArithmeticHelper.ts @@ -33,7 +33,7 @@ import { RawScalarValue, TimeNumber } from './InterpreterValue' -import {SimpleRangeValue} from './SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' import Collator = Intl.Collator export type complex = [number, number] diff --git a/src/interpreter/CriterionFunctionCompute.ts b/src/interpreter/CriterionFunctionCompute.ts index 02c147b9da..0a1fc449a7 100644 --- a/src/interpreter/CriterionFunctionCompute.ts +++ b/src/interpreter/CriterionFunctionCompute.ts @@ -12,7 +12,7 @@ import {Maybe} from '../Maybe' import {CriterionLambda, CriterionPackage} from './Criterion' import {Interpreter} from './Interpreter' import {getRawValue, InternalScalarValue, RawScalarValue} from './InterpreterValue' -import {SimpleRangeValue} from './SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' const findSmallerRangeForMany = (dependencyGraph: DependencyGraph, conditionRanges: AbsoluteCellRange[], valuesRange: AbsoluteCellRange): { smallerRangeVertex?: RangeVertex, restConditionRanges: AbsoluteCellRange[], restValuesRange: AbsoluteCellRange } => { if (valuesRange.end.row > valuesRange.start.row) { diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 5e8c323baa..dece0f3b47 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -39,7 +39,7 @@ import { InterpreterValue, isExtendedNumber, } from './InterpreterValue' -import {SimpleRangeValue} from './SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' export class Interpreter { public readonly criterionBuilder: CriterionBuilder diff --git a/src/interpreter/InterpreterValue.ts b/src/interpreter/InterpreterValue.ts index adc53c2c29..d419e09b10 100644 --- a/src/interpreter/InterpreterValue.ts +++ b/src/interpreter/InterpreterValue.ts @@ -4,7 +4,7 @@ */ import {CellError} from '../Cell' -import {SimpleRangeValue} from './SimpleRangeValue' +import {SimpleRangeValue} from '../SimpleRangeValue' export const EmptyValue = Symbol('Empty value') export type EmptyValueType = typeof EmptyValue diff --git a/src/interpreter/plugin/ArrayPlugin.ts b/src/interpreter/plugin/ArrayPlugin.ts index 6b6c2c1dd7..48261c710a 100644 --- a/src/interpreter/plugin/ArrayPlugin.ts +++ b/src/interpreter/plugin/ArrayPlugin.ts @@ -10,7 +10,7 @@ import {AstNodeType, ProcedureAst} from '../../parser' import {coerceScalarToBoolean} from '../ArithmeticHelper' import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, InterpreterValue} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export class ArrayPlugin extends FunctionPlugin implements FunctionPluginTypecheck { diff --git a/src/interpreter/plugin/ConditionalAggregationPlugin.ts b/src/interpreter/plugin/ConditionalAggregationPlugin.ts index 790770a7a0..3133c04fcd 100644 --- a/src/interpreter/plugin/ConditionalAggregationPlugin.ts +++ b/src/interpreter/plugin/ConditionalAggregationPlugin.ts @@ -17,7 +17,7 @@ import { RawInterpreterValue, RawScalarValue } from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' class AverageResult { diff --git a/src/interpreter/plugin/DateTimePlugin.ts b/src/interpreter/plugin/DateTimePlugin.ts index 365a9b8c66..9ba18003e3 100644 --- a/src/interpreter/plugin/DateTimePlugin.ts +++ b/src/interpreter/plugin/DateTimePlugin.ts @@ -30,7 +30,7 @@ import { RawNoErrorScalarValue, RawScalarValue, } from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** diff --git a/src/interpreter/plugin/FinancialPlugin.ts b/src/interpreter/plugin/FinancialPlugin.ts index b6ef5080c9..68bf11a722 100644 --- a/src/interpreter/plugin/FinancialPlugin.ts +++ b/src/interpreter/plugin/FinancialPlugin.ts @@ -15,7 +15,7 @@ import { NumberType, RawInterpreterValue } from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export class FinancialPlugin extends FunctionPlugin implements FunctionPluginTypecheck { diff --git a/src/interpreter/plugin/FunctionPlugin.ts b/src/interpreter/plugin/FunctionPlugin.ts index 9b88e79645..5e76abe586 100644 --- a/src/interpreter/plugin/FunctionPlugin.ts +++ b/src/interpreter/plugin/FunctionPlugin.ts @@ -35,7 +35,7 @@ import { RawNoErrorScalarValue, RawScalarValue } from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' export interface ImplementedFunctions { [formulaId: string]: FunctionMetadata, diff --git a/src/interpreter/plugin/InformationPlugin.ts b/src/interpreter/plugin/InformationPlugin.ts index 6ddf0d0631..b637b4b3e1 100644 --- a/src/interpreter/plugin/InformationPlugin.ts +++ b/src/interpreter/plugin/InformationPlugin.ts @@ -9,7 +9,7 @@ import {ErrorMessage} from '../../error-message' import {AstNodeType, ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {EmptyValue, InternalScalarValue, InterpreterValue, isExtendedNumber} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** diff --git a/src/interpreter/plugin/LookupPlugin.ts b/src/interpreter/plugin/LookupPlugin.ts index 2f38d2a0e2..2c61e2d7d1 100644 --- a/src/interpreter/plugin/LookupPlugin.ts +++ b/src/interpreter/plugin/LookupPlugin.ts @@ -13,7 +13,7 @@ import {StatType} from '../../statistics' import {zeroIfEmpty} from '../ArithmeticHelper' import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, InterpreterValue, RawNoErrorScalarValue} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypecheck { diff --git a/src/interpreter/plugin/MathPlugin.ts b/src/interpreter/plugin/MathPlugin.ts index d12d72a823..c285fdc6c9 100644 --- a/src/interpreter/plugin/MathPlugin.ts +++ b/src/interpreter/plugin/MathPlugin.ts @@ -8,7 +8,7 @@ import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InterpreterValue, RawInterpreterValue} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export class MathPlugin extends FunctionPlugin implements FunctionPluginTypecheck { diff --git a/src/interpreter/plugin/MatrixPlugin.ts b/src/interpreter/plugin/MatrixPlugin.ts index 410801d159..6fbaafa244 100644 --- a/src/interpreter/plugin/MatrixPlugin.ts +++ b/src/interpreter/plugin/MatrixPlugin.ts @@ -9,7 +9,7 @@ import {ErrorMessage} from '../../error-message' import {AstNodeType, ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, InterpreterValue} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export type KernelRunShortcut = (...args: any[]) => number[][] diff --git a/src/interpreter/plugin/MedianPlugin.ts b/src/interpreter/plugin/MedianPlugin.ts index caba33c41b..3f09b53703 100644 --- a/src/interpreter/plugin/MedianPlugin.ts +++ b/src/interpreter/plugin/MedianPlugin.ts @@ -8,7 +8,7 @@ import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InterpreterValue, RawScalarValue} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** diff --git a/src/interpreter/plugin/NumericAggregationPlugin.ts b/src/interpreter/plugin/NumericAggregationPlugin.ts index 813203c751..ae2dd1683c 100644 --- a/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -13,7 +13,7 @@ import {ColumnRangeAst, RowRangeAst} from '../../parser/Ast' import {coerceBooleanToNumber} from '../ArithmeticHelper' import {InterpreterState} from '../InterpreterState' import {EmptyValue, ExtendedNumber, getRawValue, InternalScalarValue, isExtendedNumber} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' import {RangeVertex} from '../../DependencyGraph' diff --git a/src/interpreter/plugin/StatisticalAggregationPlugin.ts b/src/interpreter/plugin/StatisticalAggregationPlugin.ts index d0d604b762..b6a45ad565 100644 --- a/src/interpreter/plugin/StatisticalAggregationPlugin.ts +++ b/src/interpreter/plugin/StatisticalAggregationPlugin.ts @@ -14,7 +14,7 @@ import { isExtendedNumber, RawInterpreterValue } from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import { centralF, chisquare, diff --git a/src/interpreter/plugin/SumprodPlugin.ts b/src/interpreter/plugin/SumprodPlugin.ts index 1c8a22002d..5f416ab0d6 100644 --- a/src/interpreter/plugin/SumprodPlugin.ts +++ b/src/interpreter/plugin/SumprodPlugin.ts @@ -8,7 +8,7 @@ import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {getRawValue, InterpreterValue, isExtendedNumber} from '../InterpreterValue' -import {SimpleRangeValue} from '../SimpleRangeValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export class SumprodPlugin extends FunctionPlugin implements FunctionPluginTypecheck { diff --git a/test/content-changes.spec.ts b/test/content-changes.spec.ts index e1c0c39b7f..79849cc0ec 100644 --- a/test/content-changes.spec.ts +++ b/test/content-changes.spec.ts @@ -1,5 +1,5 @@ import {CellValueChange, ChangeExporter, ContentChanges} from '../src/ContentChanges' -import {SimpleRangeValue} from '../src/interpreter/SimpleRangeValue' +import {SimpleRangeValue} from '../src/SimpleRangeValue' import {adr} from './testUtils' class SimpleChangeExporter implements ChangeExporter { From 8d4fca3d7368f1f61eeeb3caff4a401606a8ad43 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 13 Dec 2022 16:12:56 +0100 Subject: [PATCH 13/29] Describe DOUBLE_RANGE function in the custom-functions guide --- docs/guide/custom-functions.md | 176 +++++++++++++++++++++------------ 1 file changed, 115 insertions(+), 61 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index fbed76be17..61a8664f64 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -7,7 +7,7 @@ Expand the function library of your application, by adding custom functions. ## Add a simple custom function -As an example, let's create a function that accepts a person's first name as a string argument and returns a personalized greeting. +As an example, let's create a custom function `GREET` that accepts a person's first name as a string argument and returns a personalized greeting. ### 1. Create a function plugin @@ -62,14 +62,10 @@ MyCustomPlugin.implementedFunctions = { ### 3. Add your function's names -In your function plugin, in the static `translations` property, define your function's names in every language you want to support. Your end users use these names to call your function inside formulas. +In your function plugin, in the static `translations` property, define your function's [names in every language you want to support](#function-name-translations). Your end users use these names to call your function inside formulas. If you support just one language, you still need to define the name of your function in that language. -::: tip -Function names are case-insensitive, as they are all normalized to uppercase. -::: - ```javascript GreetingsPlugin.translations = { enGB: { @@ -178,33 +174,128 @@ HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations) ## Advanced custom function example -In more advanced example we'll create a function that takes a range of numbers and returns the range of the same size with all the numbers doubled. +In more advanced example, we'll create a custom function `DOUBLE_RANGE` that takes a range of numbers and returns the range of the same size with all the numbers doubled. ### Accept a range argument -`SimpleRangeValue` +To accept a range argument, declare it in the `parameters` array: -### Work with different value types +```js +MyCustomPlugin.implementedFunctions = { + DOUBLE_RANGE: { + method: 'doubleRange', + parameters: [ + { argumentType: 'RANGE' }, + ], + } +}; +``` -`InternalScalarValue` +The range arguments are passed to the implementation method as instances of the [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): -### Validate the arguments +```js +doubleRange(ast, state) { + return this.runFunction( + ast.args, + state, + this.metadata('DOUBLE_RANGE'), + (range) => { + const rangeData = range.data; + // ... + }, + ); +} +``` -`CellError` +### Return an array of data -[error handling](#returning-errors) +A function may return multiple values in the form of an array. To do that, use [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): -### Return an array of data +```js +const resultArray = //... +return SimpleRangeValue.onlyValues(resultArray); +``` -`arraySizeMethod` -`ArraySize` +You also need to provide the `arraySizeMethod` that calculates the size of the result array based on the function arguments and returns an instance of the [`ArraySize` class](../api/classes/arraysize.md). + +::: tip +If you don't define the `arraySizeMethod`, returning an array will cause the `#VALUE!` error. +::: + +```js +export class MyCustomPlugin extends FunctionPlugin { + doubleRangeResultArraySize(ast, state) { + const arg = ast?.args?.[0]; + + if (arg?.start == null || arg?.end == null) { + // return new ArraySize.scalar(); + return { width: 1, height: 1, isRef: false, isScalar: () => true }; + } + + const width = arg.end.col - arg.start.col + 1; + const height = arg.end.row - arg.start.row + 1; + + // return new ArraySize(width, height); + return { width, height, isRef: false, isScalar: () => width === 1 && height === 1 }; + } +} + +MyCustomPlugin.implementedFunctions = { + DOUBLE_RANGE: { + method: 'doubleRange', + arraySizeMethod: 'doubleRangeResultArraySize', + parameters: [ + { argumentType: 'RANGE' }, + ], + } +}; +``` + +### Validate the arguments and return an error + +To handle invalid inputs, the custom function should return an instance of the [`CellError` class](../api/classes/cellerror.md). Check the available [error types](types-of-errors.md). Errors are localized according to your [language settings](localizing-functions.md). + +```js +if (rangeData.some(row => row.some(val => typeof rawValue !== 'number'))) { + return new CellError('VALUE', 'Function DOUBLE_RANGE operates only on numbers.'); +} +``` + +::: tip +All HyperFormula [error types](types-of-errors.md) support optional custom error messages. Put them to good use: let your users know what caused the error and how to avoid it in the future. +::: ### Test your function You may add unit tests to make sure that your custom function works correctly using one of the javascript testing libraries. ```js -// TODO: unit tests for DOUBLE_RANGE +it('works for a range of numbers', () => { + HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); + + const engine = HyperFormula.buildFromArray([ + [1, '=DOUBLE_RANGE(A1:A3)'], + [2], + [3], + ], { licenseKey: 'gpl-v3' }); + + expect(engine.getCellValue({ sheet: 0, row: 0, col: 1 })).toEqual(2); + expect(engine.getCellValue({ sheet: 0, row: 1, col: 1 })).toEqual(4); + expect(engine.getCellValue({ sheet: 0, row: 2, col: 1 })).toEqual(6); +}); + +it('returns a VALUE error if the range argument contains a string', () => { + HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); + + const engine = HyperFormula.buildFromArray([ + [1, '=DOUBLE_RANGE(A1:A3)'], + ['I should not be here'], + [3], + ], { licenseKey: 'gpl-v3' }); + + expect(engine.getCellValueType({ sheet: 0, row: 0, col: 1 })).toEqual('ERROR'); + expect(engine.getCellValue({ sheet: 0, row: 0, col: 1 }).value).toEqual('#VALUE!'); +}); ``` ## Working demo @@ -240,7 +331,7 @@ You can set the following options for your function: In your function plugin, in the static `implementedFunctions` property, add your function's options: ```javascript -MyFunctionPlugin.implementedFunctions = { +MyCustomPlugin.implementedFunctions = { MY_FUNCTION: { method: 'myFunctionMethod', arrayFunction: false, @@ -271,7 +362,7 @@ You can set the following argument validation options: In your function plugin, in the static `implementedFunctions` property, next to other options add an array called `parameters`: ```javascript -MyFunctionPlugin.implementedFunctions = { +MyCustomPlugin.implementedFunctions = { MY_FUNCTION: { method: 'myFunctionMethod', parameters: [{ @@ -302,7 +393,7 @@ You can assign multiple aliases to a single custom function. In your function plugin, in the static `aliases` property, add aliases for your function: ```javascript -MyFunctionPlugin.aliases = { +MyCustomPlugin.aliases = { // `=MY_ALIAS()` will work the same as `=MY_FUNCTION()` 'MY_ALIAS': 'MY_FUNCTION' }; @@ -311,7 +402,7 @@ MyFunctionPlugin.aliases = { ::: tip For each alias of your function, define a translation, even if you want to support only one language. ```js -MyFunctionPlugin.translations = { +MyCustomPlugin.translations = { enGB: { 'MY_FUNCTION': 'MY_FUNCTION', 'MY_ALIAS': 'MY_ALIAS', @@ -322,8 +413,6 @@ MyFunctionPlugin.translations = { ## Function name translations -// TODO: merge this section with the simple custom function tutorial - You can configure the name of your function with multiple translations. Your end users call your function by referring to those translations. @@ -335,7 +424,7 @@ Function names are case-insensitive, as they are all normalized to uppercase. ::: ```javascript -MyFunctionPlugin.translations = { +MyCustomPlugin.translations = { enGB: { // formula in English: `=MY_FUNCTION()` 'MY_FUNCTION': 'MY_FUNCTION' @@ -347,7 +436,7 @@ MyFunctionPlugin.translations = { }; // register your function plugin and translations -HyperFormula.registerFunctionPlugin(MyFunctionPlugin, MyFunctionPlugin.translations); +HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); ``` You can also define `translations` as a standalone object: @@ -363,44 +452,9 @@ export const MyFunctionNameTranslations = { }; // register your function plugin and translations -HyperFormula.registerFunctionPlugin(MyFunctionPlugin, MyFunctionNameTranslations); +HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyFunctionNameTranslations); ``` ::: tip Before using a translated function name, remember to [register and set the language](localizing-functions.md). ::: - -## Returning errors - -If you want your custom function to return an error, check the [API reference](../api) for the HyperFormula [error types](types-of-errors.md). - -::: tip -All HyperFormula [error types](types-of-errors.md) support optional custom error messages. Put them to good use: let your users know what caused the error and how to avoid it in the future. -::: - -For example, if you want to return a `#DIV/0!` error with your custom error message, use the [`CellError` class](../api/classes/cellerror.md), and the [DIV_BY_ZERO](../api/enums/errortype.md#div-by-zero) error type: - -```javascript -// import `CellError` and `ErrorType` -import { FunctionPlugin, CellError, ErrorType } from 'hyperformula'; - -export class MyFunctionPlugin extends FunctionPlugin { - myFunctionMethod(ast, state) { - if (!ast.args.length) { - // create a `CellError` instance with an `ErrorType` of `DIV_BY_ZERO` - // with your custom error message (optional) - return new CellError(ErrorType.DIV_BY_ZERO, 'Sorry, cannot divide by zero!'); - } - - return this.runFunction(ast.args, state, this.metadata('HYPER'), () => 'Hyperformula'.length) - } -} -``` - -The error displays as `#DIV/0` and gets translated appropriately. - -### Error localization - -Errors returned by methods such as `getCellValue` are wrapped in the [`DetailedCellError` type](../api/classes/detailedcellerror.md). - -`DetailedCellError` localizes the error based on your [internationalization settings](localizing-functions.md). From 6b5992df85d868c793e0a0838dea81216081f3b9 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 13 Dec 2022 16:26:29 +0100 Subject: [PATCH 14/29] Use ArraySize in the example of arraySizeMethod in the custom-functiosn guide --- docs/guide/custom-functions.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 61a8664f64..1ae7091232 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -26,7 +26,7 @@ export class MyCustomPlugin extends FunctionPlugin { In your function plugin, in the static `implementedFunctions` property, define an object that declares the functions provided by this plugin. -The name of that object becomes the ID by which [translations](#function-translations), [aliases](#function-aliases), and other elements refer to your function. +The name of that object becomes the ID by which [translations](#function-name-translations), [aliases](#function-aliases), and other elements refer to your function. Make the ID unique among all HyperFormula functions ([built-in](built-in-functions.md#list-of-available-functions) and custom). In your function's object, you can specify: @@ -194,16 +194,18 @@ MyCustomPlugin.implementedFunctions = { The range arguments are passed to the implementation method as instances of the [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): ```js -doubleRange(ast, state) { - return this.runFunction( - ast.args, - state, - this.metadata('DOUBLE_RANGE'), - (range) => { - const rangeData = range.data; - // ... - }, - ); +export class MyCustomPlugin extends FunctionPlugin { + doubleRange(ast, state) { + return this.runFunction( + ast.args, + state, + this.metadata('DOUBLE_RANGE'), + (range) => { + const rangeData = range.data; + // ... + }, + ); + } } ``` @@ -228,15 +230,13 @@ export class MyCustomPlugin extends FunctionPlugin { const arg = ast?.args?.[0]; if (arg?.start == null || arg?.end == null) { - // return new ArraySize.scalar(); - return { width: 1, height: 1, isRef: false, isScalar: () => true }; + return new ArraySize.scalar(); } const width = arg.end.col - arg.start.col + 1; const height = arg.end.row - arg.start.row + 1; - // return new ArraySize(width, height); - return { width, height, isRef: false, isScalar: () => width === 1 && height === 1 }; + return new ArraySize(width, height); } } From ee375f702845f65fc802f0d0b98b9c07f97b7670 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 13 Dec 2022 16:38:16 +0100 Subject: [PATCH 15/29] Add changelog entry --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 66ae6fbb1c..4f3e5b850b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- Expanded the HyperFormula public API by adding the code entities that are necessary to implement a complex custom function: `ArraySize`, `ImplementedFunctions`, `FunctionMetadata`, `FunctionArgumentType`. [#779](https://github.com/handsontable/hyperformula/issues/779) + ## [2.2.0] - 2022-11-17 ### Added From 0ab746586850e8934c031f903f91940c0864fdd7 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 13 Dec 2022 16:56:09 +0100 Subject: [PATCH 16/29] Add the description for the arraySizeMethod option --- docs/guide/custom-functions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 1ae7091232..839d358a76 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -74,6 +74,8 @@ GreetingsPlugin.translations = { enUS: { GREET: "GREET", } + + // repeat for all languages used in your system... }; ``` @@ -321,7 +323,7 @@ You can set the following options for your function: | `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely. | | `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments. | | `returnNumberType` | String | Function return type. | -| `arraySizeMethod` | ? | ? | +| `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | | `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md). | | `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns). | | `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated). | From b9c68682735cbaf1e9b9ff65faa6ab6d6536b27c Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 11:57:34 +0100 Subject: [PATCH 17/29] Rephrase a few sentences in the custom-functions guide --- docs/guide/custom-functions.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 839d358a76..430f2539ec 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -13,7 +13,7 @@ As an example, let's create a custom function `GREET` that accepts a person's fi Import `FunctionPlugin`, and extend it with a new class. For example: -```javascript +```js import { FunctionPlugin } from 'hyperformula'; // let's call the function plugin `GreetingsPlugin` @@ -31,10 +31,10 @@ Make the ID unique among all HyperFormula functions ([built-in](built-in-functio In your function's object, you can specify: - a `method` property (required), which maps your function to an implementation method (we'll define it later on), -- an `parameters` array that describes the arguments accepted by your function and [validation options](#argument-validation-options) for each argument, +- a `parameters` array that describes the arguments accepted by your function and [validation options](#argument-validation-options) for each argument, - other [custom function options](#custom-function-options). -```javascript +```js MyCustomPlugin.implementedFunctions = { // let's define the function's ID as `GREET` GREET: { @@ -66,7 +66,7 @@ In your function plugin, in the static `translations` property, define your func If you support just one language, you still need to define the name of your function in that language. -```javascript +```js GreetingsPlugin.translations = { enGB: { GREET: "GREET", @@ -90,7 +90,7 @@ To benefit from HyperFormula's automatic validations, wrap your method in the bu * Validates your function's parameters against your [custom function options](#custom-function-options). * Validates arguments passed to your function against your [argument validation options](#argument-validation-options). -```javascript +```js export class MyCustomPlugin extends FunctionPlugin { greet(ast, state) { return this.runFunction( @@ -119,7 +119,7 @@ HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations) Now, you can use your GREET function inside a formula: -```javascript +```js // prepare spreadsheet data const data = [['Anthony', '=GREET(A1)']]; @@ -269,7 +269,7 @@ All HyperFormula [error types](types-of-errors.md) support optional custom error ### Test your function -You may add unit tests to make sure that your custom function works correctly using one of the javascript testing libraries. +You may add unit tests to make sure that your custom function works correctly using one of the JavaScript testing libraries. ```js it('works for a range of numbers', () => { @@ -330,7 +330,7 @@ You can set the following options for your function: | `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions. | | `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized. | -In your function plugin, in the static `implementedFunctions` property, add your function's options: +The options listed above are set in the static `implementedFunctions` property of your function plugin: ```javascript MyCustomPlugin.implementedFunctions = { @@ -361,9 +361,9 @@ You can set the following argument validation options: | `lessThan` | Number | If set: numerical argument need to be less than `lessThan`. | | `greaterThan` | Number | If set: numerical argument need to be greater than `greaterThan`. | -In your function plugin, in the static `implementedFunctions` property, next to other options add an array called `parameters`: +In your function plugin, in the static `implementedFunctions` property, add an array called `parameters`: -```javascript +```js MyCustomPlugin.implementedFunctions = { MY_FUNCTION: { method: 'myFunctionMethod', @@ -394,7 +394,7 @@ You can assign multiple aliases to a single custom function. In your function plugin, in the static `aliases` property, add aliases for your function: -```javascript +```js MyCustomPlugin.aliases = { // `=MY_ALIAS()` will work the same as `=MY_FUNCTION()` 'MY_ALIAS': 'MY_FUNCTION' @@ -425,7 +425,7 @@ in every language that you want to support. Function names are case-insensitive, as they are all normalized to uppercase. ::: -```javascript +```js MyCustomPlugin.translations = { enGB: { // formula in English: `=MY_FUNCTION()` From fb5e5aae40399e3062f45eeb12300fc40ff81a7b Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 12:13:39 +0100 Subject: [PATCH 18/29] Improve the description of returnNumberType option in the custom-functions guide --- docs/guide/custom-functions.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 430f2539ec..9f5026ffec 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -316,19 +316,19 @@ This demo contains the implementation of both `GREET` and `DOUBLE_RANGE` custom You can set the following options for your function: -| Option | Type | Description | -|-------------------------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------| -| `method` (required) | String | Name of the method that implements the custom function logic. | -| `parameters` | Array | Specification of the arguments accepted by the function and their [validation options](#argument-validation-options). | -| `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely. | -| `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments. | -| `returnNumberType` | String | Function return type. | -| `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | -| `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md). | -| `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns). | -| `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated). | -| `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions. | -| `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized. | +| Option | Type | Description | +|-------------------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `method` (required) | String | Name of the method that implements the custom function logic. | +| `parameters` | Array | Specification of the arguments accepted by the function and their [validation options](#argument-validation-options). | +| `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely. | +| `returnNumberType` | String | If function returns a numeric value, this option indicates the way to interpret the returned number.
Possible values: `NUMBER_RAW, NUMBER_DATE, NUMBER_TIME, NUMBER_DATETIME, NUMBER_CURRENCY, NUMBER_PERCENT`. | +| `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | +| `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments. | +| `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md). | +| `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns). | +| `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated). | +| `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions. | +| `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized. | The options listed above are set in the static `implementedFunctions` property of your function plugin: From befa8074a3fe1842b786fb1f0ef97afc9ddce5b1 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 12:21:43 +0100 Subject: [PATCH 19/29] Add default values to the custom function options description --- docs/guide/custom-functions.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 9f5026ffec..9eba641928 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -316,19 +316,19 @@ This demo contains the implementation of both `GREET` and `DOUBLE_RANGE` custom You can set the following options for your function: -| Option | Type | Description | -|-------------------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `method` (required) | String | Name of the method that implements the custom function logic. | -| `parameters` | Array | Specification of the arguments accepted by the function and their [validation options](#argument-validation-options). | -| `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely. | -| `returnNumberType` | String | If function returns a numeric value, this option indicates the way to interpret the returned number.
Possible values: `NUMBER_RAW, NUMBER_DATE, NUMBER_TIME, NUMBER_DATETIME, NUMBER_CURRENCY, NUMBER_PERCENT`. | -| `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | -| `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments. | -| `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md). | -| `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns). | -| `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated). | -| `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions. | -| `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized. | +| Option | Type | Description | +|-------------------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `method` (required) | String | Name of the method that implements the custom function logic. | +| `parameters` | Array | Specification of the arguments accepted by the function and their [validation options](#argument-validation-options). | +| `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | +| `returnNumberType` | String | If function returns a numeric value, this option indicates the way to interpret the returned number.
Possible values: `NUMBER_RAW, NUMBER_DATE, NUMBER_TIME, NUMBER_DATETIME, NUMBER_CURRENCY, NUMBER_PERCENT`.
Default: `NUMBER_RAW` | +| `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely.
Default: `0` | +| `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments.
Default: `false` | +| `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md).
Default: `false` | +| `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns).
Default: `false` | +| `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated).
Default: `false` | +| `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions.
Default: `false` | +| `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized.
Default: `false` | The options listed above are set in the static `implementedFunctions` property of your function plugin: From 4f622238e7e32373370f0f45b9d8ddb4da993012 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 12:33:20 +0100 Subject: [PATCH 20/29] Add possible values to the argumentType description in the custom-fucntions guide --- docs/guide/custom-functions.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 9eba641928..53f130ce3a 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -350,16 +350,16 @@ MyCustomPlugin.implementedFunctions = { You can set the following argument validation options: -| Option | Type | Description | -|---------------------------|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `argumentType` (required) | String | Expected type of the argument. | -| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`). | -| `defaultValue` | `InternalScalarValue` \ `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | -| `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).

Setting this option to `true` is the same as setting `defaultValue` to `undefined`. | -| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | -| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | -| `lessThan` | Number | If set: numerical argument need to be less than `lessThan`. | -| `greaterThan` | Number | If set: numerical argument need to be greater than `greaterThan`. | +| Option | Type | Description | +|---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | +| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | +| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | +| `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).
Default: `false`
Setting this option to `true` is the same as setting `defaultValue` to `undefined`. | +| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | +| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | +| `lessThan` | Number | If set: numerical argument need to be less than `lessThan`. | +| `greaterThan` | Number | If set: numerical argument need to be greater than `greaterThan`. | In your function plugin, in the static `implementedFunctions` property, add an array called `parameters`: From ea0f41b44b63985c00889bf721dc6777b12027d5 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 12:55:52 +0100 Subject: [PATCH 21/29] Reduce content duplication on custom function name translations --- docs/guide/custom-functions.md | 76 ++++++++++++++---------------- docs/guide/localizing-functions.md | 18 +------ 2 files changed, 37 insertions(+), 57 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 53f130ce3a..5cdc157432 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -62,9 +62,7 @@ MyCustomPlugin.implementedFunctions = { ### 3. Add your function's names -In your function plugin, in the static `translations` property, define your function's [names in every language you want to support](#function-name-translations). Your end users use these names to call your function inside formulas. - -If you support just one language, you still need to define the name of your function in that language. +In your function plugin, in the static `translations` property, define your function's names in [every language you want to support](#function-name-translations). ```js GreetingsPlugin.translations = { @@ -74,7 +72,6 @@ GreetingsPlugin.translations = { enUS: { GREET: "GREET", } - // repeat for all languages used in your system... }; ``` @@ -388,42 +385,17 @@ Setting a `defaultValue` for an argument always makes that argument optional. Bu If you don't want to set any `defaultValue` (because, for example, your function's behavior depends on the number of valid arguments passed), use the `optionalArg` setting instead. -## Function aliases - -You can assign multiple aliases to a single custom function. - -In your function plugin, in the static `aliases` property, add aliases for your function: +## Function name translations -```js -MyCustomPlugin.aliases = { - // `=MY_ALIAS()` will work the same as `=MY_FUNCTION()` - 'MY_ALIAS': 'MY_FUNCTION' -}; -``` +You can provide the translations for your function name in multiple languages. +Your end users use the translated names to call your function inside formulas. ::: tip -For each alias of your function, define a translation, even if you want to support only one language. -```js -MyCustomPlugin.translations = { - enGB: { - 'MY_FUNCTION': 'MY_FUNCTION', - 'MY_ALIAS': 'MY_ALIAS', - }, -}; -``` +If you support just one language, you still need to define the name of your function in that language. ::: -## Function name translations - -You can configure the name of your function with multiple translations. -Your end users call your function by referring to those translations. - -In your function plugin, in the static `translations` property, define your function's names, -in every language that you want to support. - -::: tip +Define the translations for every language you want to support in the static `translations` property. Function names are case-insensitive, as they are all normalized to uppercase. -::: ```js MyCustomPlugin.translations = { @@ -434,7 +406,8 @@ MyCustomPlugin.translations = { deDE: { // formula in German: `=MEINE_FUNKTION()` 'MY_FUNCTION': 'MEINE_FUNKTION' - } + }, + // repeat for all languages used in your system... }; // register your function plugin and translations @@ -445,12 +418,7 @@ You can also define `translations` as a standalone object: ```js export const MyFunctionNameTranslations = { - enGB: { - 'MY_FUNCTION': 'MY_FUNCTION' - }, - deDE: { - 'MY_FUNCTION': 'MEINE_FUNKTION' - } + // ... }; // register your function plugin and translations @@ -460,3 +428,29 @@ HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyFunctionNameTranslations); ::: tip Before using a translated function name, remember to [register and set the language](localizing-functions.md). ::: + +## Function aliases + +You can also assign multiple aliases to a single custom function. + +In your function plugin, in the static `aliases` property, add aliases for your function: + +```js +MyCustomPlugin.aliases = { + // `=MY_ALIAS()` will work the same as `=MY_FUNCTION()` + 'MY_ALIAS': 'MY_FUNCTION' +}; +``` + +::: tip +For each alias of your function, define a translation, even if you want to support only one language. +```js + +MyCustomPlugin.translations = { + enGB: { + 'MY_FUNCTION': 'MY_FUNCTION', + 'MY_ALIAS': 'MY_ALIAS', + }, +}; +``` +::: diff --git a/docs/guide/localizing-functions.md b/docs/guide/localizing-functions.md index a20da5dfaf..7d9937e496 100644 --- a/docs/guide/localizing-functions.md +++ b/docs/guide/localizing-functions.md @@ -71,22 +71,8 @@ errors: { ## Localizing custom functions -You can translate your own [custom functions](custom-functions) into -different languages too. You need to define the translations and register the corresponding language pack after registering a plugin: - -```javascript -const translations = { - 'enGB': { - 'HYPER': 'HYPER' - }, - 'enUS': { - 'HYPER': 'HYPER' - }, - 'plPL': { - 'HYPER': 'HAJPER' - } -} -``` +Localization of custom functions is also supported. +[Custom functions guide](custom-functions.md#function-name-translations) describes, how to define the translations for your custom functions in multiple languages. ### List of supported languages | Language name | Language code | From 682f5d50ab6e2a5add3e93da47f1671b99dfeb7f Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 15:43:02 +0100 Subject: [PATCH 22/29] Minor improvements to custom-functions guide --- docs/guide/custom-functions.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 5cdc157432..8cbd731062 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -16,7 +16,7 @@ Import `FunctionPlugin`, and extend it with a new class. For example: ```js import { FunctionPlugin } from 'hyperformula'; -// let's call the function plugin `GreetingsPlugin` +// let's call the function plugin `MyCustomPlugin` export class MyCustomPlugin extends FunctionPlugin { } @@ -30,7 +30,7 @@ The name of that object becomes the ID by which [translations](#function-name-tr Make the ID unique among all HyperFormula functions ([built-in](built-in-functions.md#list-of-available-functions) and custom). In your function's object, you can specify: -- a `method` property (required), which maps your function to an implementation method (we'll define it later on), +- a `method` property (required), which maps your function to the implementation method (we'll define it later on), - a `parameters` array that describes the arguments accepted by your function and [validation options](#argument-validation-options) for each argument, - other [custom function options](#custom-function-options). @@ -62,10 +62,10 @@ MyCustomPlugin.implementedFunctions = { ### 3. Add your function's names -In your function plugin, in the static `translations` property, define your function's names in [every language you want to support](#function-name-translations). +In your function plugin, in the static `translations` property, [define your function's names in every language you want to support](#function-name-translations). ```js -GreetingsPlugin.translations = { +MyCustomPlugin.translations = { enGB: { GREET: "GREET", }, @@ -213,8 +213,20 @@ export class MyCustomPlugin extends FunctionPlugin { A function may return multiple values in the form of an array. To do that, use [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): ```js -const resultArray = //... -return SimpleRangeValue.onlyValues(resultArray); +export class MyCustomPlugin extends FunctionPlugin { + doubleRange(ast, state) { + return this.runFunction( + ast.args, + state, + this.metadata('DOUBLE_RANGE'), + (range) => { + // ... + const resultArray = //... + return SimpleRangeValue.onlyValues(resultArray); + }, + ); + } +} ``` You also need to provide the `arraySizeMethod` that calculates the size of the result array based on the function arguments and returns an instance of the [`ArraySize` class](../api/classes/arraysize.md). From bfbb0f039a970f763b161d391e97a4b3734813e4 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 21:08:53 +0100 Subject: [PATCH 23/29] grammarly fixes --- docs/guide/custom-functions.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 8cbd731062..153d795590 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -1,6 +1,6 @@ # Custom functions -Expand the function library of your application, by adding custom functions. +Expand the function library of your application by adding custom functions. **Contents:** [[toc]] @@ -22,7 +22,7 @@ export class MyCustomPlugin extends FunctionPlugin { } ``` -### 2. Define your function's ID, method and metadata +### 2. Define your function's ID, method, and metadata In your function plugin, in the static `implementedFunctions` property, define an object that declares the functions provided by this plugin. @@ -173,7 +173,7 @@ HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations) ## Advanced custom function example -In more advanced example, we'll create a custom function `DOUBLE_RANGE` that takes a range of numbers and returns the range of the same size with all the numbers doubled. +In a more advanced example, we'll create a custom function `DOUBLE_RANGE` that takes a range of numbers and returns the range of the same size with all the numbers doubled. ### Accept a range argument @@ -220,7 +220,6 @@ export class MyCustomPlugin extends FunctionPlugin { state, this.metadata('DOUBLE_RANGE'), (range) => { - // ... const resultArray = //... return SimpleRangeValue.onlyValues(resultArray); }, @@ -241,7 +240,7 @@ export class MyCustomPlugin extends FunctionPlugin { const arg = ast?.args?.[0]; if (arg?.start == null || arg?.end == null) { - return new ArraySize.scalar(); + return ArraySize.scalar(); } const width = arg.end.col - arg.start.col + 1; @@ -264,7 +263,8 @@ MyCustomPlugin.implementedFunctions = { ### Validate the arguments and return an error -To handle invalid inputs, the custom function should return an instance of the [`CellError` class](../api/classes/cellerror.md). Check the available [error types](types-of-errors.md). Errors are localized according to your [language settings](localizing-functions.md). +To handle invalid inputs, the custom function should return an instance of the [`CellError` class](../api/classes/cellerror.md) with the relevant [error type](types-of-errors.md). +Errors are localized according to your [language settings](localizing-functions.md). ```js if (rangeData.some(row => row.some(val => typeof rawValue !== 'number'))) { @@ -278,7 +278,7 @@ All HyperFormula [error types](types-of-errors.md) support optional custom error ### Test your function -You may add unit tests to make sure that your custom function works correctly using one of the JavaScript testing libraries. +You may add unit tests to ensure your custom function works correctly using one of the JavaScript testing libraries. ```js it('works for a range of numbers', () => { @@ -330,7 +330,7 @@ You can set the following options for your function: | `method` (required) | String | Name of the method that implements the custom function logic. | | `parameters` | Array | Specification of the arguments accepted by the function and their [validation options](#argument-validation-options). | | `arraySizeMethod` | String | Name of the method that calculates the size of the result array. Not required for functions that never return an array. | -| `returnNumberType` | String | If function returns a numeric value, this option indicates the way to interpret the returned number.
Possible values: `NUMBER_RAW, NUMBER_DATE, NUMBER_TIME, NUMBER_DATETIME, NUMBER_CURRENCY, NUMBER_PERCENT`.
Default: `NUMBER_RAW` | +| `returnNumberType` | String | If the function returns a numeric value, this option indicates how to interpret the returned number.
Possible values: `NUMBER_RAW, NUMBER_DATE, NUMBER_TIME, NUMBER_DATETIME, NUMBER_CURRENCY, NUMBER_PERCENT`.
Default: `NUMBER_RAW` | | `repeatLastArgs` | Number | For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely.
Default: `0` | | `expandRanges` | Boolean | `true`: ranges in the function's arguments are inlined to (possibly multiple) scalar arguments.
Default: `false` | | `isVolatile` | Boolean | `true`: the function is [volatile](volatile-functions.md).
Default: `false` | @@ -359,16 +359,16 @@ MyCustomPlugin.implementedFunctions = { You can set the following argument validation options: -| Option | Type | Description | -|---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | -| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | -| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | +| Option | Type | Description | +|---------------------------|-------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | +| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | +| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | | `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).
Default: `false`
Setting this option to `true` is the same as setting `defaultValue` to `undefined`. | -| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | -| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | -| `lessThan` | Number | If set: numerical argument need to be less than `lessThan`. | -| `greaterThan` | Number | If set: numerical argument need to be greater than `greaterThan`. | +| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | +| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | +| `lessThan` | Number | If set: numerical argument needs to be less than `lessThan`. | +| `greaterThan` | Number | If set: numerical argument needs to be greater than `greaterThan`. | In your function plugin, in the static `implementedFunctions` property, add an array called `parameters`: From 56fe511f7b9fad6fc1b0f43c15958f44ddd56fed Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 14 Dec 2022 21:11:07 +0100 Subject: [PATCH 24/29] Reformat table --- docs/guide/custom-functions.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 153d795590..a3c8158d37 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -359,16 +359,16 @@ MyCustomPlugin.implementedFunctions = { You can set the following argument validation options: -| Option | Type | Description | -|---------------------------|-------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | -| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | -| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | +| Option | Type | Description | +|---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | +| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | +| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | | `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).
Default: `false`
Setting this option to `true` is the same as setting `defaultValue` to `undefined`. | -| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | -| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | -| `lessThan` | Number | If set: numerical argument needs to be less than `lessThan`. | -| `greaterThan` | Number | If set: numerical argument needs to be greater than `greaterThan`. | +| `minValue` | Number | If set: numerical arguments need to be greater than or equal to `minValue`. | +| `maxValue` | Number | If set: numerical arguments need to be less than or equal to `maxValue`. | +| `lessThan` | Number | If set: numerical argument needs to be less than `lessThan`. | +| `greaterThan` | Number | If set: numerical argument needs to be greater than `greaterThan`. | In your function plugin, in the static `implementedFunctions` property, add an array called `parameters`: From 32556e459ca1550fbf31a0e2dbe5e0ce9f46ae31 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Thu, 15 Dec 2022 17:21:56 +0100 Subject: [PATCH 25/29] Improve the description of the vectorization feature --- docs/guide/arrays.md | 33 +++++++++++++++++---------------- docs/guide/custom-functions.md | 2 +- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/docs/guide/arrays.md b/docs/guide/arrays.md index 000748eeb8..fa06dfce3b 100644 --- a/docs/guide/arrays.md +++ b/docs/guide/arrays.md @@ -72,7 +72,7 @@ ISEVEN(A2:A5*10) Thanks to HyperFormula's built-in array features, you can: * [Operate on arrays](#operating-on-arrays) just like on [scalars](#about-arrays) -* [Pass arrays to functions](#passing-arrays-to-scalar-functions) that accept [scalars](#about-arrays) +* [Pass arrays to functions](#passing-arrays-to-scalar-functions-vectorization) that accept [scalars](#about-arrays) * [Broadcast](#broadcasting) smaller input arrays across larger output areas You can also: @@ -83,7 +83,7 @@ You can also: You can operate on arrays just like on single values. -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled, each output array value is the result of your operation on the corresponding input array value. +When the [array arithmetic mode](#array-arithmetic-mode) is enabled, each output array value is the result of your operation on the corresponding input array value. ``` =ARRAYFORMULA(A2:A5*B2:B5) @@ -95,22 +95,23 @@ When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled // =A5*B5 ``` -### Passing arrays to scalar functions -You can pass arrays to functions that would normally accept [scalars](#about-arrays) (thanks to HyperFormula's **vectorization** feature). +### Passing arrays to scalar functions (vectorization) -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled, and you pass an array to a [scalar](#about-arrays) function, that function produces an array on the output as well. +When the [array arithmetic mode](#array-arithmetic-mode) is enabled, HyperFormula automatically _vectorizes_ most functions. + +As a consequence of that, you can pass arrays to functions that would normally accept [scalars](#about-arrays). The result would also be an array. ``` -=ARRAYFORMULA(ISEVEN(A2:A5*10)) +=ARRAYFORMULA(ISEVEN(A2:A5)) // calculates: -// =ISEVEN(A2*10) -// =ISEVEN(A3*10) -// =ISEVEN(A4*10) -// =ISEVEN(A5*10) +// =ISEVEN(A2) +// =ISEVEN(A3) +// =ISEVEN(A4) +// =ISEVEN(A5) ``` -#### Broadcasting +### Broadcasting If an input array has a dimension of `1`, it's automatically repeated ("broadcast") on that dimension to match the size of the output. @@ -126,7 +127,7 @@ If an input array has a dimension of `1`, it's automatically repeated ("broadcas ### Filtering an array -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled, you can filter an array, based on boolean arrays, using the `FILTER` function: +When the [array arithmetic mode](#array-arithmetic-mode) is enabled, you can filter an array, based on boolean arrays, using the `FILTER` function: | Syntax | Example | |:-----------------------------------------------------|:------------------------------------------------| @@ -134,7 +135,7 @@ When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled ### Constraining an array's size -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled, you can constrain the size of the output array, using the `ARRAY_CONSTRAIN` function: +When the [array arithmetic mode](#array-arithmetic-mode) is enabled, you can constrain the size of the output array, using the `ARRAY_CONSTRAIN` function: | Syntax | Example | |:-------------------------------------------|:----------------------------------------------| @@ -148,7 +149,7 @@ If your specified output array size is larger or equal to the input array size, ### With the array arithmetic mode enabled -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled, and you pass an array to a [scalar](#about-arrays) function, the following rules apply: +When the [array arithmetic mode](#array-arithmetic-mode) is enabled, and you pass an array to a [scalar](#about-arrays) function, the following rules apply: * Array dimensions need to be consistent (e.g. every row needs to be of the same length). * If an input array value is missing (due to a difference in dimensions), the corresponding output array value is `#N/A`. * If a cell evaluates to an array, the array values are spilled into neighboring cells (unless the neighboring cells are already filled).
This behavior doesn't apply to ranges, which return the `#VALUE!` error in this case. @@ -156,9 +157,9 @@ When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is enabled ### With the array arithmetic mode disabled -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is disabled, and you pass an array to a [scalar](#about-arrays) function, the array is reduced to 1 element (usually the array's top-left value). +When the [array arithmetic mode](#array-arithmetic-mode) is disabled, and you pass an array to a [scalar](#about-arrays) function, the array is reduced to 1 element (usually the array's top-left value). -When the [array arithmetic mode](#enabling-the-array-arithmetic-mode) is disabled, and you operate on a range of width/height equal to `1`, the behavior depends on your array formula's location: +When the [array arithmetic mode](#array-arithmetic-mode) is disabled, and you operate on a range of width/height equal to `1`, the behavior depends on your array formula's location: | Your array formula's location | Behavior | |:--------------------------------------------------|:---------------------------------------| diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index a3c8158d37..e40316610f 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -337,7 +337,7 @@ You can set the following options for your function: | `isDependentOnSheetStructureChange` | Boolean | `true`: the function gets recalculated with each sheet shape change (e.g., when adding/removing rows or columns).
Default: `false` | | `doesNotNeedArgumentsToBeComputed` | Boolean | `true`: the function treats reference or range arguments as arguments that don't create dependency (other arguments are properly evaluated).
Default: `false` | | `arrayFunction` | Boolean | `true`: the function enables the [array arithmetic mode](arrays.md) in its arguments and nested expressions.
Default: `false` | -| `vectorizationForbidden` | Boolean | `true`: the function will never get vectorized.
Default: `false` | +| `vectorizationForbidden` | Boolean | `true`: the function will never get [vectorized](arrays.md#passing-arrays-to-scalar-functions-vectorization).
Default: `false` | The options listed above are set in the static `implementedFunctions` property of your function plugin: From aef856bf77082e2d9d54fcccda2f4de90dd4a279 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 20 Dec 2022 17:32:39 +0100 Subject: [PATCH 26/29] code review fixes --- docs/guide/custom-functions.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index e40316610f..e1165e5722 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -135,7 +135,7 @@ console.log(result); The complete implementation of this custom function is also included in the [demo](#working-demo). ```js -import { FunctionPlugin, CellError } from 'hyperformula'; +import { FunctionPlugin } from 'hyperformula'; export class MyCustomPlugin extends FunctionPlugin { greet(ast, state) { @@ -210,7 +210,7 @@ export class MyCustomPlugin extends FunctionPlugin { ### Return an array of data -A function may return multiple values in the form of an array. To do that, use [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): +A function may return multiple values in the form of an [array](arrays.md). To do that, use [`SimpleRangeValue` class](../api/classes/simplerangevalue.md): ```js export class MyCustomPlugin extends FunctionPlugin { @@ -228,11 +228,8 @@ export class MyCustomPlugin extends FunctionPlugin { } ``` -You also need to provide the `arraySizeMethod` that calculates the size of the result array based on the function arguments and returns an instance of the [`ArraySize` class](../api/classes/arraysize.md). - -::: tip -If you don't define the `arraySizeMethod`, returning an array will cause the `#VALUE!` error. -::: +A function that returns an array will cause the `VALUE!` error unless you also declare a companion method for the array size. +To do that, provide the `arraySizeMethod` that calculates the size of the result array based on the function arguments and returns an instance of the [`ArraySize` class](../api/classes/arraysize.md). ```js export class MyCustomPlugin extends FunctionPlugin { From f629630d4d66fd44f48607e34f8aaeeb66cf93a0 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 20 Dec 2022 18:19:05 +0100 Subject: [PATCH 27/29] Change translations object to be standalone instead of a static property in the custom functions guide --- docs/guide/custom-functions.md | 31 ++++++++++--------------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index e1165e5722..85f069cfc1 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -62,10 +62,10 @@ MyCustomPlugin.implementedFunctions = { ### 3. Add your function's names -In your function plugin, in the static `translations` property, [define your function's names in every language you want to support](#function-name-translations). +In a separate object, [define your function's names in every language you want to support](#function-name-translations). ```js -MyCustomPlugin.translations = { +export const MyCustomPluginTranslations = { enGB: { GREET: "GREET", }, @@ -109,7 +109,7 @@ Register your function plugin (and its translations) so that HyperFormula can re Use the [`registerFunctionPlugin()`](../api/classes/hyperformula.md#registerfunctionplugin) method: ```js -HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); +HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPluginTranslations); ``` ### 6. Use your custom function inside a formula @@ -159,7 +159,7 @@ MyCustomPlugin.implementedFunctions = { } }; -MyCustomPlugin.translations = { +export const MyCustomPluginTranslations = { enGB: { GREET: 'GREET', }, @@ -168,7 +168,7 @@ MyCustomPlugin.translations = { } }; -HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); +HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPluginTranslations); ``` ## Advanced custom function example @@ -279,7 +279,7 @@ You may add unit tests to ensure your custom function works correctly using one ```js it('works for a range of numbers', () => { - HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); + HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPluginTranslations); const engine = HyperFormula.buildFromArray([ [1, '=DOUBLE_RANGE(A1:A3)'], @@ -293,7 +293,7 @@ it('works for a range of numbers', () => { }); it('returns a VALUE error if the range argument contains a string', () => { - HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); + HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPluginTranslations); const engine = HyperFormula.buildFromArray([ [1, '=DOUBLE_RANGE(A1:A3)'], @@ -403,11 +403,11 @@ Your end users use the translated names to call your function inside formulas. If you support just one language, you still need to define the name of your function in that language. ::: -Define the translations for every language you want to support in the static `translations` property. +In a separate object, define the translations of your custom functions' names in every language you want to support. Function names are case-insensitive, as they are all normalized to uppercase. ```js -MyCustomPlugin.translations = { +export const MyCustomPluginTranslations = { enGB: { // formula in English: `=MY_FUNCTION()` 'MY_FUNCTION': 'MY_FUNCTION' @@ -420,18 +420,7 @@ MyCustomPlugin.translations = { }; // register your function plugin and translations -HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPlugin.translations); -``` - -You can also define `translations` as a standalone object: - -```js -export const MyFunctionNameTranslations = { - // ... -}; - -// register your function plugin and translations -HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyFunctionNameTranslations); +HyperFormula.registerFunctionPlugin(MyCustomPlugin, MyCustomPluginTranslations); ``` ::: tip From efe66ef6efab30f9d573ad8ef27462e95888ba80 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 20 Dec 2022 18:54:32 +0100 Subject: [PATCH 28/29] Use FunctionArgumentType enum in custom functions guide --- docs/guide/custom-functions.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 85f069cfc1..711e7d63b6 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -35,12 +35,14 @@ In your function's object, you can specify: - other [custom function options](#custom-function-options). ```js +import { FunctionPlugin, FunctionArgumentType } from 'hyperformula'; + MyCustomPlugin.implementedFunctions = { // let's define the function's ID as `GREET` GREET: { method: "greet", parameters: [ - { argumentType: "STRING" } + { argumentType: FunctionArgumentType.STRING } ], } }; @@ -135,7 +137,7 @@ console.log(result); The complete implementation of this custom function is also included in the [demo](#working-demo). ```js -import { FunctionPlugin } from 'hyperformula'; +import { FunctionPlugin, FunctionArgumentType } from 'hyperformula'; export class MyCustomPlugin extends FunctionPlugin { greet(ast, state) { @@ -154,7 +156,7 @@ MyCustomPlugin.implementedFunctions = { GREET: { method: 'greet', parameters: [ - { argumentType: 'STRING' } + { argumentType: FunctionArgumentType.STRING } ], } }; @@ -184,7 +186,7 @@ MyCustomPlugin.implementedFunctions = { DOUBLE_RANGE: { method: 'doubleRange', parameters: [ - { argumentType: 'RANGE' }, + { argumentType: FunctionArgumentType.RANGE }, ], } }; @@ -252,7 +254,7 @@ MyCustomPlugin.implementedFunctions = { method: 'doubleRange', arraySizeMethod: 'doubleRangeResultArraySize', parameters: [ - { argumentType: 'RANGE' }, + { argumentType: FunctionArgumentType.RANGE }, ], } }; @@ -358,7 +360,7 @@ You can set the following argument validation options: | Option | Type | Description | |---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `argumentType` (required) | String | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | +| `argumentType` (required) | `FunctionArgumentType` | Expected type of the argument. Possible values: `STRING, NUMBER, BOOLEAN, SCALAR, NOERROR, RANGE, INTEGER, COMPLEX, ANY`. | | `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. | | `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).
Default: `false` | | `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).
Default: `false`
Setting this option to `true` is the same as setting `defaultValue` to `undefined`. | From 318d0947204874d106be85696e13249d77d8daf7 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Tue, 20 Dec 2022 19:58:37 +0100 Subject: [PATCH 29/29] Fix typo --- docs/guide/custom-functions.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 711e7d63b6..689e0b0da4 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -52,10 +52,10 @@ MyCustomPlugin.implementedFunctions = { To define multiple functions in a single function plugin, add them all to the `implementedFunctions` object. ```js MyCustomPlugin.implementedFunctions = { - GREET: { + FUNCTION_A: { //... - }, - FAREWELL: { + }, + FUNCTION_B: { //... }, };