Tinymath is now a Kibana package (#89383)

* Tinymath is now a Kibana package

* Rename to @kbn/tinymath

* Update import style

* Update README

* Use commonjs import syntax

* Fix to commonjs export

* More commonjs fixes
This commit is contained in:
Wylie Conlon 2021-01-28 13:58:37 -05:00 committed by GitHub
parent af88e024fa
commit ac39321fc5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
102 changed files with 5115 additions and 17 deletions

View file

@ -36,6 +36,7 @@ snapshots.js
# package overrides
/packages/elastic-eslint-config-kibana
/packages/kbn-interpreter/src/common/lib/grammar.js
/packages/kbn-tinymath/src/grammar.js
/packages/kbn-plugin-generator/template
/packages/kbn-pm/dist
/packages/kbn-test/src/functional_test_runner/__tests__/fixtures/

View file

@ -312,7 +312,7 @@
"tabbable": "1.1.3",
"tar": "4.4.13",
"tinygradient": "0.4.3",
"tinymath": "1.2.1",
"@kbn/tinymath": "link:packages/kbn-tinymath",
"tree-kill": "^1.2.2",
"ts-easing": "^0.2.0",
"tslib": "^2.0.0",
@ -847,4 +847,4 @@
"yargs": "^15.4.1",
"zlib": "^1.0.5"
}
}
}

View file

@ -65,6 +65,11 @@ module.exports = {
to: false,
disallowedMessage: `Don't import monaco directly, use or add exports to @kbn/monaco`
},
{
from: 'tinymath',
to: '@kbn/tinymath',
disallowedMessage: `Don't use 'tinymath', use '@kbn/tinymath'`
},
],
],
},

View file

@ -216,7 +216,6 @@ export function getWebpackConfig(bundle: Bundle, bundleRefs: BundleRefs, worker:
extensions: ['.js', '.ts', '.tsx', '.json'],
mainFields: ['browser', 'main'],
alias: {
tinymath: require.resolve('tinymath/lib/tinymath.es5.js'),
core_app_image_assets: Path.resolve(worker.repoRoot, 'src/core/public/core_app/images'),
},
},

View file

@ -0,0 +1,72 @@
# kbn-tinymath
kbn-tinymath is a tiny arithmetic and function evaluator for simple numbers and arrays. Named properties can be accessed from an optional scope parameter.
It's available as an expression function called `math` in Canvas, and the grammar/AST structure is available
for use by Kibana plugins that want to use math.
See [Function Documentation](/docs/functions.md) for details on built-in functions available in Tinymath.
```javascript
const { evaluate } = require('@kbn/tinymath');
// Simple math
evaluate('10 + 20'); // 30
evaluate('round(3.141592)') // 3
// Named properties
evaluate('foo + 20', {foo: 5}); // 25
// Arrays
evaluate('bar + 20', {bar: [1, 2, 3]}); // [21, 22, 23]
evaluate('bar + baz', {bar: [1, 2, 3], baz: [4, 5, 6]}); // [5, 7, 9]
evaluate('multiply(bar, baz) / 10', {bar: [1, 2, 3], baz: [4, 5, 6]}); // [0.4, 1, 1.8]
```
### Adding Functions
Functions can be injected, and built in function overwritten, via the 3rd argument to `evaluate`:
```javascript
const { evaluate } = require('@kbn/tinymath');
evaluate('plustwo(foo)', {foo: 5}, {
plustwo: function(a) {
return a + 2;
}
}); // 7
```
### Parsing
You can get to the parsed AST by importing `parse`
```javascript
const { parse } = require('@kbn/tinymath');
parse('1 + random()')
/*
{
"name": "add",
"args": [
1,
{
"name": "random",
"args": []
}
]
}
*/
```
#### Notes
* Floating point operations have the normal Javascript limitations
### Building kbn-tinymath
This package is rebuilt when running `yarn kbn bootstrap`, but can also be build directly
using `yarn build` from the `packages/kbn-tinymath` directory.
### Running tests
To test `@kbn/tinymath` from Kibana, run `yarn run jest --watch packages/kbn-tinymath` from
the top level of Kibana.

View file

@ -0,0 +1,19 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
module.exports = {
env: {
web: {
presets: ['@kbn/babel-preset/webpack_preset'],
},
node: {
presets: ['@kbn/babel-preset/node_preset'],
},
},
ignore: ['**/*.test.ts', '**/*.test.tsx'],
};

View file

