Skip to main content

Util functions

Various utility functions.


assert()

Returns an Error with message if the value is false. If the value is true, nothing happens.

assert(value, [message])

Arguments

value (Any)
The assertion value.
message (String)
(Optional) The message string.

Returns

(Error)
Error if the value is false, else return nothing.

Examples

InputExpressionResult
18
attempt(
&assert([0] >= 21, 'Age under 21'),
@
) | to_string(@) || 'ok'
"RuntimeError: Function invocation failed: assert(...). Age under 21"

attempt()

Attempts to evaluate function and returns either the result or any caught error object. Additional arguments are passed to the function when evaluated.

attempt(function, [arg1, [arg2, [...]]])

Arguments

function (Expression)
The expression to evaluate.
args (Any)
(Optional) The arguments to evaluate function with.

Returns

(Any)
The function result or error object.

Examples

InputExpressionResult
[]
attempt(&length([0]), [1,2,3], 123)
3
[]
attempt(&length([1]), [1,2,3], 123)
{ "name": "TypeMismatchError" }

case_default()

Helper function that works exclusively within switch() or cond() functions. Returns the result of default only when no other case functions are truthy.

case_default(default)

Arguments

default (Expression, Any)
(Optional) The value or the expression to evaluate. For switch(), uses the function context; for cond(), uses value. Defaults to &@.

Examples

InputExpressionResult
1
switch(
&case_when(&@ > 0, &@)
&case_default(0)
)
1
-1
switch(
&case_when(&@ > 0, &@)
&case_default(0)
)
0

case_when()

Helper function that works exclusively within switch() or cond() functions. Evaluates the predicate and returns the result of ifTrue only if the predicate is truthy.

case_when(predicate, [ifTrue])

Arguments

predicate (Expression, Any)
The predicate to evaluate.
ifTrue (Expression, Any)
(Optional) The value or the expression to evaluate when predicate is truthy. For switch(), uses the function context; for cond(), uses value. Defaults to &@.

Examples

InputExpressionResult
1
switch(
&case_when(&mod(@, 2) == 0, 'even')
&case_when(&mod(@, 2) > 0)
)
1
2
switch(
&case_when(&mod(@, 2) == 0, 'even')
&case_when(&mod(@, 2) > 0)
)
"even"

case_with()

Helper function that works exclusively within switch() or cond() functions. Evaluates the predicate and returns the result of ifTrue only if the predicate is truthy, using the predicate’s result as context.

case_with(predicate, [ifTrue])

Arguments

predicate (Expression, Any)
The predicate to evaluate.
ifTrue (Expression, Any)
(Optional) The value or the expression to evaluate when predicate is truthy. Uses the result of predicate as context. Defaults to &@.

Examples

InputExpressionResult
1
switch(
&case_with(&add(@, 1), &@)
&case_with(true, 'negative')
)
2
-1
switch(
&case_with(&add(@, 1), &@)
&case_with(true, 'negative')
)
"negative"

cond()

Iterates through cases and evaluates each case helper function or predicate with value in context. Returns the result of the corresponding function or function expression from the first case whose predicate is truthy.

cond(value, case1, [case2, [...]]])

Arguments

value (Any)
The input value.
cases (Expression, Array)

The case helper functions (case_when()case_with()case_default()) expressions or predicate-function pairs [predicatefunction].

predicate (Expression | Array | Object | String) – the predicate to evaluate, with value in context. Optional for the last pair (default condition).
function (Expression | Array | Object | String) – the value or the expression to evaluate when predicate is truthy. Uses the value as context.

Returns

(Any)
The result of the evaluated function.

Examples

InputExpressionResult
{ "grade": 79 }
cond(@,
[grade >= 80 && grade < 100, 'A'],
[grade >= 70 && grade < 80, 'B'],
[grade >= 60 && grade < 70, 'C'],
['D'] -- default value
)
"B"
{
"temp": 24,
"rain": true
}
cond(@,
[temp > 25, cond(@,
&case_when(rain, 'Take an umbrella'),
&case_default('Wear sunglasses')
)],
&case_when(temp > 5, cond(@,
[rain, 'Wear a hat and take an umbrella'],
['Wear a hat']
)),
['Stay home'] -- default value
)
"Take an umbrella"

dataurl_to_blob()

Given a string in Data URL format, returns a File object that can be submitted with the HTTP Connector using multipart/form-data encoding type.

dataurl_to_blob(dataURL)

Arguments

dataURL (String)
String, in Data URL format.

Returns

(Blob)
The File object.

Examples

