Built-in native functions
All of these work with or without the ton. prefix (see Language basics).
Core
| Function | Description |
|---|---|
print(x) | Prints a value to stdout |
type(x) | Returns the type name of a value as a string |
str(x) | Converts a value to string |
num(x) | Converts a value to number (0 if it can't be parsed) |
format(template, ...args) | Replaces each {} in template with the matching argument (see String formatting) |
json(x) | Converts a value (array, dict, or scalar) to a JSON string |
assert(cond, [msg]) | Throws (catchable) if cond is falsy |
input([prompt]) | Prints an optional prompt, reads and returns one line from stdin |
readfile(path) | Reads a file's content as ton.html (resolved relative to the script's directory too) |
writefile(path, content) | Writes (overwriting) a file with content; returns whether it succeeded |
Math
| Function | Description |
|---|---|
sqrt(x), pow(x, y), abs(x) | Square root, power, absolute value |
floor(x), ceil(x), round(x) | Rounding |
min(...), max(...) | Smallest/largest of any number of arguments |
random() | A float in [0, 1) |
random(max) | An integer in [0, max) |
random(min, max) | An integer in [min, max) |
Strings
| Function | Description |
|---|---|
len(s) | Length |
upper(s), lower(s) | Case conversion |
trim(s) | Strips leading/trailing whitespace |
split(s, sep) | Splits into a ton.array of strings |
join(arr, sep) | Joins an array into a string (see also under Arrays) |
replace(s, search, repl) | Replaces every occurrence of search with repl |
substring(s, start, [length]) | Extracts a substring |
contains(s, sub) | Whether sub occurs in s |
indexOf(s, sub) | Index of the first occurrence, or -1 |
s[i] | The character at index i, as a 1-character string (read-only — see Arrays) |
Arrays
| Function | Description |
|---|---|
len(arr) | Number of elements |
push(arr, v) | Appends a value (mutates in place) |
pop(arr) | Removes and returns the last element |
shift(arr) | Removes and returns the first element |
unshift(arr, v) | Inserts a value at the front |
slice(arr, start, [end]) | Returns a new sub-array |
join(arr, sep) | Joins elements into a string |
sort(arr) | Sorts in place (numeric or alphabetical) and returns it |
reverse(arr) | Reverses in place and returns it |
contains(arr, item) | Whether item is an element (structural equality) |
indexOf(arr, item) | Index of the first matching element, or -1 |
map(arr, fn) | New array of fn(element) for each element |
filter(arr, fn) | New array keeping only elements where fn(element) is truthy |
reduce(arr, fn, initial) | Folds the array via fn(accumulator, element) |
find(arr, fn) | First element where fn(element) is truthy, or nil |
any(arr, fn) | true if fn(element) is truthy for at least one element |
all(arr, fn) | true if fn(element) is truthy for every element |
Dicts
| Function | Description |
|---|---|
len(d) | Number of keys |
keys(d) | Array of keys, in insertion order |
values(d) | Array of values, in insertion order |
has(d, key) | Whether key exists |
json(d) | JSON-encodes the dict |
HTTP server
| Function | Description |
|---|---|
get(path, fn) | Registers a GET route (see Local server) |
post(path, fn) | Registers a POST route |
serve(port) / serve(port, content) | Starts the local HTTP server |
Added in beta-2.0.0 — every one of them can also be called with method syntax (arr.sum(), s.padStart(3, "0")).
Conversions & misc
| Function | Description |
|---|---|
int(x, [base]) | Integer part of a number, or parse a string (int("ff", 16) is 255) |
float(x) | Parse a string as a number (errors on garbage, unlike num) |
bool(x) | true/false according to truthiness |
fixed(x, [digits=2]) | Number to string with a fixed number of decimals |
round(x, [digits]) | Rounds, optionally to some decimals |
repr(x) | Like str, but strings come back quoted |
isinstance(obj, Class) | Whether obj is an instance of Class or of a subclass |
copy(x) / deepcopy(x) | Shallow / recursive copy of an array, dict or object |
clamp(x, lo, hi), sign(x) | Number helpers |
exit([code]) | Stops the script immediately |
print(a, b, ...) | print is also a function value, printing its arguments separated by spaces |
Arrays
| Function | Description |
|---|---|
range(end), range(start, end, [step]) | Array of numbers, end excluded |
sum(arr), avg(arr) | Sum / mean of numbers |
min(arr), max(arr) | min/max also accept a single array |
sorted(arr, [key]) | Sorted copy; key(x) gives what to sort by: sorted(words, w => len(w)) |
sort(arr, [compare]) | In place; compare(a, b) returns a negative number (or true) when a comes first |
forEach(arr, fn) | Calls fn(item) (or fn(item, index)) for each element |
findIndex(arr, fn) | Index of the first match, or -1 |
count(arr, valueOrFn) | How many elements equal a value / match a predicate (also counts substrings) |
flatMap(arr, fn) | map then flatten one level |
unique(arr) | Copy without duplicates (first occurrence kept) |
flatten(arr, [depth=1]) | Flattens nested arrays |
zip(a, b, ...) | [[a0, b0], [a1, b1], ...] |
enumerate(arr) | [[0, a0], [1, a1], ...] |
chunk(arr, size) | Splits into arrays of size elements |
groupBy(arr, fn) | Dict of arrays, grouped by fn(item) |
first(arr), last(arr) | First / last element, or nil |
insert(arr, index, value), removeAt(arr, index) | Insert / remove at a position |
remove(arr, value) | Removes the first equal element; remove(dict, key) removes a key |
clear(x), isEmpty(x) | Empty an array/dict; test emptiness |
lastIndexOf(x, item) | Last position in an array or string, or -1 |
reduce(arr, fn) | Without an initial value, starts from the first element |
Dicts
| Function | Description |
|---|---|
items(d) | [[key, value], ...] |
dict(pairs) | Builds a dict from [[key, value], ...] |
merge(a, b, ...) | New dict, later keys win |
keys, values, items, has and len also work on objects (their fields).
Strings
| Function | Description |
|---|---|
startsWith(s, p), endsWith(s, p) | Prefix / suffix test |
padStart(s, width, [fill]), padEnd(...) | Pad to a width |
repeat(s, n) | Repeat a string (or an array) |
chars(s), lines(s) | Split into characters / lines |
capitalize(s) | First letter in upper case |
reverse(s) | reverse now also reverses a string |
ord(c), chr(n) | Character code and back |