@ -0,0 +1,687 @@
# TinyMath Functions
This document provides detailed information about the functions available in Tinymath and lists what parameters each function accepts, the return value of that function, and examples of how each function behaves. Most of the functions below accept arrays and apply JavaScript Math methods to each element of that array. For the functions that accept multiple arrays as parameters, the function generally does calculation index by index. Any function below can be wrapped by another function as long as the return type of the inner function matches the acceptable parameter type of the outer function.
## _abs(_ _a_ _)_
Calculates the absolute value of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The absolute value of `a`. Returns an array with the the absolute values of each element if `a` is an array.
**Example**
```js
abs(-1) // returns 1
abs(2) // returns 2
abs([-1 , -2, 3, -4]) // returns [1, 2, 3, 4]
```
***
## _add(_ ..._args_ _)_
Calculates the sum of one or more numbers/arrays passed into the function. If at least one array of numbers is passed into the function, the function will calculate the sum by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The sum of all numbers in `args` if `args` contains only numbers. Returns an array of sums of the elements at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Throws**:
- `'Array length mismatch'` if `args` contains arrays of different lengths
**Example**
```js
add(1, 2, 3) // returns 6
add([10, 20, 30, 40], 10, 20, 30) // returns [70, 80, 90, 100]
add([1, 2], 3, [4, 5], 6) // returns [(1 + 3 + 4 + 6), (2 + 3 + 5 + 6)] = [14, 16]
```
***
## _cbrt(_ _a_ _)_
Calculates the cube root of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The cube root of `a`. Returns an array with the the cube roots of each element if `a` is an array.
**Example**
```js
cbrt(-27) // returns -3
cbrt(94) // returns 4.546835943776344
cbrt([27, 64, 125]) // returns [3, 4, 5]
```
***
## _ceil(_ _a_ _)_
Calculates the ceiling of a number, i.e. rounds a number towards positive infinity. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The ceiling of `a`. Returns an array with the the ceilings of each element if `a` is an array.
**Example**
```js
ceil(1.2) // returns 2
ceil(-1.8) // returns -1
ceil([1.1, 2.2, 3.3]) // returns [2, 3, 4]
```
***
## _clamp(_ ..._a_, _min_, _max_ _)_
Restricts value to a given range and returns closed available value. If only min is provided, values are restricted to only a lower bound.
| Param | Type | Description |
| --- | --- | --- |
| ...a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
| min | <code>number</code> \| <code>Array.&lt;number&gt;</code> | The minimum value this function will return. |
| max | <code>number</code> \| <code>Array.&lt;number&gt;</code> | The maximum value this function will return. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The closest value between `min` (inclusive) and `max` (inclusive). Returns an array with values greater than or equal to `min` and less than or equal to `max` (if provided) at each index.
**Throws**:
- `'Array length mismatch'` if `a`, `min`, and/or `max` are arrays of different lengths
- `'Min must be less than max'` if `max` is less than `min`
- `'Missing minimum value. You may want to use the 'max' function instead'` if min is not provided
- `'Missing maximum value. You may want to use the 'min' function instead'` if max is not provided
**Example**
```js
clamp(1, 2, 3) // returns 2
clamp([10, 20, 30, 40], 15, 25) // returns [15, 20, 25, 25]
clamp(10, [15, 2, 4, 20], 25) // returns [15, 10, 10, 20]
clamp(35, 10, [20, 30, 40, 50]) // returns [20, 30, 35, 35]
clamp([1, 9], 3, [4, 5]) // returns [clamp([1, 3, 4]), clamp([9, 3, 5])] = [3, 5]
```
***
## _cos(_ _a_ _)_
Calculates the the cosine of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` is expected to be given in radians. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The cosine of `a`. Returns an array with the the cosine of each element if `a` is an array.
**Example**
```js
cos(0) // returns 1
cos(1.5707963267948966) // returns 6.123233995736766e-17
cos([0, 1.5707963267948966]) // returns [1, 6.123233995736766e-17]
```
***
## _count(_ _a_ _)_
Returns the length of an array. Alias for size
| Param | Type | Description |
| --- | --- | --- |
| a | <code>Array.&lt;any&gt;</code> | array of any values |
**Returns**: <code>number</code> - The length of the array. Returns 1 if `a` is not an array.
**Throws**:
- `'Must pass an array'` if `a` is not an array
**Example**
```js
count([]) // returns 0
count([-1, -2, -3, -4]) // returns 4
count(100) // returns 1
```
***
## _cube(_ _a_ _)_
Calculates the cube of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The cube of `a`. Returns an array with the the cubes of each element if `a` is an array.
**Example**
```js
cube(-3) // returns -27
cube([3, 4, 5]) // returns [27, 64, 125]
```
***
## _degtorad(_ _a_ _)_
Converts degrees to radians for a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` is expected to be given in degrees. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The radians of `a`. Returns an array with the the radians of each element if `a` is an array.
**Example**
```js
degtorad(0) // returns 0
degtorad(90) // returns 1.5707963267948966
degtorad([0, 90, 180, 360]) // returns [0, 1.5707963267948966, 3.141592653589793, 6.283185307179586]
```
***
## _divide(_ _a_, _b_ _)_
Divides two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | dividend, a number or an array of numbers |
| b | <code>number</code> \| <code>Array.&lt;number&gt;</code> | divisor, a number or an array of numbers, `b` != 0 |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The quotient of `a` and `b` if both are numbers. Returns an array with the quotients applied index-wise to each element if `a` or `b` is an array.
**Throws**:
- `'Array length mismatch'` if `a` and `b` are arrays with different lengths
- `'Cannot divide by 0'` if `b` equals 0 or contains 0
**Example**
```js
divide(6, 3) // returns 2
divide([10, 20, 30, 40], 10) // returns [1, 2, 3, 4]
divide(10, [1, 2, 5, 10]) // returns [10, 5, 2, 1]
divide([14, 42, 65, 108], [2, 7, 5, 12]) // returns [7, 6, 13, 9]
```
***
## _exp(_ _a_ _)_
Calculates _e^x_ where _e_ is Euler&#x27;s number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - `e^a`. Returns an array with the values of `e^x` evaluated where `x` is each element of `a` if `a` is an array.
**Example**
```js
exp(2) // returns e^2 = 7.3890560989306495
exp([1, 2, 3]) // returns [e^1, e^2, e^3] = [2.718281828459045, 7.3890560989306495, 20.085536923187668]
```
***
## _first(_ _a_ _)_
Returns the first element of an array. If anything other than an array is passed in, the input is returned.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>Array.&lt;any&gt;</code> | array of any values |
**Returns**: <code>\*</code> - The first element of `a`. Returns `a` if `a` is not an array.
**Example**
```js
first(2) // returns 2
first([1, 2, 3]) // returns 1
```
***
## _fix(_ _a_ _)_
Calculates the fix of a number, i.e. rounds a number towards 0. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The fix of `a`. Returns an array with the the fixes for each element if `a` is an array.
**Example**
```js
fix(1.2) // returns 1
fix(-1.8) // returns -1
fix([1.8, 2.9, -3.7, -4.6]) // returns [1, 2, -3, -4]
```
***
## _floor(_ _a_ _)_
Calculates the floor of a number, i.e. rounds a number towards negative infinity. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The floor of `a`. Returns an array with the the floor of each element if `a` is an array.
**Example**
```js
floor(1.8) // returns 1
floor(-1.2) // returns -2
floor([1.7, 2.8, 3.9]) // returns [1, 2, 3]
```
***
## _last(_ _a_ _)_
Returns the last element of an array. If anything other than an array is passed in, the input is returned.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>Array.&lt;any&gt;</code> | array of any values |
**Returns**: <code>\*</code> - The last element of `a`. Returns `a` if `a` is not an array.
**Example**
```js
last(2) // returns 2
last([1, 2, 3]) // returns 3
```
***
## _log(_ _a_, _b_ _)_
Calculates the logarithm of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` must be greater than 0 |
| b | <code>Object</code> | (optional) base for the logarithm. If not provided a value, the default base is e, and the natural log is calculated. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The logarithm of `a`. Returns an array with the the logarithms of each element if `a` is an array.
**Throws**:
- `'Base out of range'` if `b` <= 0
- 'Must be greater than 0' if `a` > 0
**Example**
```js
log(1) // returns 0
log(64, 8) // returns 2
log(42, 5) // returns 2.322344707681546
log([2, 4, 8, 16, 32], 2) // returns [1, 2, 3, 4, 5]
```
***
## _log10(_ _a_ _)_
Calculates the logarithm base 10 of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` must be greater than 0 |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The logarithm of `a`. Returns an array with the the logarithms base 10 of each element if `a` is an array.
**Throws**:
- `'Must be greater than 0'` if `a` < 0
**Example**
```js
log(10) // returns 1
log(100) // returns 2
log(80) // returns 1.9030899869919433
log([10, 100, 1000, 10000, 100000]) // returns [1, 2, 3, 4, 5]
```
***
## _max(_ ..._args_ _)_
Finds the maximum value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the maximum by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The maximum value of all numbers if `args` contains only numbers. Returns an array with the the maximum values at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Throws**:
- `'Array length mismatch'` if `args` contains arrays of different lengths
**Example**
```js
max(1, 2, 3) // returns 3
max([10, 20, 30, 40], 15) // returns [15, 20, 30, 40]
max([1, 9], 4, [3, 5]) // returns [max([1, 4, 3]), max([9, 4, 5])] = [4, 9]
```
***
## _mean(_ ..._args_ _)_
Finds the mean value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the mean by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The mean value of all numbers if `args` contains only numbers. Returns an array with the the mean values of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Example**
```js
mean(1, 2, 3) // returns 2
mean([10, 20, 30, 40], 20) // returns [15, 20, 25, 30]
mean([1, 9], 5, [3, 4]) // returns [mean([1, 5, 3]), mean([9, 5, 4])] = [3, 6]
```
***
## _median(_ ..._args_ _)_
Finds the median value(s) of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the median by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The median value of all numbers if `args` contains only numbers. Returns an array with the the median values of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Example**
```js
median(1, 1, 2, 3) // returns 1.5
median(1, 1, 2, 2, 3) // returns 2
median([10, 20, 30, 40], 10, 20, 30) // returns [15, 20, 25, 25]
median([1, 9], 2, 4, [3, 5]) // returns [median([1, 2, 4, 3]), median([9, 2, 4, 5])] = [2.5, 4.5]
```
***
## _min(_ ..._args_ _)_
Finds the minimum value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the minimum by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The minimum value of all numbers if `args` contains only numbers. Returns an array with the the minimum values of each index, including all scalar numbers in `args` in the calculation at each index if `a` is an array.
**Throws**:
- `'Array length mismatch'` if `args` contains arrays of different lengths
**Example**
```js
min(1, 2, 3) // returns 1
min([10, 20, 30, 40], 25) // returns [10, 20, 25, 25]
min([1, 9], 4, [3, 5]) // returns [min([1, 4, 3]), min([9, 4, 5])] = [1, 4]
```
***
## _mod(_ _a_, _b_ _)_
Remainder after dividing two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | dividend, a number or an array of numbers |
| b | <code>number</code> \| <code>Array.&lt;number&gt;</code> | divisor, a number or an array of numbers, `b` != 0 |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The remainder of `a` divided by `b` if both are numbers. Returns an array with the the remainders applied index-wise to each element if `a` or `b` is an array.
**Throws**:
- `'Array length mismatch'` if `a` and `b` are arrays with different lengths
- `'Cannot divide by 0'` if `b` equals 0 or contains 0
**Example**
```js
mod(10, 7) // returns 3
mod([11, 22, 33, 44], 10) // returns [1, 2, 3, 4]
mod(100, [3, 7, 11, 23]) // returns [1, 2, 1, 8]
mod([14, 42, 65, 108], [5, 4, 14, 2]) // returns [5, 2, 9, 0]
```
***
## _mode(_ ..._args_ _)_
Finds the mode value(s) of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the mode by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>Array.&lt;number&gt;</code> \| <code>Array.&lt;Array.&lt;number&gt;&gt;</code> - An array mode value(s) of all numbers if `args` contains only numbers. Returns an array of arrays with mode value(s) of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Example**
```js
mode(1, 1, 2, 3) // returns [1]
mode(1, 1, 2, 2, 3) // returns [1,2]
mode([10, 20, 30, 40], 10, 20, 30) // returns [[10], [20], [30], [10, 20, 30, 40]]
mode([1, 9], 1, 4, [3, 5]) // returns [mode([1, 1, 4, 3]), mode([9, 1, 4, 5])] = [[1], [4, 5, 9]]
```
***
## _multiply(_ _a_, _b_ _)_
Multiplies two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
| b | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The product of `a` and `b` if both are numbers. Returns an array with the the products applied index-wise to each element if `a` or `b` is an array.
**Throws**:
- `'Array length mismatch'` if `a` and `b` are arrays with different lengths
**Example**
```js
multiply(6, 3) // returns 18
multiply([10, 20, 30, 40], 10) // returns [100, 200, 300, 400]
multiply(10, [1, 2, 5, 10]) // returns [10, 20, 50, 100]
multiply([1, 2, 3, 4], [2, 7, 5, 12]) // returns [2, 14, 15, 48]
```
***
## _pi(__)_
Returns the mathematical constant PI
**Returns**: <code>number</code> - The mathematical constant PI
**Example**
```js
pi() // 3.141592653589793
```
***
## _pow(_ _a_, _b_ _)_
Raises a number to a given exponent. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
| b | <code>number</code> | the power that `a` is raised to |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - `a` raised to the power of `b`. Returns an array with the each element raised to the power of `b` if `a` is an array.
**Throws**:
- `'Missing exponent'` if `b` is not provided
**Example**
```js
pow(2,3) // returns 8
pow([1, 2, 3], 4) // returns [1, 16, 81]
```
***
## _radtodeg(_ _a_ _)_
Converts radians to degrees for a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` is expected to be given in radians. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The degrees of `a`. Returns an array with the the degrees of each element if `a` is an array.
**Example**
```js
radtodeg(0) // returns 0
radtodeg(1.5707963267948966) // returns 90
radtodeg([0, 1.5707963267948966, 3.141592653589793, 6.283185307179586]) // returns [0, 90, 180, 360]
```
***
## _random(_ _a_, _b_ _)_
Generates a random number within the given range where the lower bound is inclusive and the upper bound is exclusive. If no numbers are passed in, it will return a number between 0 and 1. If only one number is passed in, it will return .
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> | (optional) must be greater than 0 if `b` is not provided |
| b | <code>number</code> | (optional) must be greater |
**Returns**: <code>number</code> - A random number between 0 and 1 if no numbers are passed in. Returns a random number between 0 and `a` if only one number is passed in. Returns a random number between `a` and `b` if two numbers are passed in.
**Throws**:
- `'Min is be greater than max'` if `a` < 0 when only `a` is passed in or if `a` > `b` when both `a` and `b` are passed in
**Example**
```js
random() // returns a random number between 0 (inclusive) and 1 (exclusive)
random(10) // returns a random number between 0 (inclusive) and 10 (exclusive)
random(-10,10) // returns a random number between -10 (inclusive) and 10 (exclusive)
```
***
## _range(_ ..._args_ _)_
Finds the range of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the range by index.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The range value of all numbers if `args` contains only numbers. Returns an array with the the range values at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
**Example**
```js
range(1, 2, 3) // returns 2
range([10, 20, 30, 40], 15) // returns [5, 5, 15, 25]
range([1, 9], 4, [3, 5]) // returns [range([1, 4, 3]), range([9, 4, 5])] = [3, 5]
```
***
## _round(_ _a_, _b_ _)_
Rounds a number towards the nearest integer by default or decimal place if specified. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
| b | <code>number</code> | (optional) number of decimal places, default value: 0 |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The rounded value of `a`. Returns an array with the the rounded values of each element if `a` is an array.
**Example**
```js
round(1.2) // returns 2
round(-10.51) // returns -11
round(-10.1, 2) // returns -10.1
round(10.93745987, 4) // returns 10.9375
round([2.9234, 5.1234, 3.5234, 4.49234324], 2) // returns [2.92, 5.12, 3.52, 4.49]
```
***
## _sin(_ _a_ _)_
Calculates the the sine of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` is expected to be given in radians. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The sine of `a`. Returns an array with the the sine of each element if `a` is an array.
**Example**
```js
sin(0) // returns 0
sin(1.5707963267948966) // returns 1
sin([0, 1.5707963267948966]) // returns [0, 1]
```
***
## _size(_ _a_ _)_
Returns the length of an array. Alias for count
| Param | Type | Description |
| --- | --- | --- |
| a | <code>Array.&lt;any&gt;</code> | array of any values |
**Returns**: <code>number</code> - The length of the array. Returns 1 if `a` is not an array.
**Throws**:
- `'Must pass an array'` if `a` is not an array
**Example**
```js
size([]) // returns 0
size([-1, -2, -3, -4]) // returns 4
size(100) // returns 1
```
***
## _sqrt(_ _a_ _)_
Calculates the square root of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The square root of `a`. Returns an array with the the square roots of each element if `a` is an array.
**Throws**:
- `'Unable find the square root of a negative number'` if `a` < 0
**Example**
```js
sqrt(9) // returns 3
sqrt(30) //5.477225575051661
sqrt([9, 16, 25]) // returns [3, 4, 5]
```
***
## _square(_ _a_ _)_
Calculates the square of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The square of `a`. Returns an array with the the squares of each element if `a` is an array.
**Example**
```js
square(-3) // returns 9
square([3, 4, 5]) // returns [9, 16, 25]
```
***
## _subtract(_ _a_, _b_ _)_
Subtracts two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
| b | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The difference of `a` and `b` if both are numbers or an array of differences applied index-wise to each element.
**Throws**:
- `'Array length mismatch'` if `a` and `b` are arrays with different lengths
**Example**
```js
subtract(6, 3) // returns 3
subtract([10, 20, 30, 40], 10) // returns [0, 10, 20, 30]
subtract(10, [1, 2, 5, 10]) // returns [9, 8, 5, 0]
subtract([14, 42, 65, 108], [2, 7, 5, 12]) // returns [12, 35, 52, 96]
```
***
## _sum(_ ..._args_ _)_
Calculates the sum of one or more numbers/arrays passed into the function. If at least one array is passed, the function will sum up one or more numbers/arrays of numbers and distinct values of an array. Sum accepts arrays of different lengths.
| Param | Type | Description |
| --- | --- | --- |
| ...args | <code>number</code> \| <code>Array.&lt;number&gt;</code> | one or more numbers or arrays of numbers |
**Returns**: <code>number</code> - The sum of one or more numbers/arrays of numbers including distinct values in arrays
**Example**
```js
sum(1, 2, 3) // returns 6
sum([10, 20, 30, 40], 10, 20, 30) // returns 160
sum([1, 2], 3, [4, 5], 6) // returns sum(1, 2, 3, 4, 5, 6) = 21
sum([10, 20, 30, 40], 10, [1, 2, 3], 22) // returns sum(10, 20, 30, 40, 10, 1, 2, 3, 22) = 138
```
***
## _tan(_ _a_ _)_
Calculates the the tangent of a number. For arrays, the function will be applied index-wise to each element.
| Param | Type | Description |
| --- | --- | --- |
| a | <code>number</code> \| <code>Array.&lt;number&gt;</code> | a number or an array of numbers, `a` is expected to be given in radians. |
**Returns**: <code>number</code> \| <code>Array.&lt;number&gt;</code> - The tangent of `a`. Returns an array with the the tangent of each element if `a` is an array.
**Example**
```js
tan(0) // returns 0
tan(1) // returns 1.5574077246549023
tan([0, 1, -1]) // returns [0, 1.5574077246549023, -1.5574077246549023]
```
***
## _unique(_ _a_ _)_
Counts the number of unique values in an array
| Param | Type | Description |
| --- | --- | --- |
| a | <code>Array.&lt;any&gt;</code> | array of any values |
**Returns**: <code>number</code> - The number of unique values in the array. Returns 1 if `a` is not an array.
**Example**
```js
unique(100) // returns 1
unique([]) // returns 0
unique([1, 2, 3, 4]) // returns 4
unique([1, 2, 3, 4, 2, 2, 2, 3, 4, 2, 4, 5, 2, 1, 4, 2]) // returns 5
```

View file