InputExpressionResult
"data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E"
dataurl_to_blob(@)
File()

See Also


dataurl_to_text()

Given a string in Data URL format, returns a text. Assumes that Data URL contains text in UTF-8 encoding.

dataurl_to_text(dataURL)

Arguments

dataURL (String)
String, in Data URL format.

Returns

(String)
The decoded text.

Examples

InputExpressionResult
"data:,Hello%2C%20World%21"
dataurl_to_blob(@)
"Hello, World!"

See Also


default_to()

Checks value to determine whether a default value should be returned in its place. The defaultValue is returned if value is NaN, null, or undefined.

default_to(value, [defaultValue])

Arguments

value (Any)
The value to check.
defaultValue (Any)
The default value.

Returns

(Any)
The resolved value.

Examples

InputExpressionResult
[]
default_to(1, 10)
1
{
"a": 1
}
default_to(b, 10)
10

from_formdata()

Given FormData object returns array of key-value pairs.

from_formdata(formData)

Arguments

formData (FormData)
The FormObject data to convert.

Returns

(Array)
The key-value pairs.

Examples

InputExpressionResult
[]
from_formdata(to_formdata({ title: 'Job Title' }))
['title', 'Job Title']

See Also


if()

Returns the result of ifTrue if the predicate is truthy; otherwise, returns the result of ifFalse.

if(predicate, ifTrue, [ifFalse])

Arguments

predicate (Expression, Any)
The predicate to evaluate.
ifTrue (Expression, Any)
The value or the expression to evaluate when predicate is truthy.
ifFalse (Expression, Any)
(Optional) The value or the expression to evaluate when predicate is falsy. Defaults to &null.

Returns

(Any)
The value returned by either ifTrue or ifFalse, depending on which one is evaluated.

Examples

InputExpressionResult
[1, 2, 3]
if(&is_array(@), &length(@))
3
15
if(&@ >= 18, 'Access granted', 'Access denied')
"Access denied"

json_parse()

Parses a well-formed JSON string, constructing the value or object described by the string.

Aliases: parse_json().

json_parse(string)

Arguments

string (String)
The string to parse as JSON. See the JavaScript Object Notation (JSON) for a description of JSON syntax.

Returns

(Array)
The value (Object, Array, String, Number, Boolean, or null) corresponding to the given JSON string.

Examples

InputExpressionResult
[]
json_parse('{}')
{}
[]
json_parse('true')
true
[]
json_parse('"foo"')
"foo"
[]
json_parse('[1, 5, "false"]')
[1, 5, "false"]
[]
json_parse('null')
null

json_stringify()

Converts a value to a JSON string.

Aliases: to_json().

json_stringify(value, [space])

Arguments

value (Any)
The value to convert to a JSON string.
space (String | Number)

A String or Number object that's used to insert white space into the output JSON string for readability purposes.

If this is a Number, it indicates the number of space characters to use as white space for indenting purposes; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used.

If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.

Returns

(Array)
The JSON string representing the given value.

Examples

InputExpressionResult
{}
json_stringify(@)
"{}"
true
json_stringify(@)
"true"
"foo"
json_stringify(@)
"\"foo\""
[1, "false", false]
json_stringify(@)
"[\n  1,\n  \"false\",\n  false\n]"
{ "x": 5 }
json_stringify(@)
"{\n  \"x\": 5\n}"

parse_json()

Alias for json_parse().


range()

Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. If step is not specified, the default 1 or -1 is used.

range(start, end, [step])

Arguments

start (Number)
The start of the range.
end (Number)
The end of the range.
step (Number)
(Optional) The value to increment or decrement by. The default value is 1 or -1

Returns

(Array)
The range of numbers.

Examples

InputExpressionResult
[]
range(0, 4)
[0, 1, 2, 3]
[]
range(5, 20, 5)
[5, 10, 15]
[]
range(4, -3, -2)
[4, 2, 0, -2]
[]
range(`4.2`, 8)
[4.2, 5.2, 6.2, 7.2]
[]
range(2, 5, 0)
[2, 2, 2]

range_right()

This method is like range() except that it populates values in descending order.

range_right(start, end, [step])

Arguments

start (Number)
The start of the range.
end (Number)
The end of the range.
step (Number)
(Optional) The value to increment or decrement by. The default value is 1 or -1

Returns

(Array)
The range of numbers.

Examples

