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 invoke func, returning either the result or the caught error object. Any additional arguments are provided to func as when it's invoked.

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

Arguments

func (Expression)
The function to attempt.
args (Any)
(Optional) The arguments to invoke func with.

Returns

(Any)
The func result or error object.

Examples

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

cond()

Iterates over predicate-function pairs and invokes the corresponding function of the first predicate to return truthy. The predicate and function expressions are invoked with one argument (value).

cond(value, [pair1 [, [pair1 [...]]])

Arguments

value (Any)
The input value.
pairs (Array)

The predicate-function pairs [predicate, function].

predicate (Expression | Array | Object | String) - an expression, if returns truthy the corresponding function is invoked. Optional for the last pair (default condition).
function (Expression | Array | Object | String) - The expression to be invoked.

Returns

(Any)
The result of the corresponding 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": 60,
"rain": true
}
cond(@,
[temp > 32, cond(@,
[rain, 'Bring an umbrella'],
['Don\'t bring an umbrella']
)
],
[temp <= 32, 'Wear awarm hat'],
['Stay home'] -- default value
)
"Bring an umbrella"

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

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"
}
}

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_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"]

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_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
[]
uuid_validate('not a UUID')
false
[]
uuid_validate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b')
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 RFC4122).

Examples

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

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
[]
dataurl_to_blob('data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E')
File()

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


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