@ -0,0 +1,15 @@
# TinyMath Functions
This document provides detailed information about the functions available in Tinymath and lists what parameters each function accepts, the return value of that function, and examples of how each function behaves. Most of the functions below accept arrays and apply JavaScript Math methods to each element of that array. For the functions that accept multiple arrays as parameters, the function generally does calculation index by index. Any function below can be wrapped by another function as long as the return type of the inner function matches the acceptable parameter type of the outer function.
{{#functions}}
## _{{name}}(_{{#each params}} {{#if variable}}...{{/if}}_{{name}}_{{#unless @last}},{{/unless}} {{/each}}_)_
{{description}}
{{>params~}}
{{>returns~}}
{{>throws~}}
{{>examples~}}
{{#unless @last}}
***
{{/unless}}
{{/functions}}

View file

@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
module.exports = {
preset: '@kbn/test',
rootDir: '../..',
roots: ['<rootDir>/packages/kbn-tinymath'],
};

View file

@ -0,0 +1,12 @@
{
"name": "@kbn/tinymath",
"version": "2.0.0",
"license": "SSPL-1.0 OR Elastic License",
"private": true,
"main": "src/index.js",
"scripts": {
"kbn:bootstrap": "yarn build",
"build": "../../node_modules/.bin/pegjs -o src/grammar.js src/grammar.pegjs"
},
"dependencies": {}
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the absolute value of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The absolute value of `a`. Returns an array with the the absolute values of each element if `a` is an array.
*
* @example
* abs(-1) // returns 1
* abs(2) // returns 2
* abs([-1 , -2, 3, -4]) // returns [1, 2, 3, 4]
*/
module.exports = { abs };
function abs(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.abs(a));
}
return Math.abs(a);
}

View file

@ -0,0 +1,37 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the sum of one or more numbers/arrays passed into the function. If at least one array of numbers is passed into the function, the function will calculate the sum by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The sum of all numbers in `args` if `args` contains only numbers. Returns an array of sums of the elements at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
* @throws `'Array length mismatch'` if `args` contains arrays of different lengths
* @example
* add(1, 2, 3) // returns 6
* add([10, 20, 30, 40], 10, 20, 30) // returns [70, 80, 90, 100]
* add([1, 2], 3, [4, 5], 6) // returns [(1 + 3 + 4 + 6), (2 + 3 + 5 + 6)] = [14, 16]
*/
module.exports = { add };
function add(...args) {
if (args.length === 1) {
if (Array.isArray(args[0])) return args[0].reduce((result, current) => result + current);
return args[0];
}
return args.reduce((result, current) => {
if (Array.isArray(result) && Array.isArray(current)) {
if (current.length !== result.length) throw new Error('Array length mismatch');
return result.map((val, i) => val + current[i]);
}
if (Array.isArray(result)) return result.map((val) => val + current);
if (Array.isArray(current)) return current.map((val) => val + result);
return result + current;
});
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the cube root of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The cube root of `a`. Returns an array with the the cube roots of each element if `a` is an array.
*
* @example
* cbrt(-27) // returns -3
* cbrt(94) // returns 4.546835943776344
* cbrt([27, 64, 125]) // returns [3, 4, 5]
*/
module.exports = { cbrt };
function cbrt(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.cbrt(a));
}
return Math.cbrt(a);
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the ceiling of a number, i.e. rounds a number towards positive infinity. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The ceiling of `a`. Returns an array with the the ceilings of each element if `a` is an array.
*
* @example
* ceil(1.2) // returns 2
* ceil(-1.8) // returns -1
* ceil([1.1, 2.2, 3.3]) // returns [2, 3, 4]
*/
module.exports = { ceil };
function ceil(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.ceil(a));
}
return Math.ceil(a);
}

View file

@ -0,0 +1,75 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const findClamp = (a, min, max) => {
if (min > max) throw new Error('Min must be less than max');
return Math.min(Math.max(a, min), max);
};
/**
* Restricts value to a given range and returns closed available value. If only min is provided, values are restricted to only a lower bound.
* @param {...(number|number[])} a one or more numbers or arrays of numbers
* @param {(number|number[])} min The minimum value this function will return.
* @param {(number|number[])} max The maximum value this function will return.
* @return {(number|number[])} The closest value between `min` (inclusive) and `max` (inclusive). Returns an array with values greater than or equal to `min` and less than or equal to `max` (if provided) at each index.
* @throws `'Array length mismatch'` if `a`, `min`, and/or `max` are arrays of different lengths
* @throws `'Min must be less than max'` if `max` is less than `min`
* @throws `'Missing minimum value. You may want to use the 'max' function instead'` if min is not provided
* @throws `'Missing maximum value. You may want to use the 'min' function instead'` if max is not provided
*
* @example
* clamp(1, 2, 3) // returns 2
* clamp([10, 20, 30, 40], 15, 25) // returns [15, 20, 25, 25]
* clamp(10, [15, 2, 4, 20], 25) // returns [15, 10, 10, 20]
* clamp(35, 10, [20, 30, 40, 50]) // returns [20, 30, 35, 35]
* clamp([1, 9], 3, [4, 5]) // returns [clamp([1, 3, 4]), clamp([9, 3, 5])] = [3, 5]
*/
module.exports = { clamp };
function clamp(a, min, max) {
if (max === null)
throw new Error("Missing maximum value. You may want to use the 'min' function instead");
if (min === null)
throw new Error("Missing minimum value. You may want to use the 'max' function instead");
if (Array.isArray(max)) {
if (Array.isArray(a) && Array.isArray(min)) {
if (a.length !== max.length || a.length !== min.length)
throw new Error('Array length mismatch');
return max.map((max, i) => findClamp(a[i], min[i], max));
}
if (Array.isArray(a)) {
if (a.length !== max.length) throw new Error('Array length mismatch');
return max.map((max, i) => findClamp(a[i], min, max));
}
if (Array.isArray(min)) {
if (min.length !== max.length) throw new Error('Array length mismatch');
return max.map((max, i) => findClamp(a, min[i], max));
}
return max.map((max) => findClamp(a, min, max));
}
if (Array.isArray(a) && Array.isArray(min)) {
if (a.length !== min.length) throw new Error('Array length mismatch');
return a.map((a, i) => findClamp(a, min[i]));
}
if (Array.isArray(a)) {
return a.map((a) => findClamp(a, min, max));
}
if (Array.isArray(min)) {
return min.map((min) => findClamp(a, min, max));
}
return findClamp(a, min, max);
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the the cosine of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` is expected to be given in radians.
* @return {(number|number[])} The cosine of `a`. Returns an array with the the cosine of each element if `a` is an array.
* @example
* cos(0) // returns 1
* cos(1.5707963267948966) // returns 6.123233995736766e-17
* cos([0, 1.5707963267948966]) // returns [1, 6.123233995736766e-17]
*/
module.exports = { cos };
function cos(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.cos(a));
}
return Math.cos(a);
}

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { size } = require('./size.js');
/**
* Returns the length of an array. Alias for size
* @param {any[]} a array of any values
* @return {(number)} The length of the array. Returns 1 if `a` is not an array.
* @throws `'Must pass an array'` if `a` is not an array
* @example
* count([]) // returns 0
* count([-1, -2, -3, -4]) // returns 4
* count(100) // returns 1
*/
module.exports = { count };
function count(a) {
return size(a);
}
count.skipNumberValidation = true;

View file

@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { pow } = require('./pow.js');
/**
* Calculates the cube of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The cube of `a`. Returns an array with the the cubes of each element if `a` is an array.
*
* @example
* cube(-3) // returns -27
* cube([3, 4, 5]) // returns [27, 64, 125]
*/
module.exports = { cube };
function cube(a) {
return pow(a, 3);
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Converts degrees to radians for a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` is expected to be given in degrees.
* @return {(number|number[])} The radians of `a`. Returns an array with the the radians of each element if `a` is an array.
* @example
* degtorad(0) // returns 0
* degtorad(90) // returns 1.5707963267948966
* degtorad([0, 90, 180, 360]) // returns [0, 1.5707963267948966, 3.141592653589793, 6.283185307179586]
*/
module.exports = { degtorad };
function degtorad(a) {
if (Array.isArray(a)) {
return a.map((a) => (a * Math.PI) / 180);
}
return (a * Math.PI) / 180;
}

View file

@ -0,0 +1,37 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Divides two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
* @param {(number|number[])} a dividend, a number or an array of numbers
* @param {(number|number[])} b divisor, a number or an array of numbers, `b` != 0
* @return {(number|number[])} The quotient of `a` and `b` if both are numbers. Returns an array with the quotients applied index-wise to each element if `a` or `b` is an array.
* @throws `'Array length mismatch'` if `a` and `b` are arrays with different lengths
* - `'Cannot divide by 0'` if `b` equals 0 or contains 0
* @example
* divide(6, 3) // returns 2
* divide([10, 20, 30, 40], 10) // returns [1, 2, 3, 4]
* divide(10, [1, 2, 5, 10]) // returns [10, 5, 2, 1]
* divide([14, 42, 65, 108], [2, 7, 5, 12]) // returns [7, 6, 13, 9]
*/
module.exports = { divide };
function divide(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) throw new Error('Array length mismatch');
return a.map((val, i) => {
if (b[i] === 0) throw new Error('Cannot divide by 0');
return val / b[i];
});
}
if (Array.isArray(b)) return b.map((b) => a / b);
if (b === 0) throw new Error('Cannot divide by 0');
if (Array.isArray(a)) return a.map((a) => a / b);
return a / b;
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates _e^x_ where _e_ is Euler's number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} `e^a`. Returns an array with the values of `e^x` evaluated where `x` is each element of `a` if `a` is an array.
*
* @example
* exp(2) // returns e^2 = 7.3890560989306495
* exp([1, 2, 3]) // returns [e^1, e^2, e^3] = [2.718281828459045, 7.3890560989306495, 20.085536923187668]
*/
module.exports = { exp };
function exp(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.exp(a));
}
return Math.exp(a);
}

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Returns the first element of an array. If anything other than an array is passed in, the input is returned.
* @param {any[]} a array of any values
* @return {*} The first element of `a`. Returns `a` if `a` is not an array.
*
* @example
* first(2) // returns 2
* first([1, 2, 3]) // returns 1
*/
module.exports = { first };
function first(a) {
if (Array.isArray(a)) {
return a[0];
}
return a;
}
first.skipNumberValidation = true;

View file

@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const fixer = (a) => {
if (a > 0) {
return Math.floor(a);
}
return Math.ceil(a);
};
/**
* Calculates the fix of a number, i.e. rounds a number towards 0. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The fix of `a`. Returns an array with the the fixes for each element if `a` is an array.
*
* @example
* fix(1.2) // returns 1
* fix(-1.8) // returns -1
* fix([1.8, 2.9, -3.7, -4.6]) // returns [1, 2, -3, -4]
*/
module.exports = { fix };
function fix(a) {
if (Array.isArray(a)) {
return a.map((a) => fixer(a));
}
return fixer(a);
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the floor of a number, i.e. rounds a number towards negative infinity. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The floor of `a`. Returns an array with the the floor of each element if `a` is an array.
*
* @example
* floor(1.8) // returns 1
* floor(-1.2) // returns -2
* floor([1.7, 2.8, 3.9]) // returns [1, 2, 3]
*/
module.exports = { floor };
function floor(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.floor(a));
}
return Math.floor(a);
}

View file

@ -0,0 +1,89 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { abs } = require('./abs');
const { add } = require('./add');
const { cbrt } = require('./cbrt');
const { ceil } = require('./ceil');
const { clamp } = require('./clamp');
const { cos } = require('./cos');
const { count } = require('./count');
const { cube } = require('./cube');
const { degtorad } = require('./degtorad');
const { divide } = require('./divide');
const { exp } = require('./exp');
const { first } = require('./first');
const { fix } = require('./fix');
const { floor } = require('./floor');
const { last } = require('./last');
const { log } = require('./log');
const { log10 } = require('./log10');
const { max } = require('./max');
const { mean } = require('./mean');
const { median } = require('./median');
const { min } = require('./min');
const { mod } = require('./mod');
const { mode } = require('./mode');
const { multiply } = require('./multiply');
const { pi } = require('./pi');
const { pow } = require('./pow');
const { radtodeg } = require('./radtodeg');
const { random } = require('./random');
const { range } = require('./range');
const { round } = require('./round');
const { sin } = require('./sin');
const { size } = require('./size');
const { sqrt } = require('./sqrt');
const { square } = require('./square');
const { subtract } = require('./subtract');
const { sum } = require('./sum');
const { tan } = require('./tan');
const { unique } = require('./unique');
module.exports = {
functions: {
abs,
add,
cbrt,
ceil,
clamp,
cos,
count,
cube,
degtorad,
divide,
exp,
first,
fix,
floor,
last,
log,
log10,
max,
mean,
median,
min,
mod,
mode,
multiply,
pi,
pow,
radtodeg,
random,
range,
round,
sin,
size,
sqrt,
square,
subtract,
sum,
tan,
unique,
},
};

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Returns the last element of an array. If anything other than an array is passed in, the input is returned.
* @param {any[]} a array of any values
* @return {*} The last element of `a`. Returns `a` if `a` is not an array.
*
* @example
* last(2) // returns 2
* last([1, 2, 3]) // returns 3
*/
module.exports = { last };
function last(a) {
if (Array.isArray(a)) {
return a[a.length - 1];
}
return a;
}
last.skipNumberValidation = true;

View file

@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Transposes a 2D array, i.e. turns the rows into columns and vice versa. Scalar values are also included in the transpose.
* @param {any[][]} args an array or an array that contains arrays
* @param {number} index index of the first array element in args
* @return {any[][]} transpose of args
* @throws `'Array length mismatch'` if `args` contains arrays of different lengths
* @example
* transpose([[1,2], [3,4], [5,6]], 0) // returns [[1, 3, 5], [2, 4, 6]]
* transpose([10, 20, [10, 20, 30, 40], 30], 2) // returns [[10, 20, 10, 30], [10, 20, 20, 30], [10, 20, 30, 30], [10, 20, 40, 30]]
* transpose([4, [1, 9], [3, 5]], 1) // returns [[4, 1, 3], [4, 9, 5]]
*/
module.exports = { transpose };
function transpose(args, index) {
const len = args[index].length;
return args[index].map((col, i) =>
args.map((row) => {
if (Array.isArray(row)) {
if (row.length !== len) throw new Error('Array length mismatch');
return row[i];
}
return row;
})
);
}

