Files
Tsering Paljor 8c0d3bc373 Add more advanced formulas (#4297)
* Add replace()

* Add length()

* Add contains()

* Add reverse()

* Add join()

* Add split()

* Add is_empty()

* Add strip()

* Add sum()

* Add avg()

* Add at()

* Add changelog

* Small fixes

* Add tests for ensure_array()

* Improve error handling for RuntimeLength

* RuntimeContains should return None/null for the default case

* Improve array/object/int check for RuntimeIsEmpty

* Fix logic to only work on strings for RuntimeStrip

* Lint fix

* RuntimeSum backend validation shouldn't allow non-numbers.

* RuntimeAvg backend validation shouldn't allow non-numbers.

* Handle ValueError in literal array string

* Lint fix backend

* Fix frontend tests

* Add more test cases

* Refactor backend tests

* Remove allowLiteralArray/allow_literal_array

* Add new RuntimeToArray function and refactor existing functions that use Any type to avoid using ensurer. Update examples with usage of to_array.

* Refactor frontend tests

* Add RuntimeToArray in the backend + tests

* Refactor backend functions/tests to avoid using ensurer

* Improve frontend validation and tests

* Fix examples

* simplify

* Remove local debugging code

* Allow > to compare any type

* Allow < to compare any type

* Allow >= to compare any type

* Allow <= to compare any type

* lint fix

* is_empty should raise an error for unsupported types.

* Change arg type to text for strip

* split() should return a list with the same arg if the string has no spaces and no delimited is provided.

* Update avg() helper to allow a strict param

* Fix toArray description

* is_empty() should return false by default, and handle supported args correctly.

* Refactor at() to bubble up error

* Let join() bubble up errors

* Allow reverse() to bubble up errors

* Allow contains() to bubble up errors

* Allow length() to bubble up errors

* Update examples for comparison operators to include date examples
2025-12-19 15:33:54 +04:00

48 lines
1.1 KiB
JavaScript

export const rounder = (digits) => {
return parseInt('1' + Array(digits + 1).join('0'))
}
export const floor = (n, digits = 0) => {
const r = rounder(digits)
return Math.floor(n * r) / r
}
export const ceil = (n, digits = 0) => {
const r = rounder(digits)
return Math.ceil(n * r) / r
}
export const clamp = (value, min, max) => {
return Math.max(min, Math.min(value, max))
}
export const sum = (arr, { strict = false } = {}) => {
return arr.reduce((total, val) => {
const num = Number(val)
if (Number.isFinite(num)) {
return total + num
} else if (strict) {
throw new Error(`Invalid number: ${val}`)
}
return total
}, 0)
}
export const avg = (arr, { strict = false } = {}) => {
let validNumbers = 0
const _sum = arr.reduce((total, val) => {
const num = Number(val)
if (Number.isFinite(num)) {
validNumbers++
return total + num
} else if (strict) {
throw new Error(`Invalid number: ${val}`)
}
return total
}, 0)
if (validNumbers > 0) {
return _sum / validNumbers
}
return _sum
}