InputExpressionResult
[]
range_right(0, 4)
[3, 2, 1, 0]
[]
range_right(5, 20, 5)
[15, 10, 5]
[]
range_right(4, -3, -2)
[-2, 0, 2, 4]
[]
range_right(`4.2`, 8)
[7.2, 6.2, 5.2, 4.2]
[]
range_right(2, 5, 0)
[2, 2, 2]

repl()

Evaluates KelpQL expression represented as a string. This function makes possible to build REPL style interfaces in Kelp. See KelpQL Playground.

repl(expression, [data])

Arguments

expression (String)
The string representing a KelpQL expression, or sequence of expression.
data (Any)
(Optional) The arguments to invoke the expression with.

Returns

(Object)

The object with the completion result or error of evaluating the given expression.

status (String) - The status of the evaluation: success or error.
result (Any) - The completion value of evaluating the given code.
kind (String) - The kind of error occured during the evaluation.
reason (Error) - The Error object.

Examples

InputExpressionResult
[2, 3]
repl('add([0], [1])', @)
{
"status": "success",
"result": 5
}
[2, 3]
repl('add([0])', @)
{
"status": "error",
"kind": "runtime",
"reason": {
"name": "ArgumentError"
}
}

switch()

Iterates through cases and evaluates each case helper function or predicate. Returns the result of the corresponding function or function expression from the first case whose predicate is truthy.

switch(case1, [case2, [...]]])

Arguments

cases (Expression, Array)

The case helper functions (case_when()case_with()case_default()) expressions or predicate-function pairs [predicatefunction].

predicate (Expression | Array | Object | String) – the predicate to evaluate, with function context. Optional for the last pair (default condition).
function (Expression | Array | Object | String) – the value or the expression to evaluate when predicate is truthy. Uses the function context.

Returns

(Any)
The result of the evaluated function.

Examples

InputExpressionResult
{ "grade": 79 }
switch(
[grade >= 80 && grade < 100, 'A'],
[grade >= 70 && grade < 80, 'B'],
[grade >= 60 && grade < 70, 'C'],
['D'] -- default value
)
"B"
{
"temp": 24,
"rain": true
}
switch(
[temp > 25, cond(@,
&case_when(rain, 'Take an umbrella'),
&case_default('Wear sunglasses')
)],
&case_when(temp > 5, cond(@,
[rain, 'Wear a hat and take an umbrella'],
['Wear a hat']
)),
['Stay home'] -- default value
)
"Take an umbrella"

times()

Invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with one argument: (index).

times(n, [iteratee])

Arguments

n (Number)
The number of times to invoke iteratee.
iteratee (Expression)
(Optional) The expression invoked per iteration. The default value is &@. The iteratee is invoked with one argument: (index). The index starts from 0.

Returns

(Array)
The array of results.

Examples

InputExpressionResult
[]
times(4, &multiply(@, 2))
[0, 2, 4, 6]
[]
times(4, &to_string(@))
["0", "1", "2", "3"]

to_blob()

Creates a File from a plain string, blob, file, array buffer or typed array that can be submitted with an HTTP Connector using multipart/form-data encoding type. If the fileName is not provided, it returns a Blob object. If the input is already Blob or File, will use provided fileName and mimeType to override original values.

to_blob(input, [fileName, [mimeType]])

Arguments

input (String, Blob, Array, ArrayBuffer, TypedArray)
String, Blob, Array, ArrayBuffer or TypedArray, that will be converted to Blob object.
fileName (String)
(Optional) Filename to attach to Blob object.
mimeType (String)
(Optional) Mime-Type to associate with a string, i.e. text/plain.

Returns

(Blob)
The Blob or File object.

Examples

InputExpressionResult
[]
to_blob('<h1>Hello, World!</h1>')
File()

to_formdata()

Given plain object or array of key-value pairs creates FormData object that can be submitted with an HTTP Connector using multipart/form-data encoding type.

to_formdata(pairs)

Arguments

pairsOrObject (Array, Object, FormData)
Plain object, instance of FormData or key-value pairs.

Returns

(FormData)
The FormData object.

Examples

InputExpressionResult
[]
to_formdata({ title: 'Job Title', file: to_blob('Hellow World') })
FormData()

See Also


to_json()

Alias for json_stringify().


to_path()

Converts value to a property path array.

to_path(value)

Arguments

value (Any)
The value to convert.

Returns

(Array)
The new property path array.

Examples

InputExpressionResult
[]
to_path('a.b.c')
["a", "b", "c"]
[]
to_path('a[0].b.c')
["a", "0", "b", "c"]

try()

Evaluates function expression and returns either the onSuccess result with the function's output as context, or the onFailure result with the error object as context if it fails.

try(function, onSuccess, [onFailure])