View file

@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const changeOfBase = (a, b) => Math.log(a) / Math.log(b);
/**
* Calculates the logarithm of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` must be greater than 0
* @param {{number}} b (optional) base for the logarithm. If not provided a value, the default base is e, and the natural log is calculated.
* @return {(number|number[])} The logarithm of `a`. Returns an array with the the logarithms of each element if `a` is an array.
* @throws `'Base out of range'` if `b` <= 0
* - 'Must be greater than 0' if `a` > 0
* @example
* log(1) // returns 0
* log(64, 8) // returns 2
* log(42, 5) // returns 2.322344707681546
* log([2, 4, 8, 16, 32], 2) // returns [1, 2, 3, 4, 5]
*/
module.exports = { log };
function log(a, b = Math.E) {
if (b <= 0) throw new Error('Base out of range');
if (Array.isArray(a)) {
return a.map((a) => {
if (a < 0) throw new Error('Must be greater than 0');
return changeOfBase(a, b);
});
}
if (a < 0) throw new Error('Must be greater than 0');
return changeOfBase(a, b);
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { log } = require('./log.js');
/**
* Calculates the logarithm base 10 of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` must be greater than 0
* @return {(number|number[])} The logarithm of `a`. Returns an array with the the logarithms base 10 of each element if `a` is an array.
* @throws `'Must be greater than 0'` if `a` < 0
* @example
* log(10) // returns 1
* log(100) // returns 2
* log(80) // returns 1.9030899869919433
* log([10, 100, 1000, 10000, 100000]) // returns [1, 2, 3, 4, 5]
*/
module.exports = { log10 };
function log10(a) {
return log(a, 10);
}

View file

@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Finds the maximum value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the maximum by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The maximum value of all numbers if `args` contains only numbers. Returns an array with the the maximum values at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
* @throws `'Array length mismatch'` if `args` contains arrays of different lengths
* @example
* max(1, 2, 3) // returns 3
* max([10, 20, 30, 40], 15) // returns [15, 20, 30, 40]
* max([1, 9], 4, [3, 5]) // returns [max([1, 4, 3]), max([9, 4, 5])] = [4, 9]
*/
module.exports = { max };
function max(...args) {
if (args.length === 1) {
if (Array.isArray(args[0]))
return args[0].reduce((result, current) => Math.max(result, current));
return args[0];
}
return args.reduce((result, current) => {
if (Array.isArray(result) && Array.isArray(current)) {
if (current.length !== result.length) throw new Error('Array length mismatch');
return result.map((val, i) => Math.max(val, current[i]));
}
if (Array.isArray(result)) return result.map((val) => Math.max(val, current));
if (Array.isArray(current)) return current.map((val) => Math.max(val, result));
return Math.max(result, current);
});
}

View file

@ -0,0 +1,36 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { add } = require('./add.js');
/**
* Finds the mean value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the mean by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The mean value of all numbers if `args` contains only numbers. Returns an array with the the mean values of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
*
* @example
* mean(1, 2, 3) // returns 2
* mean([10, 20, 30, 40], 20) // returns [15, 20, 25, 30]
* mean([1, 9], 5, [3, 4]) // returns [mean([1, 5, 3]), mean([9, 5, 4])] = [3, 6]
*/
module.exports = { mean };
function mean(...args) {
if (args.length === 1) {
if (Array.isArray(args[0])) return add(args[0]) / args[0].length;
return args[0];
}
const sum = add(...args);
if (Array.isArray(sum)) {
return sum.map((val) => val / args.length);
}
return sum / args.length;
}

View file

@ -0,0 +1,50 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { transpose } = require('./lib/transpose');
const findMedian = (a) => {
const len = a.length;
const half = Math.floor(len / 2);
a.sort((a, b) => b - a);
if (len % 2 === 0) {
return (a[half] + a[half - 1]) / 2;
}
return a[half];
};
/**
* Finds the median value(s) of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the median by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The median value of all numbers if `args` contains only numbers. Returns an array with the the median values of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
*
* @example
* median(1, 1, 2, 3) // returns 1.5
* median(1, 1, 2, 2, 3) // returns 2
* median([10, 20, 30, 40], 10, 20, 30) // returns [15, 20, 25, 25]
* median([1, 9], 2, 4, [3, 5]) // returns [median([1, 2, 4, 3]), median([9, 2, 4, 5])] = [2.5, 4.5]
*/
module.exports = { median };
function median(...args) {
if (args.length === 1) {
if (Array.isArray(args[0])) return findMedian(args[0]);
return args[0];
}
const firstArray = args.findIndex((element) => Array.isArray(element));
if (firstArray !== -1) {
const result = transpose(args, firstArray);
return result.map((val) => findMedian(val));
}
return findMedian(args);
}

View file

@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Finds the minimum value of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the minimum by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The minimum value of all numbers if `args` contains only numbers. Returns an array with the the minimum values of each index, including all scalar numbers in `args` in the calculation at each index if `a` is an array.
* @throws `'Array length mismatch'` if `args` contains arrays of different lengths
* @example
* min(1, 2, 3) // returns 1
* min([10, 20, 30, 40], 25) // returns [10, 20, 25, 25]
* min([1, 9], 4, [3, 5]) // returns [min([1, 4, 3]), min([9, 4, 5])] = [1, 4]
*/
module.exports = { min };
function min(...args) {
if (args.length === 1) {
if (Array.isArray(args[0]))
return args[0].reduce((result, current) => Math.min(result, current));
return args[0];
}
return args.reduce((result, current) => {
if (Array.isArray(result) && Array.isArray(current)) {
if (current.length !== result.length) throw new Error('Array length mismatch');
return result.map((val, i) => Math.min(val, current[i]));
}
if (Array.isArray(result)) return result.map((val) => Math.min(val, current));
if (Array.isArray(current)) return current.map((val) => Math.min(val, result));
return Math.min(result, current);
});
}

View file

@ -0,0 +1,37 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Remainder after dividing two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
* @param {(number|number[])} a dividend, a number or an array of numbers
* @param {(number|number[])} b divisor, a number or an array of numbers, `b` != 0
* @return {(number|number[])} The remainder of `a` divided by `b` if both are numbers. Returns an array with the the remainders applied index-wise to each element if `a` or `b` is an array.
* @throws `'Array length mismatch'` if `a` and `b` are arrays with different lengths
* - `'Cannot divide by 0'` if `b` equals 0 or contains 0
* @example
* mod(10, 7) // returns 3
* mod([11, 22, 33, 44], 10) // returns [1, 2, 3, 4]
* mod(100, [3, 7, 11, 23]) // returns [1, 2, 1, 8]
* mod([14, 42, 65, 108], [5, 4, 14, 2]) // returns [5, 2, 9, 0]
*/
module.exports = { mod };
function mod(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) throw new Error('Array length mismatch');
return a.map((val, i) => {
if (b[i] === 0) throw new Error('Cannot divide by 0');
return val % b[i];
});
}
if (Array.isArray(b)) return b.map((b) => a % b);
if (b === 0) throw new Error('Cannot divide by 0');
if (Array.isArray(a)) return a.map((a) => a % b);
return a % b;
}

View file

@ -0,0 +1,57 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { transpose } = require('./lib/transpose');
const findMode = (a) => {
let maxFreq = 0;
const mapping = {};
a.map((val) => {
if (mapping[val] === undefined) {
mapping[val] = 0;
}
mapping[val] += 1;
if (mapping[val] > maxFreq) {
maxFreq = mapping[val];
}
});
return Object.keys(mapping)
.filter((key) => mapping[key] === maxFreq)
.map((val) => parseFloat(val))
.sort((a, b) => a - b);
};
/**
* Finds the mode value(s) of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the mode by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number[]|number[][])} An array mode value(s) of all numbers if `args` contains only numbers. Returns an array of arrays with mode value(s) of each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
*
* @example
* mode(1, 1, 2, 3) // returns [1]
* mode(1, 1, 2, 2, 3) // returns [1,2]
* mode([10, 20, 30, 40], 10, 20, 30) // returns [[10], [20], [30], [10, 20, 30, 40]]
* mode([1, 9], 1, 4, [3, 5]) // returns [mode([1, 1, 4, 3]), mode([9, 1, 4, 5])] = [[1], [4, 5, 9]]
*/
module.exports = { mode };
function mode(...args) {
if (args.length === 1) {
if (Array.isArray(args[0])) return findMode(args[0]);
return args[0];
}
const firstArray = args.findIndex((element) => Array.isArray(element));
if (firstArray !== -1) {
const result = transpose(args, firstArray);
return result.map((val) => findMode(val));
}
return findMode(args);
}

View file

@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Multiplies two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @param {(number|number[])} b a number or an array of numbers
* @return {(number|number[])} The product of `a` and `b` if both are numbers. Returns an array with the the products applied index-wise to each element if `a` or `b` is an array.
* @throws `'Array length mismatch'` if `a` and `b` are arrays with different lengths
* @example
* multiply(6, 3) // returns 18
* multiply([10, 20, 30, 40], 10) // returns [100, 200, 300, 400]
* multiply(10, [1, 2, 5, 10]) // returns [10, 20, 50, 100]
* multiply([1, 2, 3, 4], [2, 7, 5, 12]) // returns [2, 14, 15, 48]
*/
module.exports = { multiply };
function multiply(...args) {
return args.reduce((result, current) => {
if (Array.isArray(result) && Array.isArray(current)) {
if (current.length !== result.length) throw new Error('Array length mismatch');
return result.map((val, i) => val * current[i]);
}
if (Array.isArray(result)) return result.map((val) => val * current);
if (Array.isArray(current)) return current.map((val) => val * result);
return result * current;
});
}

View file

