Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
154630c
Add description of the function argument types to the custom-function…
sequba Jan 10, 2023
fdfba73
Refactor the argument validation part of the runFunction method
sequba Jan 11, 2023
aa20522
Refactor FunctionPlugin.runFunction
sequba Jan 13, 2023
12da266
Improve formatting in file FormulaParser.ts
sequba Jan 25, 2023
937e383
Make description of MATCH function more accurate
sequba Jan 25, 2023
bd7297c
Adjust eslint jsdoc configuration
sequba Jan 26, 2023
57ea05a
Refactor runFunction
sequba Jan 27, 2023
91fe222
Refactor runFunction
sequba Feb 7, 2023
098a2c5
Make boolean functions handle empty values properly
sequba Feb 7, 2023
ef88986
Describe the features of the runFunction method in the custom-functio…
sequba Feb 7, 2023
bdd1adc
Add unit tests for handling strings by boolean functios
sequba Feb 8, 2023
a55ee51
Add typedoc strings to SimpleRangeValue class
sequba Feb 8, 2023
b90613c
Add unit test for vectorization of an array function
sequba Feb 8, 2023
f7c393c
Apply grammarly suggestions
sequba Feb 8, 2023
4185307
Fix cross-documentation references
sequba Feb 8, 2023
123fe32
Merge branch 'develop' into feature/issue-1123
sequba Feb 8, 2023
32c2c9b
Fix karma/chevrotain warnings
sequba Feb 8, 2023
f7d0670
Fix unit tests for karma
sequba Feb 8, 2023
543b469
Merge branch 'develop' into feature/issue-1123
sequba Mar 1, 2023
6d7e980
Mark MatchType argument as optional in the built-in-functions guide
sequba Mar 1, 2023
80107c0
Update custom-functions.md
sequba Mar 1, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ module.exports = {
"jsdoc/check-alignment": 'warn',
"jsdoc/check-param-names": 'warn',
"jsdoc/check-property-names": 'warn',
"jsdoc/check-tag-names": 'warn',
"jsdoc/check-tag-names": ['warn', {definedTags: ['category']}],
"jsdoc/check-types": 'warn',
"jsdoc/empty-tags": 'warn',
"jsdoc/implements-on-classes": 'warn',
Expand All @@ -90,9 +90,7 @@ module.exports = {
"jsdoc/require-returns-check": 'warn',
"jsdoc/require-returns-description": 'warn',
"jsdoc/require-returns-type": 'warn',
"jsdoc/require-yields": 'warn',
"jsdoc/require-yields-check": 'warn',
"jsdoc/tag-lines": 'warn',
"jsdoc/valid-types": 'warn',
"jsdoc/require-jsdoc": ['warn', {
require: {
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/built-in-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ Total number of functions: **{{ $page.functionsCount }}**
| FORMULATEXT | Returns a formula in a given cell as a string. | FORMULATEXT(Reference) |
| HLOOKUP | Searches horizontally with reference to adjacent cells to the bottom. | HLOOKUP(Search_Criterion, Array, Index, Sort_Order) |
| INDEX | Returns the contents of a cell specified by row and column number. The column number is optional and defaults to 1. | INDEX(Range, Row [, Column]) |
| MATCH | Returns the relative position of an item in an array that matches a specified value. | MATCH(Searchcriterion, Lookuparray, Type) |
| MATCH | Returns the relative position of an item in an array that matches a specified value. | MATCH(Searchcriterion, Lookuparray [, MatchType]) |
| OFFSET | Returns the value of a cell offset by a certain number of rows and columns from a given reference point. | OFFSET(Reference, Rows, Columns, Height, Width) |
| ROW | Returns row number of a given reference or formula reference if argument not provided. | ROW([Reference]) |
| ROWS | Returns the number of rows in the given reference. | ROWS(Array) |
Expand Down
34 changes: 27 additions & 7 deletions docs/guide/custom-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ In your function plugin, in the static `implementedFunctions` property, define a
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:
In your function's object, you can specify the following:
- 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](#function-options).
Expand Down Expand Up @@ -84,10 +84,16 @@ In your function plugin, add a method that implements your function's calculatio
* Take two optional arguments: `ast` and `state`.
* Return the results of your calculations.

To benefit from HyperFormula's automatic validations, wrap your method in the built-in `runFunction()` method, which:
* Verifies the format of the values returned by your function.
* Validates your function's parameters against your [custom function options](#function-options).
* Validates arguments passed to your function against your [argument validation options](#argument-validation-options).
Wrap your implementation in the built-in `runFunction()` method, which:
- evaluates the arguments of your custom function
- validates the number of arguments according to the [`parameters` array](#function-options)
- performs coercion of the argument values to types set in the [`parameters` array](#argument-validation-options)
- handles optional arguments and default values according to options set in the [`parameters` array](#argument-validation-options)
- validates the arguments of your custom function against the [argument validation options](#argument-validation-options)
- duplicates the arguments according to [`repeatLastArgs` option](#function-options)
- handles [array arithmetic mode](arrays.md#array-arithmetic-mode)
- performs [function vectorization](arrays.md#passing-arrays-to-scalar-functions-vectorization)
- performs [argument broadcasting](arrays.md#broadcasting)

```js
export class MyCustomPlugin extends FunctionPlugin {
Expand Down Expand Up @@ -366,7 +372,7 @@ You can set the following argument validation options:

| Option | Type | Description |
|---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `argumentType` (required) | `FunctionArgumentType` | Expected type of the argument. Possible values: `STRING`, `NUMBER`, `BOOLEAN`, `SCALAR`, `NOERROR`, `RANGE`, `INTEGER`, `COMPLEX`, `ANY`. |
| `argumentType` (required) | `FunctionArgumentType` | Expected type of the function argument. See [possible values](#types-of-the-function-argument). |
| `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`).<br/>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).<br/>Default: `false`<br/>Setting this option to `true` is the same as setting `defaultValue` to `undefined`. |
Expand Down Expand Up @@ -395,7 +401,21 @@ MyCustomPlugin.implementedFunctions = {
};
```

#### Handling missing arguments
### Types of the function argument

| Type | Description | Example |
|-----------|----------------------------------------------------------------------------------------------------------|----------------------------------------------|
| `NUMBER` | A general numeric value such as floating-point number, date/time value, currency value or percent value. | `3`, `3.14`, `$100`, `1939/09/01`, `4:45 AM` |
| `INTEGER` | An integer. | `42` |
| `COMPLEX` | A text representing a complex value. | `"-3+4i"` |
| `STRING` | A text value. | `"aaa"` |
| `BOOLEAN` | A logical value. | `=TRUE()` |
| `NOERROR` | Any non-range and non-error value. | All of the above |
| `SCALAR` | Any non-range value. | All of the above |
| `RANGE` | Multiple values as a range of cells or an inline array. | `A1:B100`, `{1, 2}` |
| `ANY` | Any value. | All of the above |

### Handling missing arguments

Both the `defaultValue` and `optionalArg` options let you decide what happens when a user doesn't pass enough valid arguments to your custom function.

Expand Down
95 changes: 85 additions & 10 deletions src/SimpleRangeValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,60 +10,101 @@ import {DependencyGraph} from './DependencyGraph'
import {ErrorMessage} from './error-message'
import {InternalScalarValue, isExtendedNumber} from './interpreter/InterpreterValue'


/**
* A class that represents a range of data.
*/
export class SimpleRangeValue {

/**
* A property representing the size of the range.
*/
public readonly size: ArraySize

/**
* In most cases it's more convenient to create a SimpleRangeValue object by calling one of the static factory methods.
*/
constructor(
private _data?: InternalScalarValue[][],

/**
* A property representing the address of the range.
*/
public readonly range?: AbsoluteCellRange,
private readonly dependencyGraph?: DependencyGraph,
private _hasOnlyNumbers?: boolean,
) {
if (_data === undefined) {
this.size = new ArraySize(range!.effectiveWidth(dependencyGraph!), range!.effectiveHeight(dependencyGraph!))
} else {
this.size = new ArraySize(_data[0].length, _data.length)
}
this.size = _data === undefined
? new ArraySize(range!.effectiveWidth(dependencyGraph!), range!.effectiveHeight(dependencyGraph!))
: new ArraySize(_data[0].length, _data.length)
}

/**
* Returns the range data as a 2D-array.
*/
public get data(): InternalScalarValue[][] {
this.ensureThatComputed()
return this._data!
}

/**
* Factory method. Returns a SimpleRangeValue object with address and provided data.
*/
public static fromRange(data: InternalScalarValue[][], range: AbsoluteCellRange, dependencyGraph: DependencyGraph): SimpleRangeValue {
return new SimpleRangeValue(data, range, dependencyGraph, true)
}

/**
* Factory method. Returns a SimpleRangeValue object with provided numeric data.
*/
public static onlyNumbers(data: number[][]): SimpleRangeValue {
return new SimpleRangeValue(data, undefined, undefined, true)
}

/**
* Factory method. Returns a SimpleRangeValue object with provided data.
*/
public static onlyValues(data: InternalScalarValue[][]): SimpleRangeValue {
return new SimpleRangeValue(data, undefined, undefined, undefined)
}

/**
* Factory method. Returns a SimpleRangeValue object with address.
*/
public static onlyRange(range: AbsoluteCellRange, dependencyGraph: DependencyGraph): SimpleRangeValue {
return new SimpleRangeValue(undefined, range, dependencyGraph, undefined)
}

/**
* Factory method. Returns a SimpleRangeValue object containing the single value.
*/
public static fromScalar(scalar: InternalScalarValue): SimpleRangeValue {
return new SimpleRangeValue([[scalar]], undefined, undefined, undefined)
}

/**
* Returns true if and only if the SimpleRangeValue has no address set.
*/
public isAdHoc(): boolean {
return this.range === undefined
}

/**
* Returns the number of columns contained in the range.
*/
public width(): number {
return this.size.width //should be equal to this.data[0].length
return this.size.width
}

/**
* Returns the number of rows contained in the range.
*/
public height(): number {
return this.size.height //should be equal to this.data.length
return this.size.height
}

/**
* Returns the range data as a 1D-array.
*/
public valuesFromTopLeftCorner(): InternalScalarValue[] {
this.ensureThatComputed()

Expand All @@ -77,6 +118,9 @@ export class SimpleRangeValue {
return ret
}

/**
* Generates the addresses of the cells contained in the range assuming the provided address is the left corner of the range.
*/
public* effectiveAddressesFromData(leftCorner: SimpleCellAddress): IterableIterator<SimpleCellAddress> {
for (let row = 0; row < this.data.length; ++row) {
const rowData = this.data[row]
Expand All @@ -86,6 +130,11 @@ export class SimpleRangeValue {
}
}

/**
* Generates both values and addresses of the cells contained in the range assuming the provided address is the left corner of the range.
*
* This method combines the functionalities of `iterateValuesFromTopLeftCorner` and `effectiveAddressesFromData`.
*/
public* entriesFromTopLeftCorner(leftCorner: SimpleCellAddress): IterableIterator<[InternalScalarValue, SimpleCellAddress]> {
this.ensureThatComputed()
for (let row = 0; row < this.size.height; ++row) {
Expand All @@ -95,15 +144,24 @@ export class SimpleRangeValue {
}
}

/**
* Generates the values of the cells contained in the range assuming the provided address is the left corner of the range.
*/
public* iterateValuesFromTopLeftCorner(): IterableIterator<InternalScalarValue> {
yield* this.valuesFromTopLeftCorner()
}

/**
* Returns the number of cells contained in the range.
*/
public numberOfElements(): number {
return this.size.width * this.size.height
}

public hasOnlyNumbers() {
/**
* Returns true if and only if the range contains only numeric values.
*/
public hasOnlyNumbers(): boolean {
if (this._hasOnlyNumbers === undefined) {
this._hasOnlyNumbers = true
for (const row of this.data) {
Expand All @@ -119,20 +177,37 @@ export class SimpleRangeValue {
return this._hasOnlyNumbers
}

/**
* Returns the range data as a 2D-array of numbers.
*
* Internal use only.
*/
public rawNumbers(): number[][] {
return this._data as number[][]
}


/**
* Returns the range data as a 2D-array.
*
* Internal use only.
*/
public rawData(): InternalScalarValue[][] {
this.ensureThatComputed()
return this._data ?? []
}

/**
* Returns true if and only if the range has the same width and height as the provided range object.
*/
public sameDimensionsAs(other: SimpleRangeValue): boolean {
return this.width() === other.width() && this.height() === other.height()
}

private ensureThatComputed() {
/**
* Computes the range data if it is not computed yet.
*/
private ensureThatComputed(): void {
if (this._data !== undefined) {
return
}
Expand Down
6 changes: 3 additions & 3 deletions src/interpreter/plugin/BooleanPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
*/
public and(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('AND'),
(...args) => !args.some((arg: boolean) => !arg)
(...args) => args.filter((arg: boolean | undefined) => arg !== undefined).every((arg: boolean) => !!arg)
Comment thread
adamu-handsontable marked this conversation as resolved.
Resolved
)
}

Expand All @@ -156,7 +156,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
*/
public or(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('OR'),
(...args) => args.some((arg: boolean) => arg)
(...args) => args.filter((arg: boolean | undefined) => arg !== undefined).some((arg: boolean) => arg)
Comment thread
sequba marked this conversation as resolved.
Resolved
)
}

Expand All @@ -167,7 +167,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
public xor(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunction(ast.args, state, this.metadata('XOR'), (...args) => {
let cnt = 0
args.forEach((arg: boolean) => {
args.filter((arg: boolean | undefined) => arg !== undefined).forEach((arg: boolean) => {
Comment thread
sequba marked this conversation as resolved.
Resolved
if (arg) {
cnt++
}
Expand Down
Loading