Arguments

function (Expression)
The expression to evaluate.
onSuccess (Expression, Any)
The value or the expression to evaluate when the function succeeds. The expression will be evaluated using the function's result as context.
onFailure (Expression, Any)
(Optional) The value or the expression to evaluate when the function fails. The expression will be evaluated using the error object as context. Defaults to &null.

Returns

(Any)
The value returned by either onSuccess or onFailure, depending on which one is evaluated.

Examples

InputExpressionResult
[1, 2, 3]
try(&length(@), &@)
3
"{invalid json"
try(&json_parse(@), &@, &'parsing failed')
"parsing failed"

uuid_nil()

The "nil" UUID, a special case, is the UUID 00000000-0000-0000-0000-000000000000; that is, all bits set to zero.

uuid_nil()

Returns

(String)
The "nil" UUID string.

Examples

InputExpressionResult
[]
uuid_nil()
"00000000-0000-0000-0000-000000000000"

uuid_v1()

Generates a universally unique identifier (UUID) string, version 1 (timestamp).

uuid_v1()

Returns

(String)
The UUID string.

Examples

InputExpressionResult
[]
uuid_v1()
"2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d"

uuid_v4()

Generates pseudo-random universally unique identifier (UUID) string, version 4 (random).

uuid_v4()

Returns

(String)
The random UUID string.

Examples

InputExpressionResult
[]
uuid_v4()
"1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed"

uuid_v5()

Generates a name-based UUID, as described in RFC 4122 section 4.3, also known as a "version 5" UUID. Unlike the pseudo-random UUIDs generated by uuid_v4(), name-based UUIDs derive from namespace and an name, producing the same UUID value every time if the namespace and name are unchanged.

uuid_v5(name, namespace)

Arguments

name (String)
The name of UUID.
namespace (String)
The namespace of UUID. Use uuid_v5_ns_url() or uuid_v5_ns_dns() to generate custom URL or DNS namespace.

Returns

(String)
The UUID string.

Examples

InputExpressionResult
[]
uuid_v5(
'Hello World!',
'769a64ee-1380-5d3b-ad30-6a3c95ddf503'
)
"f71eb074-33e9-5135-8d0a-7c9c5f5c3edf"

uuid_v5_ns_dns()

Returns DNS UUID namespace string (6ba7b810-9dad-11d1-80b4-00c04fd430c8).

uuid_v5_ns_dns()

Returns

(String)
The DNS UUID namespace.

Examples

InputExpressionResult
[]
uuid_v5_ns_dns()
"6ba7b810-9dad-11d1-80b4-00c04fd430c8"
[]
uuid_v5(
'www.example.com',
uuid_v5_ns_dns()
)
-- Generate UUID for your custom namespace.
"2ed6657d-e927-568b-95e1-2665a8aea6a2"

uuid_v5_ns_url()

Returns URL UUID namespace string (6ba7b811-9dad-11d1-80b4-00c04fd430c8).

uuid_v5_ns_url()

Returns

(String)
The URL UUID namespace.

Examples

InputExpressionResult
[]
uuid_v5_ns_url()
"6ba7b811-9dad-11d1-80b4-00c04fd430c8"
[]
uuid_v5(
'https://www.example.com',
uuid_v5_ns_url()
)
-- Generate UUID for your custom namespace.
"a0787afd-c170-5773-8d60-02739168de9f"

uuid_v7()

Generates a time-ordered UUID, as described in RFC 9562 section 5.7, also known as a "version 7" UUID. Has improved entropy characteristics over UUIDs generated by uuid_v1().

uuid_v7()

Returns

(String)
The UUID string.

Examples

InputExpressionResult
[]
uuid_v7()
"0194bd7d-7e0f-7990-a958-2109d35ce995"

uuid_validate()

Checks is string is a valid UUID.

uuid_validate(value)

Arguments

value (String)
The value to inspect.

Returns

(String)
true if value is a valid UUID, false otherwise.

Examples

InputExpressionResult
"not a UUID"
uuid_validate(@)
false
"6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b"
uuid_validate(@)
true

uuid_version()

Detect version of a valid UUID string.

uuid_version(value)

Arguments

value (String)
The value to inspect.

Returns

(String)
The string representation of the UUID version number (per RFC 9562).

Examples

InputExpressionResult
"45637ec4-c85f-11ea-87d0-0242ac130003"
uuid_version()
1
"6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b"
uuid_version(@)
4
"Invalid UUID string"
attempt(&uuid_version(@))
{
"name": "RuntimeError"
}