@ -0,0 +1,21 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Returns the mathematical constant PI
* @return {(number)} The mathematical constant PI
*
* @example
* pi() // 3.141592653589793
*/
module.exports = { pi };
function pi() {
return Math.PI;
}

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Raises a number to a given exponent. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @param {(number)} b the power that `a` is raised to
* @return {(number|number[])} `a` raised to the power of `b`. Returns an array with the each element raised to the power of `b` if `a` is an array.
* @throws `'Missing exponent'` if `b` is not provided
* @example
* pow(2,3) // returns 8
* pow([1, 2, 3], 4) // returns [1, 16, 81]
*/
module.exports = { pow };
function pow(a, b) {
if (b == null) throw new Error('Missing exponent');
if (Array.isArray(a)) {
return a.map((a) => Math.pow(a, b));
}
return Math.pow(a, b);
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Converts radians to degrees for a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` is expected to be given in radians.
* @return {(number|number[])} The degrees of `a`. Returns an array with the the degrees of each element if `a` is an array.
* @example
* radtodeg(0) // returns 0
* radtodeg(1.5707963267948966) // returns 90
* radtodeg([0, 1.5707963267948966, 3.141592653589793, 6.283185307179586]) // returns [0, 90, 180, 360]
*/
module.exports = { radtodeg };
function radtodeg(a) {
if (Array.isArray(a)) {
return a.map((a) => (a * 180) / Math.PI);
}
return (a * 180) / Math.PI;
}

View file

@ -0,0 +1,35 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Generates a random number within the given range where the lower bound is inclusive and the upper bound is exclusive. If no numbers are passed in, it will return a number between 0 and 1. If only one number is passed in, it will return .
* @param {number} a (optional) must be greater than 0 if `b` is not provided
* @param {number} b (optional) must be greater
* @return {number} A random number between 0 and 1 if no numbers are passed in. Returns a random number between 0 and `a` if only one number is passed in. Returns a random number between `a` and `b` if two numbers are passed in.
* @throws `'Min is be greater than max'` if `a` < 0 when only `a` is passed in or if `a` > `b` when both `a` and `b` are passed in
* @example
* random() // returns a random number between 0 (inclusive) and 1 (exclusive)
* random(10) // returns a random number between 0 (inclusive) and 10 (exclusive)
* random(-10,10) // returns a random number between -10 (inclusive) and 10 (exclusive)
*/
module.exports = { random };
function random(a, b) {
if (a == null) return Math.random();
// a: max, generate random number between 0 and a
if (b == null) {
if (a < 0) throw new Error(`Min is greater than max`);
return Math.random() * a;
}
// a: min, b: max, generate random number between a and b
if (a > b) throw new Error(`Min is greater than max`);
return Math.random() * (b - a) + a;
}

View file

@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { max } = require('./max.js');
const { min } = require('./min.js');
const { subtract } = require('./subtract.js');
/**
* Finds the range of one of more numbers/arrays of numbers into the function. If at least one array of numbers is passed into the function, the function will find the range by index.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {(number|number[])} The range value of all numbers if `args` contains only numbers. Returns an array with the the range values at each index, including all scalar numbers in `args` in the calculation at each index if `args` contains at least one array.
*
* @example
* range(1, 2, 3) // returns 2
* range([10, 20, 30, 40], 15) // returns [5, 5, 15, 25]
* range([1, 9], 4, [3, 5]) // returns [range([1, 4, 3]), range([9, 4, 5])] = [3, 5]
*/
module.exports = { range };
function range(...args) {
return subtract(max(...args), min(...args));
}

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const rounder = (a, b) => Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
/**
* Rounds a number towards the nearest integer by default or decimal place if specified. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @param {(number)} b (optional) number of decimal places, default value: 0
* @return {(number|number[])} The rounded value of `a`. Returns an array with the the rounded values of each element if `a` is an array.
*
* @example
* round(1.2) // returns 2
* round(-10.51) // returns -11
* round(-10.1, 2) // returns -10.1
* round(10.93745987, 4) // returns 10.9375
* round([2.9234, 5.1234, 3.5234, 4.49234324], 2) // returns [2.92, 5.12, 3.52, 4.49]
*/
module.exports = { round };
function round(a, b = 0) {
if (Array.isArray(a)) {
return a.map((a) => rounder(a, b));
}
return rounder(a, b);
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the the sine of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` is expected to be given in radians.
* @return {(number|number[])} The sine of `a`. Returns an array with the the sine of each element if `a` is an array.
* @example
* sin(0) // returns 0
* sin(1.5707963267948966) // returns 1
* sin([0, 1.5707963267948966]) // returns [0, 1]
*/
module.exports = { sin };
function sin(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.sin(a));
}
return Math.sin(a);
}

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Returns the length of an array. Alias for count
* @param {any[]} a array of any values
* @return {(number)} The length of the array. Returns 1 if `a` is not an array.
* @throws `'Must pass an array'` if `a` is not an array
* @example
* size([]) // returns 0
* size([-1, -2, -3, -4]) // returns 4
* size(100) // returns 1
*/
module.exports = { size };
function size(a) {
if (Array.isArray(a)) return a.length;
throw new Error('Must pass an array');
}
size.skipNumberValidation = true;

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the square root of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The square root of `a`. Returns an array with the the square roots of each element if `a` is an array.
* @throws `'Unable find the square root of a negative number'` if `a` < 0
* @example
* sqrt(9) // returns 3
* sqrt(30) //5.477225575051661
* sqrt([9, 16, 25]) // returns [3, 4, 5]
*/
module.exports = { sqrt };
function sqrt(a) {
if (Array.isArray(a)) {
return a.map((a) => {
if (a < 0) throw new Error('Unable find the square root of a negative number');
return Math.sqrt(a);
});
}
if (a < 0) throw new Error('Unable find the square root of a negative number');
return Math.sqrt(a);
}

View file

@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { pow } = require('./pow.js');
/**
* Calculates the square of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @return {(number|number[])} The square of `a`. Returns an array with the the squares of each element if `a` is an array.
*
* @example
* square(-3) // returns 9
* square([3, 4, 5]) // returns [9, 16, 25]
*/
module.exports = { square };
function square(a) {
return pow(a, 2);
}

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Subtracts two numbers. If at least one array of numbers is passed into the function, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers
* @param {(number|number[])} b a number or an array of numbers
* @return {(number|number[])} The difference of `a` and `b` if both are numbers or an array of differences applied index-wise to each element.
* @throws `'Array length mismatch'` if `a` and `b` are arrays with different lengths
* @example
* subtract(6, 3) // returns 3
* subtract([10, 20, 30, 40], 10) // returns [0, 10, 20, 30]
* subtract(10, [1, 2, 5, 10]) // returns [9, 8, 5, 0]
* subtract([14, 42, 65, 108], [2, 7, 5, 12]) // returns [12, 35, 52, 96]
*/
module.exports = { subtract };
function subtract(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) throw new Error('Array length mismatch');
return a.map((val, i) => val - b[i]);
}
if (Array.isArray(a)) return a.map((a) => a - b);
if (Array.isArray(b)) return b.map((b) => a - b);
return a - b;
}

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const findSum = (total, current) => total + current;
/**
* Calculates the sum of one or more numbers/arrays passed into the function. If at least one array is passed, the function will sum up one or more numbers/arrays of numbers and distinct values of an array. Sum accepts arrays of different lengths.
* @param {...(number|number[])} args one or more numbers or arrays of numbers
* @return {number} The sum of one or more numbers/arrays of numbers including distinct values in arrays
*
* @example
* sum(1, 2, 3) // returns 6
* sum([10, 20, 30, 40], 10, 20, 30) // returns 160
* sum([1, 2], 3, [4, 5], 6) // returns sum(1, 2, 3, 4, 5, 6) = 21
* sum([10, 20, 30, 40], 10, [1, 2, 3], 22) // returns sum(10, 20, 30, 40, 10, 1, 2, 3, 22) = 138
*/
module.exports = { sum };
function sum(...args) {
return args.reduce((total, current) => {
if (Array.isArray(current)) {
return total + current.reduce(findSum, 0);
}
return total + current;
}, 0);
}

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Calculates the the tangent of a number. For arrays, the function will be applied index-wise to each element.
* @param {(number|number[])} a a number or an array of numbers, `a` is expected to be given in radians.
* @return {(number|number[])} The tangent of `a`. Returns an array with the the tangent of each element if `a` is an array.
* @example
* tan(0) // returns 0
* tan(1) // returns 1.5574077246549023
* tan([0, 1, -1]) // returns [0, 1.5574077246549023, -1.5574077246549023]
*/
module.exports = { tan };
function tan(a) {
if (Array.isArray(a)) {
return a.map((a) => Math.tan(a));
}
return Math.tan(a);
}

View file

@ -0,0 +1,30 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/**
* Counts the number of unique values in an array
* @param {any[]} a array of any values
* @return {number} The number of unique values in the array. Returns 1 if `a` is not an array.
*
* @example
* unique(100) // returns 1
* unique([]) // returns 0
* unique([1, 2, 3, 4]) // returns 4
* unique([1, 2, 3, 4, 2, 2, 2, 3, 4, 2, 4, 5, 2, 1, 4, 2]) // returns 5
*/
module.exports = { unique };
function unique(a) {
if (Array.isArray(a)) {
return a.filter((val, i) => a.indexOf(val) === i).length;
}
return 1;
}
unique.skipNumberValidation = true;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
// tinymath parsing grammar
start
= Expression
// characters
_ "whitespace"
= [ \t\n\r]*
Space
= [ ]
Quote
= [\"\']
StartChar
= [A-Za-z_@.\[\]-]
ValidChar
= [0-9A-Za-z._@\[\]-]
// literals and variables
Literal "literal"
= _ literal:(Number / VariableWithQuote / Variable) _ {
return literal;
}
Variable
= _ first:StartChar rest:ValidChar* _ { // We can open this up later. Strict for now.
return first + rest.join('');
}
VariableWithQuote
= _ Quote first:StartChar mid:(Space* ValidChar+)* Quote _ {
return first + mid.map(m => m[0].join('') + m[1].join('')).join('')
}
// expressions
Expression
= AddSubtract
AddSubtract
= _ left:MultiplyDivide rest:(('+' / '-') MultiplyDivide)* _ {
return rest.reduce((acc, curr) => ({
name: curr[0] === '+' ? 'add' : 'subtract',
args: [acc, curr[1]]
}), left)
}
MultiplyDivide
= _ left:Factor rest:(('*' / '/') Factor)* _ {
return rest.reduce((acc, curr) => ({
name: curr[0] === '*' ? 'multiply' : 'divide',
args: [acc, curr[1]]
}), left)
}
Factor
= Group
/ Function
/ Literal
Group
= _ '(' _ expr:Expression _ ')' _ {
return expr
}
Arguments "arguments"
= _ first:Expression rest:(_ ',' _ arg:Expression {return arg})* _ ','? _ {
return [first].concat(rest);
}
Function "function"
= _ name:[a-z]+ '(' _ args:Arguments? _ ')' _ {
return {name: name.join(''), args: args || []};
}
// Numbers. Lol.
Number "number"
= '-'? Integer Fraction? Exp? { return parseFloat(text()); }
E
= [eE]
Exp "exponent"
= E '-'? Digit+
Fraction
= '.' Digit+
Integer
= '0'
/ ([1-9] Digit*)
Digit
= [0-9]

View file

@ -0,0 +1,86 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { get } = require('lodash');
const { parse: parseFn } = require('./grammar');
const { functions: includedFunctions } = require('./functions');
module.exports = { parse, evaluate, interpret };
function parse(input, options) {
if (input == null) {
throw new Error('Missing expression');
}
if (typeof input !== 'string') {
throw new Error('Expression must be a string');
}
try {
return parseFn(input, options);
} catch (e) {
throw new Error(`Failed to parse expression. ${e.message}`);
}
}
function evaluate(expression, scope = {}, injectedFunctions = {}) {
scope = scope || {};
return interpret(parse(expression), scope, injectedFunctions);
}
function interpret(node, scope, injectedFunctions) {
const functions = Object.assign({}, includedFunctions, injectedFunctions); // eslint-disable-line
return exec(node);
function exec(node) {
const type = getType(node);
if (type === 'function') return invoke(node);
if (type === 'string') {
const val = getValue(scope, node);
if (typeof val === 'undefined') throw new Error(`Unknown variable: ${node}`);
return val;
}
return node; // Can only be a number at this point
}
function invoke(node) {
const { name, args } = node;
const fn = functions[name];
if (!fn) throw new Error(`No such function: ${name}`);
const execOutput = args.map(exec);
if (fn.skipNumberValidation || isOperable(execOutput)) return fn(...execOutput);
return NaN;
}
}
function getValue(scope, node) {
// attempt to read value from nested object first, check for exact match if value is undefined
const val = get(scope, node);
return typeof val !== 'undefined' ? val : scope[node];
}
function getType(x) {
const type = typeof x;
if (type === 'object') {
const keys = Object.keys(x);
if (keys.length !== 2 || !x.name || !x.args) throw new Error('Invalid AST object');
return 'function';
}
if (type === 'string' || type === 'number') return type;
throw new Error(`Unknown AST property type: ${type}`);
}
function isOperable(args) {
return args.every((arg) => {
if (Array.isArray(arg)) return isOperable(arg);
return typeof arg === 'number' && !isNaN(arg);
});
}

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { abs } = require('../../src/functions/abs.js');
describe('Abs', () => {
it('numbers', () => {
expect(abs(-10)).toEqual(10);
expect(abs(10)).toEqual(10);
});
it('arrays', () => {
expect(abs([-1])).toEqual([1]);
expect(abs([-10, -20, -30, -40])).toEqual([10, 20, 30, 40]);
expect(abs([-13, 30, -90, 200])).toEqual([13, 30, 90, 200]);
});
});

View file

@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { add } = require('../../src/functions/add.js');
describe('Add', () => {
it('numbers', () => {
expect(add(1)).toEqual(1);
expect(add(10, 2, 5, 8)).toEqual(25);
expect(add(0.1, 0.2, 0.4, 0.3)).toEqual(0.1 + 0.2 + 0.3 + 0.4);
});
it('arrays & numbers', () => {
expect(add([10, 20, 30, 40], 10, 20, 30)).toEqual([70, 80, 90, 100]);
expect(add(10, [10, 20, 30, 40], [1, 2, 3, 4], 22)).toEqual([43, 54, 65, 76]);
});
it('arrays', () => {
expect(add([1, 2, 3, 4])).toEqual(10);
expect(add([1, 2, 3, 4], [1, 2, 5, 10])).toEqual([2, 4, 8, 14]);
expect(add([1, 2, 3, 4], [1, 2, 5, 10], [10, 20, 30, 40])).toEqual([12, 24, 38, 54]);
expect(add([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([12, 50, 63, 76]);
});
it('array length mismatch', () => {
expect(() => add([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { cbrt } = require('../../src/functions/cbrt.js');
describe('Cbrt', () => {
it('numbers', () => {
expect(cbrt(27)).toEqual(3);
expect(cbrt(-1)).toEqual(-1);
expect(cbrt(94)).toEqual(4.546835943776344);
});
it('arrays', () => {
expect(cbrt([27, 64, 125])).toEqual([3, 4, 5]);
expect(cbrt([1, 8, 1000])).toEqual([1, 2, 10]);
});
});

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { ceil } = require('../../src/functions/ceil.js');
describe('Ceil', () => {
it('numbers', () => {
expect(ceil(-10.5)).toEqual(-10);
expect(ceil(-10.1)).toEqual(-10);
expect(ceil(10.9)).toEqual(11);
});
it('arrays', () => {
expect(ceil([-10.5, -20.9, -30.1, -40.2])).toEqual([-10, -20, -30, -40]);
expect(ceil([2.9, 5.1, 3.5, 4.3])).toEqual([3, 6, 4, 5]);
});
});

View file

@ -0,0 +1,50 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { clamp } = require('../../src/functions/clamp.js');
describe('Clamp', () => {
it('numbers', () => {
expect(clamp(10, 5, 8)).toEqual(8);
expect(clamp(1, 2, 3)).toEqual(2);
expect(clamp(0.5, 0.2, 0.4)).toEqual(0.4);
expect(clamp(3.58, 0, 1)).toEqual(1);
expect(clamp(-0.48, 0, 1)).toEqual(0);
expect(clamp(1.38, -1, 0)).toEqual(0);
});
it('arrays & numbers', () => {
expect(clamp([10, 20, 30, 40], 15, 25)).toEqual([15, 20, 25, 25]);
expect(clamp(10, [15, 2, 4, 20], 25)).toEqual([15, 10, 10, 20]);
expect(clamp(5, 10, [20, 30, 40, 50])).toEqual([10, 10, 10, 10]);
expect(clamp(35, 10, [20, 30, 40, 50])).toEqual([20, 30, 35, 35]);
expect(clamp([1, 9], 3, [4, 5])).toEqual([3, 5]);
});
it('arrays', () => {
expect(clamp([6, 28, 32, 10], [11, 2, 5, 10], [20, 21, 22, 23])).toEqual([11, 21, 22, 10]);
});
it('errors', () => {
expect(() => clamp(1, 4, 3)).toThrow('Min must be less than max');
expect(() => clamp([1, 2], [3], 3)).toThrow('Array length mismatch');
expect(() => clamp([1, 2], [3], 3)).toThrow('Array length mismatch');
expect(() => clamp(10, 20, null)).toThrow(
"Missing maximum value. You may want to use the 'min' function instead"
);
expect(() => clamp([10, 20, 30, 40], 15, null)).toThrow(
"Missing maximum value. You may want to use the 'min' function instead"
);
expect(() => clamp(10, null, 30)).toThrow(
"Missing minimum value. You may want to use the 'max' function instead"
);
expect(() => clamp([11, 28, 60, 10], null, [1, 48, 3, -17])).toThrow(
"Missing minimum value. You may want to use the 'max' function instead"
);
});
});

View file

@ -0,0 +1,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { cos } = require('../../src/functions/cos.js');
describe('Cosine', () => {
it('numbers', () => {
expect(cos(0)).toEqual(1);
expect(cos(1.5707963267948966)).toEqual(6.123233995736766e-17);
});
it('arrays', () => {
expect(cos([0, 1.5707963267948966])).toEqual([1, 6.123233995736766e-17]);
});
});

View file

@ -0,0 +1,21 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { cube } = require('../../src/functions/cube.js');
describe('Cube', () => {
it('numbers', () => {
expect(cube(3)).toEqual(27);
expect(cube(-1)).toEqual(-1);
});
it('arrays', () => {
expect(cube([3, 4, 5])).toEqual([27, 64, 125]);
expect(cube([1, 2, 10])).toEqual([1, 8, 1000]);
});
});

View file

@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { degtorad } = require('../../src/functions/degtorad.js');
describe('Degrees to Radians', () => {
it('numbers', () => {
expect(degtorad(0)).toEqual(0);
expect(degtorad(90)).toEqual(1.5707963267948966);
});
it('arrays', () => {
expect(degtorad([0, 90, 180, 360])).toEqual([
0,
1.5707963267948966,
3.141592653589793,
6.283185307179586,
]);
});
});

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { divide } = require('../../src/functions/divide.js');
describe('Divide', () => {
it('number, number', () => {
expect(divide(10, 2)).toEqual(5);
expect(divide(0.1, 0.02)).toEqual(0.1 / 0.02);
});
it('array, number', () => {
expect(divide([10, 20, 30, 40], 10)).toEqual([1, 2, 3, 4]);
});
it('number, array', () => {
expect(divide(10, [1, 2, 5, 10])).toEqual([10, 5, 2, 1]);
});
it('array, array', () => {
expect(divide([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([11, 24, 20, 18]);
});
it('array length mismatch', () => {
expect(() => divide([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { exp } = require('../../src/functions/exp.js');
describe('Exp', () => {
it('numbers', () => {
expect(exp(3)).toEqual(Math.exp(3));
expect(exp(0)).toEqual(Math.exp(0));
expect(exp(5)).toEqual(Math.exp(5));
});
it('arrays', () => {
expect(exp([3, 4, 5])).toEqual([Math.exp(3), Math.exp(4), Math.exp(5)]);
expect(exp([1, 2, 10])).toEqual([Math.exp(1), Math.exp(2), Math.exp(10)]);
expect(exp([10])).toEqual([Math.exp(10)]);
});
});

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { first } = require('../../src/functions/first.js');
describe('First', () => {
it('numbers', () => {
expect(first(-10)).toEqual(-10);
expect(first(10)).toEqual(10);
});
it('arrays', () => {
expect(first([])).toEqual(undefined);
expect(first([-1])).toEqual(-1);
expect(first([-10, -20, -30, -40])).toEqual(-10);
expect(first([-13, 30, -90, 200])).toEqual(-13);
});
it('skips number validation', () => {
expect(first).toHaveProperty('skipNumberValidation', true);
});
});

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { fix } = require('../../src/functions/fix.js');
describe('Fix', () => {
it('numbers', () => {
expect(fix(-10.5)).toEqual(-10);
expect(fix(-10.1)).toEqual(-10);
expect(fix(10.9)).toEqual(10);
});
it('arrays', () => {
expect(fix([-10.5, -20.9, -30.1, -40.2])).toEqual([-10, -20, -30, -40]);
expect(fix([2.9, 5.1, 3.5, 4.3])).toEqual([2, 5, 3, 4]);
});
});

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { floor } = require('../../src/functions/floor.js');
describe('Floor', () => {
it('numbers', () => {
expect(floor(-10.5)).toEqual(-11);
expect(floor(-10.1)).toEqual(-11);
expect(floor(10.9)).toEqual(10);
});
it('arrays', () => {
expect(floor([-10.5, -20.9, -30.1, -40.2])).toEqual([-11, -21, -31, -41]);
expect(floor([2.9, 5.1, 3.5, 4.3])).toEqual([2, 5, 3, 4]);
});
});

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { last } = require('../../src/functions/last.js');
describe('Last', () => {
it('numbers', () => {
expect(last(-10)).toEqual(-10);
expect(last(10)).toEqual(10);
});
it('arrays', () => {
expect(last([])).toEqual(undefined);
expect(last([-1])).toEqual(-1);
expect(last([-10, -20, -30, -40])).toEqual(-40);
expect(last([-13, 30, -90, 200])).toEqual(200);
});
it('skips number validation', () => {
expect(last).toHaveProperty('skipNumberValidation', true);
});
});

View file

@ -0,0 +1,39 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { log } = require('../../src/functions/log.js');
describe('Log', () => {
it('numbers', () => {
expect(log(1)).toEqual(Math.log(1));
expect(log(3, 2)).toEqual(Math.log(3) / Math.log(2));
expect(log(11, 3)).toEqual(Math.log(11) / Math.log(3));
expect(log(42, 5)).toEqual(2.322344707681546);
});
it('arrays', () => {
expect(log([3, 4, 5], 3)).toEqual([
Math.log(3) / Math.log(3),
Math.log(4) / Math.log(3),
Math.log(5) / Math.log(3),
]);
expect(log([1, 2, 10], 10)).toEqual([
Math.log(1) / Math.log(10),
Math.log(2) / Math.log(10),
Math.log(10) / Math.log(10),
]);
});
it('number less than 1', () => {
expect(() => log(-1)).toThrow('Must be greater than 0');
});
it('base out of range', () => {
expect(() => log(1, -1)).toThrow('Base out of range');
});
});

View file

@ -0,0 +1,35 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { log10 } = require('../../src/functions/log10.js');
describe('Log10', () => {
it('numbers', () => {
expect(log10(1)).toEqual(Math.log(1) / Math.log(10));
expect(log10(3)).toEqual(Math.log(3) / Math.log(10));
expect(log10(11)).toEqual(Math.log(11) / Math.log(10));
expect(log10(80)).toEqual(1.9030899869919433);
});
it('arrays', () => {
expect(log10([3, 4, 5], 3)).toEqual([
Math.log(3) / Math.log(10),
Math.log(4) / Math.log(10),
Math.log(5) / Math.log(10),
]);
expect(log10([1, 2, 10], 10)).toEqual([
Math.log(1) / Math.log(10),
Math.log(2) / Math.log(10),
Math.log(10) / Math.log(10),
]);
});
it('number less than 1', () => {
expect(() => log10(-1)).toThrow('Must be greater than 0');
});
});

View file

@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { max } = require('../../src/functions/max.js');
describe('Max', () => {
it('numbers', () => {
expect(max(1)).toEqual(1);
expect(max(10, 2, 5, 8)).toEqual(10);
expect(max(0.1, 0.2, 0.4, 0.3)).toEqual(0.4);
});
it('arrays & numbers', () => {
expect(max([88, 20, 30, 40], 60, [30, 10, 70, 90])).toEqual([88, 60, 70, 90]);
expect(max(10, [10, 20, 30, 40], [1, 2, 3, 4], 22)).toEqual([22, 22, 30, 40]);
});
it('arrays', () => {
expect(max([1, 2, 3, 4])).toEqual(4);
expect(max([6, 2, 3, 10], [11, 2, 5, 10])).toEqual([11, 2, 5, 10]);
expect(max([30, 55, 9, 4], [72, 24, 48, 10], [10, 20, 30, 40])).toEqual([72, 55, 48, 40]);
expect(max([11, 28, 60, 10], [1, 48, 3, -17])).toEqual([11, 48, 60, 10]);
});
it('array length mismatch', () => {
expect(() => max([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { mean } = require('../../src/functions/mean.js');
describe('Mean', () => {
it('numbers', () => {
expect(mean(1)).toEqual(1);
expect(mean(10, 2, 5, 8)).toEqual(25 / 4);
expect(mean(0.1, 0.2, 0.4, 0.3)).toEqual((0.1 + 0.2 + 0.3 + 0.4) / 4);
});
it('arrays & numbers', () => {
expect(mean([10, 20, 30, 40], 10, 20, 30)).toEqual([70 / 4, 80 / 4, 90 / 4, 100 / 4]);
expect(mean(10, [10, 20, 30, 40], [1, 2, 3, 4], 22)).toEqual([43 / 4, 54 / 4, 65 / 4, 76 / 4]);
});
it('arrays', () => {
expect(mean([1, 2, 3, 4])).toEqual(10 / 4);
expect(mean([1, 2, 3, 4], [1, 2, 5, 10])).toEqual([2 / 2, 4 / 2, 8 / 2, 14 / 2]);
expect(mean([1, 2, 3, 4], [1, 2, 5, 10], [10, 20, 30, 40])).toEqual([
12 / 3,
24 / 3,
38 / 3,
54 / 3,
]);
expect(mean([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([12 / 2, 50 / 2, 63 / 2, 76 / 2]);
});
it('array length mismatch', () => {
expect(() => mean([1, 2], [3])).toThrow();
});
});

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { median } = require('../../src/functions/median.js');
describe('Median', () => {
it('numbers', () => {
expect(median(1)).toEqual(1);
expect(median(10, 2, 5, 8)).toEqual((8 + 5) / 2);
expect(median(0.1, 0.2, 0.4, 0.3)).toEqual((0.2 + 0.3) / 2);
});
it('arrays & numbers', () => {
expect(median([10, 20, 30, 40], 10, 20, 30)).toEqual([15, 20, 25, 25]);
expect(median(10, [10, 20, 30, 40], [1, 2, 3, 4], 22)).toEqual([10, 15, 16, 16]);
});
it('arrays', () => {
expect(median([1, 2, 3, 4], [1, 2, 5, 10])).toEqual([1, 2, 4, 7]);
expect(median([1, 2, 3, 4], [1, 2, 5, 10], [10, 20, 30, 40])).toEqual([1, 2, 5, 10]);
expect(median([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([12 / 2, 50 / 2, 63 / 2, 76 / 2]);
});
it('array length mismatch', () => {
expect(() => median([1, 2], [3])).toThrow();
});
});

View file

@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { min } = require('../../src/functions/min.js');
describe('Min', () => {
it('numbers', () => {
expect(min(1)).toEqual(1);
expect(min(10, 2, 5, 8)).toEqual(2);
expect(min(0.1, 0.2, 0.4, 0.3)).toEqual(0.1);
});
it('arrays & numbers', () => {
expect(min([88, 20, 30, 100], 60, [30, 10, 70, 90])).toEqual([30, 10, 30, 60]);
expect(min([50, 20, 3, 40], 10, [13, 2, 34, 4], 22)).toEqual([10, 2, 3, 4]);
expect(min(10, [50, 20, 3, 40], [13, 2, 34, 4], 22)).toEqual([10, 2, 3, 4]);
});
it('arrays', () => {
expect(min([1, 2, 3, 4])).toEqual(1);
expect(min([6, 2, 30, 10], [11, 2, 5, 15])).toEqual([6, 2, 5, 10]);
expect(min([30, 55, 9, 4], [72, 24, 48, 10], [10, 20, 30, 40])).toEqual([10, 20, 9, 4]);
expect(min([11, 28, 60, 10], [1, 48, 3, -17])).toEqual([1, 28, 3, -17]);
});
it('array length mismatch', () => {
expect(() => min([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { mod } = require('../../src/functions/mod.js');
describe('Mod', () => {
it('number, number', () => {
expect(mod(13, 8)).toEqual(5);
expect(mod(0.1, 0.02)).toEqual(0.1 % 0.02);
});
it('array, number', () => {
expect(mod([13, 26, 34, 42], 10)).toEqual([3, 6, 4, 2]);
});
it('number, array', () => {
expect(mod(10, [3, 7, 2, 4])).toEqual([1, 3, 0, 2]);
});
it('array, array', () => {
expect(mod([11, 48, 60, 72], [4, 13, 9, 5])).toEqual([3, 9, 6, 2]);
});
it('array length mismatch', () => {
expect(() => mod([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,37 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { mode } = require('../../src/functions/mode.js');
describe('Mode', () => {
it('numbers', () => {
expect(mode(1)).toEqual(1);
expect(mode(10, 2, 5, 8)).toEqual([2, 5, 8, 10]);
expect(mode(0.1, 0.2, 0.4, 0.3)).toEqual([0.1, 0.2, 0.3, 0.4]);
expect(mode(1, 1, 2, 3, 1, 4, 3, 2, 4)).toEqual([1]);
});
it('arrays & numbers', () => {
expect(mode([10, 20, 30, 40], 10, 20, 30)).toEqual([[10], [20], [30], [10, 20, 30, 40]]);
expect(mode([1, 2, 3, 4], 2, 3, [3, 2, 4, 3])).toEqual([[3], [2], [3], [3]]);
});
it('arrays', () => {
expect(mode([1, 2, 3, 4], [1, 2, 5, 10])).toEqual([[1], [2], [3, 5], [4, 10]]);
expect(mode([1, 2, 3, 4], [1, 2, 1, 2], [2, 3, 2, 3], [4, 3, 2, 3])).toEqual([
[1],
[2, 3],
[2],
[3],
]);
});
it('array length mismatch', () => {
expect(() => mode([1, 2], [3])).toThrow();
});
});

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { multiply } = require('../../src/functions/multiply.js');
describe('Multiply', () => {
it('number, number', () => {
expect(multiply(10, 2)).toEqual(20);
expect(multiply(0.1, 0.2)).toEqual(0.1 * 0.2);
});
it('array, number', () => {
expect(multiply([10, 20, 30, 40], 10)).toEqual([100, 200, 300, 400]);
});
it('number, array', () => {
expect(multiply(10, [1, 2, 5, 10])).toEqual([10, 20, 50, 100]);
});
it('array, array', () => {
expect(multiply([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([11, 96, 180, 288]);
});
it('array length mismatch', () => {
expect(() => multiply([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,15 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { pi } = require('../../src/functions/pi.js');
describe('PI', () => {
it('constant', () => {
expect(pi()).toEqual(Math.PI);
});
});

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { pow } = require('../../src/functions/pow.js');
describe('Pow', () => {
it('numbers', () => {
expect(pow(3, 2)).toEqual(9);
expect(pow(-1, -1)).toEqual(-1);
expect(pow(5, 0)).toEqual(1);
});
it('arrays', () => {
expect(pow([3, 4, 5], 3)).toEqual([Math.pow(3, 3), Math.pow(4, 3), Math.pow(5, 3)]);
expect(pow([1, 2, 10], 10)).toEqual([Math.pow(1, 10), Math.pow(2, 10), Math.pow(10, 10)]);
});
it('missing exponent', () => {
expect(() => pow(1)).toThrow('Missing exponent');
});
});

View file

@ -0,0 +1,25 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { radtodeg } = require('../../src/functions/radtodeg.js');
describe('Radians to Degrees', () => {
it('numbers', () => {
expect(radtodeg(0)).toEqual(0);
expect(radtodeg(1.5707963267948966)).toEqual(90);
});
it('arrays', () => {
expect(radtodeg([0, 1.5707963267948966, 3.141592653589793, 6.283185307179586])).toEqual([
0,
90,
180,
360,
]);
});
});

View file

@ -0,0 +1,31 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { random } = require('../../src/functions/random.js');
describe('Random', () => {
it('numbers', () => {
const random1 = random();
expect(random1).toBeGreaterThanOrEqual(0);
expect(random1).toBeLessThan(1);
expect(random(0)).toEqual(0);
const random3 = random(3);
expect(random3).toBeGreaterThanOrEqual(0);
expect(random3).toBeLessThan(3);
const random100 = random(-100, 100);
expect(random100).toBeGreaterThanOrEqual(-100);
expect(random100).toBeLessThan(100);
expect(random(1, 1)).toEqual(1);
expect(random(100, 100)).toEqual(100);
});
it('min greater than max', () => {
expect(() => random(-1)).toThrow('Min is greater than max');
expect(() => random(3, 1)).toThrow('Min is greater than max');
});
});

View file

@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { range } = require('../../src/functions/range.js');
describe('Range', () => {
it('numbers', () => {
expect(range(1)).toEqual(0);
expect(range(10, 2, 5, 8)).toEqual(8);
expect(range(0.1, 0.2, 0.4, 0.3)).toEqual(0.4 - 0.1);
});
it('arrays & numbers', () => {
expect(range([88, 20, 30, 40], 60, [30, 10, 70, 90])).toEqual([58, 50, 40, 50]);
expect(range(10, [10, 20, 30, 40], [1, 2, 3, 4], 22)).toEqual([21, 20, 27, 36]);
});
it('arrays', () => {
expect(range([1, 2, 3, 4])).toEqual(3);
expect(range([6, 2, 3, 10], [11, 2, 5, 10])).toEqual([5, 0, 2, 0]);
expect(range([30, 55, 9, 4], [72, 24, 48, 10], [10, 20, 30, 40])).toEqual([62, 35, 39, 36]);
expect(range([11, 28, 60, 10], [1, 48, 3, -17])).toEqual([10, 20, 57, 27]);
});
it('array length mismatch', () => {
expect(() => range([1, 2], [3])).toThrow();
});
});

View file

@ -0,0 +1,22 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { round } = require('../../src/functions/round.js');
describe('Round', () => {
it('numbers', () => {
expect(round(-10.51)).toEqual(-11);
expect(round(-10.1, 2)).toEqual(-10.1);
expect(round(10.93745987, 4)).toEqual(10.9375);
});
it('arrays', () => {
expect(round([-10.51, -20.9, -30.1, -40.2])).toEqual([-11, -21, -30, -40]);
expect(round([2.9234, 5.1234, 3.5234, 4.49234324], 2)).toEqual([2.92, 5.12, 3.52, 4.49]);
});
});

View file

@ -0,0 +1,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { sin } = require('../../src/functions/sin.js');
describe('Sine', () => {
it('numbers', () => {
expect(sin(0)).toEqual(0);
expect(sin(1.5707963267948966)).toEqual(1);
});
it('arrays', () => {
expect(sin([0, 1.5707963267948966])).toEqual([0, 1]);
});
});

View file

@ -0,0 +1,30 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { size } = require('../../src/functions/size.js');
describe('Size (also Count)', () => {
it('array', () => {
expect(size([])).toEqual(0);
expect(size([10, 20, 30, 40])).toEqual(4);
});
it('not an array', () => {
expect(() => size(null)).toThrow('Must pass an array');
expect(() => size(undefined)).toThrow('Must pass an array');
expect(() => size('string')).toThrow('Must pass an array');
expect(() => size(10)).toThrow('Must pass an array');
expect(() => size(true)).toThrow('Must pass an array');
expect(() => size({})).toThrow('Must pass an array');
expect(() => size(function () {})).toThrow('Must pass an array');
});
it('skips number validation', () => {
expect(size).toHaveProperty('skipNumberValidation', true);
});
});

View file

@ -0,0 +1,26 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { sqrt } = require('../../src/functions/sqrt.js');
describe('Sqrt', () => {
it('numbers', () => {
expect(sqrt(9)).toEqual(3);
expect(sqrt(0)).toEqual(0);
expect(sqrt(30)).toEqual(5.477225575051661);
});
it('arrays', () => {
expect(sqrt([49, 64, 81])).toEqual([7, 8, 9]);
expect(sqrt([1, 4, 100])).toEqual([1, 2, 10]);
});
it('Invalid negative number', () => {
expect(() => sqrt(-1)).toThrow('Unable find the square root of a negative number');
});
});

View file

@ -0,0 +1,21 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { square } = require('../../src/functions/square.js');
describe('Square', () => {
it('numbers', () => {
expect(square(3)).toEqual(9);
expect(square(-1)).toEqual(1);
});
it('arrays', () => {
expect(square([3, 4, 5])).toEqual([9, 16, 25]);
expect(square([1, 2, 10])).toEqual([1, 4, 100]);
});
});

View file

@ -0,0 +1,32 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { subtract } = require('../../src/functions/subtract.js');
describe('Subtract', () => {
it('number, number', () => {
expect(subtract(10, 2)).toEqual(8);
expect(subtract(0.1, 0.2)).toEqual(0.1 - 0.2);
});
it('array, number', () => {
expect(subtract([10, 20, 30, 40], 10)).toEqual([0, 10, 20, 30]);
});
it('number, array', () => {
expect(subtract(10, [1, 2, 5, 10])).toEqual([9, 8, 5, 0]);
});
it('array, array', () => {
expect(subtract([11, 48, 60, 72], [1, 2, 3, 4])).toEqual([10, 46, 57, 68]);
});
it('array length mismatch', () => {
expect(() => subtract([1, 2], [3])).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { sum } = require('../../src/functions/sum.js');
describe('Sum', () => {
it('numbers', () => {
expect(sum(10, 2, 5, 8)).toEqual(25);
expect(sum(0.1, 0.2, 0.4, 0.3)).toEqual(0.1 + 0.2 + 0.3 + 0.4);
});
it('arrays & numbers', () => {
expect(sum([10, 20, 30, 40], 10, 20, 30)).toEqual(160);
expect(sum([10, 20, 30, 40], 10, [1, 2, 3], 22)).toEqual(138);
});
it('arrays', () => {
expect(sum([1, 2, 3, 4], [1, 2, 5, 10])).toEqual(28);
expect(sum([1, 2, 3, 4], [1, 2, 5, 10], [10, 20, 30, 40])).toEqual(128);
expect(sum([11, 48, 60, 72], [1, 2, 3, 4])).toEqual(201);
});
});

View file

@ -0,0 +1,20 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { tan } = require('../../src/functions/tan.js');
describe('Tangent', () => {
it('numbers', () => {
expect(tan(0)).toEqual(0);
expect(tan(1)).toEqual(1.5574077246549023);
});
it('arrays', () => {
expect(tan([0, 1])).toEqual([0, 1.5574077246549023]);
});
});

View file

@ -0,0 +1,41 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { transpose } = require('../../src/functions/lib/transpose');
describe('transpose', () => {
it('2D arrays', () => {
expect(
transpose(
[
[1, 2],
[3, 4],
[5, 6],
],
0
)
).toEqual([
[1, 3, 5],
[2, 4, 6],
]);
expect(transpose([10, 20, [10, 20, 30, 40], 30], 2)).toEqual([
[10, 20, 10, 30],
[10, 20, 20, 30],
[10, 20, 30, 30],
[10, 20, 40, 30],
]);
expect(transpose([4, [1, 9], [3, 5]], 1)).toEqual([
[4, 1, 3],
[4, 9, 5],
]);
});
it('array length mismatch', () => {
expect(() => transpose([[1], [2, 3]], 0)).toThrow('Array length mismatch');
});
});

View file

@ -0,0 +1,27 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
const { unique } = require('../../src/functions/unique.js');
describe('Unique', () => {
it('numbers', () => {
expect(unique(1)).toEqual(1);
expect(unique(10000)).toEqual(1);
});
it('arrays', () => {
expect(unique([])).toEqual(0);
expect(unique([-10, -20, -30, -40])).toEqual(4);
expect(unique([-13, 30, -90, 200])).toEqual(4);
expect(unique([1, 2, 3, 4, 2, 2, 2, 3, 4, 2, 4, 5, 2, 1, 4, 2])).toEqual(5);
});
it('skips number validation', () => {
expect(unique).toHaveProperty('skipNumberValidation', true);
});
});

View file

@ -0,0 +1,273 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* and the Server Side Public License, v 1; you may not use this file except in
* compliance with, at your election, the Elastic License or the Server Side
* Public License, v 1.
*/
/*
TODO: These tests are wildly imcomplete
Need tests for spacing, etc
*/
const { evaluate, parse } = require('..');
describe('Parser', () => {
describe('Numbers', () => {
it('integers', () => {
expect(parse('10')).toEqual(10);
});
it('floats', () => {
expect(parse('10.5')).toEqual(10.5);
});
it('negatives', () => {
expect(parse('-10')).toEqual(-10);
expect(parse('-10.5')).toEqual(-10.5);
});
});
describe('Variables', () => {
it('strings', () => {
expect(parse('f')).toEqual('f');
expect(parse('foo')).toEqual('foo');
});
it('allowed characters', () => {
expect(parse('_foo')).toEqual('_foo');
expect(parse('@foo')).toEqual('@foo');
expect(parse('.foo')).toEqual('.foo');
expect(parse('-foo')).toEqual('-foo');
expect(parse('_foo0')).toEqual('_foo0');
expect(parse('@foo0')).toEqual('@foo0');
expect(parse('.foo0')).toEqual('.foo0');
expect(parse('-foo0')).toEqual('-foo0');
});
});
describe('quoted variables', () => {
it('strings with double quotes', () => {
expect(parse('"foo"')).toEqual('foo');
expect(parse('"f b"')).toEqual('f b');
expect(parse('"foo bar"')).toEqual('foo bar');
expect(parse('"foo bar fizz buzz"')).toEqual('foo bar fizz buzz');
expect(parse('"foo bar baby"')).toEqual('foo bar baby');
});
it('strings with single quotes', () => {
/* eslint-disable prettier/prettier */
expect(parse("'foo'")).toEqual('foo');
expect(parse("'f b'")).toEqual('f b');
expect(parse("'foo bar'")).toEqual('foo bar');
expect(parse("'foo bar fizz buzz'")).toEqual('foo bar fizz buzz');
expect(parse("'foo bar baby'")).toEqual('foo bar baby');
/* eslint-enable prettier/prettier */
});
it('allowed characters', () => {
expect(parse('"_foo bar"')).toEqual('_foo bar');
expect(parse('"@foo bar"')).toEqual('@foo bar');
expect(parse('".foo bar"')).toEqual('.foo bar');
expect(parse('"-foo bar"')).toEqual('-foo bar');
expect(parse('"_foo0 bar1"')).toEqual('_foo0 bar1');
expect(parse('"@foo0 bar1"')).toEqual('@foo0 bar1');
expect(parse('".foo0 bar1"')).toEqual('.foo0 bar1');
expect(parse('"-foo0 bar1"')).toEqual('-foo0 bar1');
});
it('invalid characters in double quotes', () => {
const check = (str) => () => parse(str);
expect(check('" foo bar"')).toThrow('but "\\"" found');
expect(check('"foo bar "')).toThrow('but "\\"" found');
expect(check('"0foo"')).toThrow('but "\\"" found');
expect(check('" foo bar"')).toThrow('but "\\"" found');
expect(check('"foo bar "')).toThrow('but "\\"" found');
expect(check('"0foo"')).toThrow('but "\\"" found');
});
it('invalid characters in single quotes', () => {
const check = (str) => () => parse(str);
/* eslint-disable prettier/prettier */
expect(check("' foo bar'")).toThrow('but "\'" found');
expect(check("'foo bar '")).toThrow('but "\'" found');
expect(check("'0foo'")).toThrow('but "\'" found');
expect(check("' foo bar'")).toThrow('but "\'" found');
expect(check("'foo bar '")).toThrow('but "\'" found');
expect(check("'0foo'")).toThrow('but "\'" found');
/* eslint-enable prettier/prettier */
});
});
describe('Functions', () => {
it('no arguments', () => {
expect(parse('foo()')).toEqual({ name: 'foo', args: [] });
});
it('arguments', () => {
expect(parse('foo(5,10)')).toEqual({ name: 'foo', args: [5, 10] });
});
it('arguments with strings', () => {
expect(parse('foo("string with spaces")')).toEqual({
name: 'foo',
args: ['string with spaces'],
});
/* eslint-disable prettier/prettier */
expect(parse("foo('string with spaces')")).toEqual({
name: 'foo',
args: ['string with spaces'],
});
/* eslint-enable prettier/prettier */
});
});
it('Missing expression', () => {
expect(() => parse(undefined)).toThrow('Missing expression');
expect(() => parse(null)).toThrow('Missing expression');
});
it('Failed parse', () => {
expect(() => parse('')).toThrow('Failed to parse expression');
});
it('Not a string', () => {
expect(() => parse(3)).toThrow('Expression must be a string');
});
});
describe('Evaluate', () => {
it('numbers', () => {
expect(evaluate('10')).toEqual(10);
});
it('variables', () => {
expect(evaluate('foo', { foo: 10 })).toEqual(10);
expect(evaluate('bar', { bar: [1, 2] })).toEqual([1, 2]);
});
it('variables with spaces', () => {
expect(evaluate('"foo bar"', { 'foo bar': 10 })).toEqual(10);
expect(evaluate('"key with many spaces in it"', { 'key with many spaces in it': 10 })).toEqual(
10
);
});
it('valiables with dots', () => {
expect(evaluate('foo.bar', { 'foo.bar': 20 })).toEqual(20);
expect(evaluate('"is.null"', { 'is.null': null })).toEqual(null);
expect(evaluate('"is.false"', { 'is.null': null, 'is.false': false })).toEqual(false);
expect(evaluate('"with space.val"', { 'with space.val': 42 })).toEqual(42);
});
it('variables with dot notation', () => {
expect(evaluate('foo.bar', { foo: { bar: 20 } })).toEqual(20);
expect(evaluate('foo.bar[0].baz', { foo: { bar: [{ baz: 30 }, { beer: 40 }] } })).toEqual(30);
expect(evaluate('"is.false"', { is: { null: null, false: false } })).toEqual(false);
});
it('equations', () => {
expect(evaluate('3 + 4')).toEqual(7);
expect(evaluate('10 - 2')).toEqual(8);
expect(evaluate('8 + 6 / 3')).toEqual(10);
expect(evaluate('10 * (1 + 2)')).toEqual(30);
expect(evaluate('(3 - 4) * 10')).toEqual(-10);
expect(evaluate('-1 - -12')).toEqual(11);
expect(evaluate('5/20')).toEqual(0.25);
expect(evaluate('1 + 1 + 2 + 3 + 12')).toEqual(19);
expect(evaluate('100 / 10 / 10')).toEqual(1);
});
it('equations with functions', () => {
expect(evaluate('3 + multiply(10, 4)')).toEqual(43);
expect(evaluate('3 + multiply(10, 4, 5)')).toEqual(203);
});
it('equations with trigonometry', () => {
expect(evaluate('pi()')).toEqual(Math.PI);
expect(evaluate('sin(degtorad(0))')).toEqual(0);
expect(evaluate('sin(degtorad(180))')).toEqual(1.2246467991473532e-16);
expect(evaluate('cos(degtorad(0))')).toEqual(1);
expect(evaluate('cos(degtorad(180))')).toEqual(-1);
expect(evaluate('tan(degtorad(0))')).toEqual(0);
expect(evaluate('tan(degtorad(180))')).toEqual(-1.2246467991473532e-16);
});
it('equations with variables', () => {
expect(evaluate('3 + foo', { foo: 5 })).toEqual(8);
expect(evaluate('3 + foo', { foo: [5, 10] })).toEqual([8, 13]);
expect(evaluate('3 + foo', { foo: 5 })).toEqual(8);
expect(evaluate('sum(foo)', { foo: [5, 10, 15] })).toEqual(30);
expect(evaluate('90 / sum(foo)', { foo: [5, 10, 15] })).toEqual(3);
expect(evaluate('multiply(foo, bar)', { foo: [1, 2, 3], bar: [4, 5, 6] })).toEqual([4, 10, 18]);
});
it('equations with quoted variables', () => {
expect(evaluate('"b" * 7', { b: 3 })).toEqual(21);
expect(evaluate('"space name" * 2', { 'space name': [1, 2, 21] })).toEqual([2, 4, 42]);
expect(evaluate('sum("space name")', { 'space name': [1, 2, 21] })).toEqual(24);
});
it('equations with injected functions', () => {
expect(
evaluate(
'plustwo(foo)',
{ foo: 5 },
{
plustwo: function (a) {
return a + 2;
},
}
)
).toEqual(7);
expect(
evaluate('negate(1)', null, {
negate: function (a) {
return -a;
},
})
).toEqual(-1);
expect(
evaluate('stringify(2)', null, {
stringify: function (a) {
return '' + a;
},
})
).toEqual('2');
});
it('equations with arrays using special operator functions', () => {
expect(evaluate('foo + bar', { foo: [1, 2, 3], bar: [4, 5, 6] })).toEqual([5, 7, 9]);
expect(evaluate('foo - bar', { foo: [1, 2, 3], bar: [4, 5, 6] })).toEqual([-3, -3, -3]);
expect(evaluate('foo * bar', { foo: [1, 2, 3], bar: [4, 5, 6] })).toEqual([4, 10, 18]);
expect(evaluate('foo / bar', { foo: [1, 2, 3], bar: [4, 5, 6] })).toEqual([
1 / 4,
2 / 5,
3 / 6,
]);
});
it('missing expression', () => {
expect(() => evaluate('')).toThrow('Failed to parse expression');
});
it('missing referenced scope when used in injected function', () => {
expect(() =>
evaluate('increment(foo)', null, {
increment: function (a) {
return a + 1;
},
})
).toThrow('Unknown variable: foo');
});
it('invalid context datatypes', () => {
expect(evaluate('mean(foo)', { foo: [true, true, false] })).toBeNaN();
expect(evaluate('mean(foo + bar)', { foo: [true, true, false], bar: [1, 2, 3] })).toBeNaN();
expect(evaluate('mean(foo)', { foo: ['dog', 'cat', 'mouse'] })).toBeNaN();
expect(evaluate('mean(foo + 2)', { foo: ['dog', 'cat', 'mouse'] })).toBeNaN();
expect(evaluate('foo + bar', { foo: NaN, bar: [4, 5, 6] })).toBeNaN();
});
});

View file

@ -114,7 +114,7 @@ export function MathAgg(props) {
values={{
link: (
<EuiLink
href="https://github.com/elastic/tinymath/blob/master/docs/functions.md"
href="https://github.com/elastic/kibana/blob/master/packages/kbn-tinymath/docs/functions.md"
target="_blank"
>
<FormattedMessage

View file

@ -12,7 +12,7 @@ import { getDefaultDecoration } from '../../helpers/get_default_decoration';
import { getSiblingAggValue } from '../../helpers/get_sibling_agg_value';
import { getSplits } from '../../helpers/get_splits';
import { mapBucket } from '../../helpers/map_bucket';
import { evaluate } from 'tinymath';
import { evaluate } from '@kbn/tinymath';
export function mathAgg(resp, panel, series, meta, extractFields) {
return (next) => async (results) => {

View file

@ -5,7 +5,7 @@
*/
// @ts-expect-error no @typed def; Elastic library
import { evaluate } from 'tinymath';
import { evaluate } from '@kbn/tinymath';
import { pivotObjectArray } from '../../../common/lib/pivot_object_array';
import { Datatable, isDatatable, ExpressionFunctionDefinition } from '../../../types';
import { getFunctionHelp, getFunctionErrors } from '../../../i18n';

View file

@ -5,7 +5,7 @@
*/
// @ts-expect-error untyped library
import { parse } from 'tinymath';
import { parse } from '@kbn/tinymath';
import { getFieldNames } from './pointseries/lib/get_field_names';
describe('getFieldNames', () => {

View file

@ -5,7 +5,7 @@
*/
// @ts-expect-error Untyped Elastic library
import { evaluate } from 'tinymath';
import { evaluate } from '@kbn/tinymath';
import { groupBy, zipObject, omit, uniqBy } from 'lodash';
import moment from 'moment';
import { ExpressionFunctionDefinition } from 'src/plugins/expressions/common';

View file

@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { parse } from 'tinymath';
import { parse } from '@kbn/tinymath';
import { getFieldType } from '../../../../../common/lib/get_field_type';
import { isColumnReference } from './is_column_reference';
import { getFieldNames } from './get_field_names';

View file

@ -5,7 +5,7 @@
*/
// @ts-expect-error untyped library
import { parse } from 'tinymath';
import { parse } from '@kbn/tinymath';
export function isColumnReference(mathExpression: string | null): boolean {
if (mathExpression == null) {

View file

@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { parse } from 'tinymath';
import { parse } from '@kbn/tinymath';
import { unquoteString } from '../../../../common/lib/unquote_string';
// break out into separate function, write unit tests first

Some files were not shown because too many files have changed in this diff Show more