KScript docs
EN

map fields and methods

Maps such as { name: 'Joan', age: 82 }.

A map holds values under names, called keys: { name: 'Ada', age: 36 }. Read a value with a dot, $person.name, or with brackets when the key is in a variable or has a space in it, $person['home town']. Keys are text and keep the order you wrote them in.

Map methods never change the map they are called on. A method such as ->set() or ->remove() gives a new map, so you keep the result or chain the next method onto it:

<let name="stock" value="{ apples: 3 }" />
<let name="more" value="$stock->set('pears', 5)" />
<echo value="$stock->count()" /> <!-- 1 because ->set() gives a new map and leaves this one alone -->
<echo value="$more->count()" /> <!-- 2 because the new map has apples and pears -->
$stock = { apples: 3 }
$more = $stock->set('pears', 5)
echo $stock->count()   // 1 because ->set() gives a new map and leaves this one alone
echo $more->count()    // 2 because the new map has apples and pears

Methods that take a function call it once for each entry. The function gets the value first and, if you ask for it, the key second: fn(count) => ... or fn(count, fruit) => .... ->map_keys() is the one exception, since it is about keys: it passes the key first. Where you only want a field or a method of each value, write it with a dot instead of a whole function: ->filter(.is_active) is ->filter(fn(user) => $user.is_active).

Find out about a map: count · is_empty · has · get · any · all · find

Take it apart: keys · values · entries

Keep some entries: filter · reject · pick · omit

Change it: set · remove · merge · deep_merge · map · map_keys · sort

Combine into one value: reduce

A field is a plain fact about the value, read with a dot and no brackets: $value.name. A method takes arguments or does work, and is called with ->: $value->name(arguments), or with the value piped in: $value |> name(arguments).

From KScript.Core

#map->all(fn(value, key?)) → bool

True when fn(value, key) is true for every entry.

->all(fn(value, key?)) is true when the function is true for every entry. It stops at the first entry that fails. An empty map gives true, because no entry fails:

<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<echo value="$stock->all(fn(count) => $count >= 0)" /> <!-- true because no count is below zero -->
<echo value="$stock->all(fn(count) => $count > 0)" /> <!-- false because there are no pears left -->
<echo value="{}->all(fn(count) => $count > 0)" /> <!-- true because there is no entry to fail -->
$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->all(fn(count) => $count >= 0)   // true because no count is below zero
echo $stock->all(fn(count) => $count > 0)    // false because there are no pears left
echo {}->all(fn(count) => $count > 0)        // true because there is no entry to fail
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 0 }->all(fn(n) => $n > 0) }</echo>
echo { apples: 3, pears: 0 }->all(fn(n) => $n > 0)

#map->any(fn(value, key?)) → bool

True when fn(value, key) is true for any entry.

->any(fn(value, key?)) is true when the function is true for at least one entry. It stops at the first entry that passes:

<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<echo value="$stock->any(fn(count) => $count == 0)" /> <!-- true because pears have run out -->
<echo value="$stock->any(fn(count, fruit) => $fruit == 'kiwis')" /> <!-- false because there is no kiwis key -->
$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->any(fn(count) => $count == 0)                // true because pears have run out
echo $stock->any(fn(count, fruit) => $fruit == 'kiwis')   // false because there is no kiwis key
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 0 }->any(fn(n) => $n == 0) }</echo>
echo { apples: 3, pears: 0 }->any(fn(n) => $n == 0)

#map->count() → number

The number of keys.

->count() is how many keys the map has. A key whose value is null still counts, because the key is there:

<echo value="{ apples: 3, pears: 0 }->count()" /> <!-- 2 because there are two keys -->
<echo value="{ name: 'Ada', nickname: null }->count()" /> <!-- 2 because nickname is a key, even with no value -->
<echo value="{}->count()" /> <!-- 0 -->
echo { apples: 3, pears: 0 }->count()          // 2 because there are two keys
echo { name: 'Ada', nickname: null }->count()  // 2 because nickname is a key, even with no value
echo {}->count()                               // 0
Example
<echo>{ { a: 1, b: 2 }->count() }</echo>
echo { a: 1, b: 2 }->count()

#map->deep_merge(other: map) → map

Recursively merges maps. The right value replaces lists, nulls, and other leaves.

->deep_merge(other) adds another map's keys, as ->merge() does, but goes inside maps that both have under the same key and merges those too. Anything that isn't a map on both sides, such as a list, a number or null, is replaced by the other map's value. It suits settings, where a small override changes one setting deep inside without losing the rest:

<let name="defaults" value="{ theme: { colour: 'blue', size: 12 }, tags: ['news'] }" />
<let name="mine" value="{ theme: { size: 14 }, tags: ['sport'] }" />
<let name="settings" value="$defaults->deep_merge($mine)" />
<echo value="$settings.theme" /> <!-- { colour: 'blue', size: 14 } because both themes are maps, so only size changes -->
<echo value="$settings.tags" /> <!-- ['sport'] because lists aren't merged: the new list replaces the old one -->
<echo value="$defaults->merge($mine).theme" /> <!-- { size: 14 } because ->merge() replaces the whole theme -->
$defaults = { theme: { colour: 'blue', size: 12 }, tags: ['news'] }
$mine = { theme: { size: 14 }, tags: ['sport'] }
$settings = $defaults->deep_merge($mine)
echo $settings.theme   // { colour: 'blue', size: 14 } because both themes are maps, so only size changes
echo $settings.tags    // ['sport'] because lists aren't merged: the new list replaces the old one
echo $defaults->merge($mine).theme   // { size: 14 } because ->merge() replaces the whole theme
ParameterTakes
other requiredmap
Example
<echo>{ { nav: { order: 1 } }->deep_merge({ nav: { label: 'Home' } }) }</echo>
echo { nav: { order: 1 } }->deep_merge({ nav: { label: 'Home' } })

#map->entries() → list

The entries, as a list of { key, value } maps.

->entries() turns the map into a list of { key, value } maps, in order. Use it when you need list methods that a map doesn't have, such as ->take() or ->join():

<let name="prices" value="{ tea: 2, cake: 3 }" />
<echo value="$prices->entries()" /> <!-- [{ key: 'tea', value: 2 }, { key: 'cake', value: 3 }] -->
<let name="menu" value="$prices->entries()->map(fn(entry) => &quot;{ $entry.key }: £{ $entry.value }&quot;)" />
<echo value="$menu->join(', ')" /> <!-- 'tea: £2, cake: £3' -->
$prices = { tea: 2, cake: 3 }
echo $prices->entries()   // [{ key: 'tea', value: 2 }, { key: 'cake', value: 3 }]
$menu = $prices->entries()->map(fn(entry) => "{ $entry.key }: £{ $entry.value }")
echo $menu->join(', ')    // 'tea: £2, cake: £3'
Example
<echo>{ { a: 1, b: 2 }->entries() }</echo>
echo { a: 1, b: 2 }->entries()

#map->filter(fn(value, key?)) → map

The entries for which fn(value, key) is true.

->filter(fn(value, key?)) keeps the entries for which the function is true, in their order. ->reject() keeps the others:

<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<echo value="$stock->filter(fn(count) => $count > 0)" /> <!-- { apples: 3, plums: 2 } because pears are at 0 -->
<echo value="$stock->filter(fn(count, fruit) => $fruit->starts_with('p'))" /> <!-- { pears: 0, plums: 2 } because the key is checked this time -->
$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->filter(fn(count) => $count > 0)                     // { apples: 3, plums: 2 } because pears are at 0
echo $stock->filter(fn(count, fruit) => $fruit->starts_with('p')) // { pears: 0, plums: 2 } because the key is checked this time
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 0, plums: 2 }->filter(fn(n) => $n > 0) }</echo>
echo { apples: 3, pears: 0, plums: 2 }->filter(fn(n) => $n > 0)

#map->find(fn(value, key?)) → map

The first entry for which fn(value, key) is true, as { key, value }, or null.

->find(fn(value, key?)) gives the first entry for which the function is true, as a { key, value } map, so you know which key it was. It gives null when no entry passes:

<let name="stock" value="{ apples: 3, pears: 0, plums: 0 }" />
<echo value="$stock->find(fn(count) => $count == 0)" /> <!-- { key: 'pears', value: 0 } because pears come before plums -->
<echo value="$stock->find(fn(count) => $count == 0).key" /> <!-- 'pears' -->
<echo value="$stock->find(fn(count) => $count > 10)" /> <!-- null because nothing has more than 10 -->
$stock = { apples: 3, pears: 0, plums: 0 }
echo $stock->find(fn(count) => $count == 0)       // { key: 'pears', value: 0 } because pears come before plums
echo $stock->find(fn(count) => $count == 0).key   // 'pears'
echo $stock->find(fn(count) => $count > 10)       // null because nothing has more than 10
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 0 }->find(fn(n) => $n == 0).key }</echo>
echo { apples: 3, pears: 0 }->find(fn(n) => $n == 0).key

#map->get(key, default?) → any

The value for a key, or the default.

->get(key, default?) reads the value for a key, or gives the default when the key isn't there (null if you give none). Use it for a key held in a variable, or where a missing key is normal:

<let name="person" value="{ name: 'Ada', age: 36 }" />
<echo value="$person->get('name')" /> <!-- 'Ada' -->
<echo value="$person->get('town', 'Leeds')" /> <!-- 'Leeds' because there is no town key -->
<echo value="$person->get('town')" /> <!-- null because there is no town key and no default -->
$person = { name: 'Ada', age: 36 }
echo $person->get('name')           // 'Ada'
echo $person->get('town', 'Leeds')  // 'Leeds' because there is no town key
echo $person->get('town')           // null because there is no town key and no default

Arguments can be named: ->get(…, default: …).

Example
<echo>{ { name: 'Joan' }->get('age', 0) }</echo>
echo { name: 'Joan' }->get('age', 0)

#map->has(key) → bool

True when the key exists.

->has(key) is true when the map has the key, even if its value is null. Keys match exactly, so capital letters count:

<let name="person" value="{ name: 'Ada', nickname: null }" />
<echo value="$person->has('name')" /> <!-- true -->
<echo value="$person->has('nickname')" /> <!-- true because the key is there, even with no value -->
<echo value="$person->has('Name')" /> <!-- false because keys match exactly, and this one is name -->
$person = { name: 'Ada', nickname: null }
echo $person->has('name')      // true
echo $person->has('nickname')  // true because the key is there, even with no value
echo $person->has('Name')      // false because keys match exactly, and this one is name
Example
<echo>{ { name: 'Joan' }->has('age') }</echo>
echo { name: 'Joan' }->has('age')

#map->is_empty() → bool

True when the map has no keys.

->is_empty() is true when the map has no keys at all:

<echo value="{}->is_empty()" /> <!-- true -->
<echo value="{ cart: [] }->is_empty()" /> <!-- false because the map has a key, even though its list is empty -->
echo {}->is_empty()            // true
echo { cart: [] }->is_empty()  // false because the map has a key, even though its list is empty
Example
<echo>{ {}->is_empty() }</echo>
echo {}->is_empty()

#map->keys() → list

The keys, as a list.

->keys() gives the keys as a list, in order:

<let name="scores" value="{ ada: 12, bo: 9 }" />
<echo value="$scores->keys()" /> <!-- ['ada', 'bo'] -->
<echo value="$scores->keys()->join(' and ')" /> <!-- 'ada and bo' -->
$scores = { ada: 12, bo: 9 }
echo $scores->keys()                // ['ada', 'bo']
echo $scores->keys()->join(' and ') // 'ada and bo'
Example
<echo>{ { name: 'Joan', age: 82 }->keys() }</echo>
echo { name: 'Joan', age: 82 }->keys()

#map->map(fn(value, key?)) → map

A new map with fn(value, key) applied to each value.

->map(fn(value, key?)) gives a map with the same keys and each value replaced by what the function gives. ->map_keys() changes the keys instead:

<let name="prices" value="{ tea: 2, cake: 3 }" />
<echo value="$prices->map(fn(price) => $price * 2)" /> <!-- { tea: 4, cake: 6 } because each price is doubled -->
<echo value="$prices->map(fn(price, item) => &quot;{ $item } £{ $price }&quot;)" /> <!-- { tea: 'tea £2', cake: 'cake £3' } because the key is passed second -->
$prices = { tea: 2, cake: 3 }
echo $prices->map(fn(price) => $price * 2)                // { tea: 4, cake: 6 } because each price is doubled
echo $prices->map(fn(price, item) => "{ $item } £{ $price }") // { tea: 'tea £2', cake: 'cake £3' } because the key is passed second
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 5 }->map(fn(n) => $n * 2) }</echo>
echo { apples: 3, pears: 5 }->map(fn(n) => $n * 2)

#map->map_keys(fn(key, value?)) → map

A new map with each key replaced by fn(key, value). A later entry wins when two get the same key.

->map_keys(fn(key, value?)) gives a map with each key replaced by what the function gives, and the values left alone. The key comes first here, since the keys are what you are changing. When two keys turn into the same key, the later entry wins:

<let name="form" value="{ first_name: 'Ada', last_name: 'Lovelace' }" />
<echo value="$form->map_keys(fn(key) => $key->case(camel))" /> <!-- { firstName: 'Ada', lastName: 'Lovelace' } -->
<echo value="{ a: 1, A: 2 }->map_keys(fn(key) => $key->lower())" /> <!-- { a: 2 } because both keys become a, and the later one wins -->
$form = { first_name: 'Ada', last_name: 'Lovelace' }
echo $form->map_keys(fn(key) => $key->case(camel))   // { firstName: 'Ada', lastName: 'Lovelace' }
echo { a: 1, A: 2 }->map_keys(fn(key) => $key->lower()) // { a: 2 } because both keys become a, and the later one wins
ParameterTakes
fn requiredfn
Example
<echo>{ { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) }</echo>
echo { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel))

#map->merge(other) → map

A new map with other's keys added or replaced.

->merge(other) adds another map's keys to this one. Where both maps have a key, the other map's value wins. Keys keep their first place, and new keys go on the end. Maps inside are replaced whole; ->deep_merge() merges them too:

<let name="defaults" value="{ port: 80, host: 'localhost' }" />
<echo value="$defaults->merge({ port: 8080 })" /> <!-- { port: 8080, host: 'localhost' } because the new port replaces 80 -->
<echo value="$defaults->merge({ secure: true })" /> <!-- { port: 80, host: 'localhost', secure: true } because secure is new, so it goes last -->
$defaults = { port: 80, host: 'localhost' }
echo $defaults->merge({ port: 8080 })      // { port: 8080, host: 'localhost' } because the new port replaces 80
echo $defaults->merge({ secure: true })    // { port: 80, host: 'localhost', secure: true } because secure is new, so it goes last
Example
<echo>{ { port: 80, host: 'localhost' }->merge({ port: 8080 }) }</echo>
echo { port: 80, host: 'localhost' }->merge({ port: 8080 })

#map->omit(keys: Self.fields[]) → map

A copy without the given keys, in the original map's order.

->omit(keys) gives a copy without the listed keys. Keys the map doesn't have are ignored. ->pick() does the opposite. The editor offers the map's own keys inside the brackets:

<let name="user" value="{ name: 'Ada', email: 'ada@example.com', password: 'secret' }" />
<echo value="$user->omit([password])" /> <!-- { name: 'Ada', email: 'ada@example.com' } because the password is left out -->
<echo value="$user->omit([password, phone])" /> <!-- { name: 'Ada', email: 'ada@example.com' } because there was no phone to leave out -->
$user = { name: 'Ada', email: 'ada@example.com', password: 'secret' }
echo $user->omit([password])          // { name: 'Ada', email: 'ada@example.com' } because the password is left out
echo $user->omit([password, phone])   // { name: 'Ada', email: 'ada@example.com' } because there was no phone to leave out
ParameterTakes
keys requiredSelf.fields[]
Example
<echo>{ { name: 'Ada', active: true }->omit(['active']) }</echo>
echo { name: 'Ada', active: true }->omit(['active'])

#map->pick(keys: Self.fields[]) → map

A copy containing only the given keys, in the original map's order.

->pick(keys) gives a copy with only the listed keys, in the map's own order rather than the order you list them. Keys the map doesn't have are ignored:

<let name="user" value="{ name: 'Ada', email: 'ada@example.com', password: 'secret' }" />
<echo value="$user->pick([email, name])" /> <!-- { name: 'Ada', email: 'ada@example.com' } because the map's own order is kept -->
<echo value="$user->pick([name, phone])" /> <!-- { name: 'Ada' } because there is no phone to pick -->
$user = { name: 'Ada', email: 'ada@example.com', password: 'secret' }
echo $user->pick([email, name])   // { name: 'Ada', email: 'ada@example.com' } because the map's own order is kept
echo $user->pick([name, phone])   // { name: 'Ada' } because there is no phone to pick
ParameterTakes
keys requiredSelf.fields[]
Example
<echo>{ { name: 'Ada', active: true }->pick(['name']) }</echo>
echo { name: 'Ada', active: true }->pick(['name'])

#map->reduce(fn(total, value, key?), initial?) → any

Combines the entries into one value: fn(total, value, key) gives the next total, starting from initial. Without initial, the first value is the first total, as a list's ->reduce() does; an empty map then gives null.

->reduce(fn(total, value, key?), initial?) walks through the entries in order, building up one value. The function gets the total so far and the next value, and gives the new total. Without initial, the first value is the first total, and an empty map gives null:

<let name="basket" value="{ apples: 3, pears: 5, plums: 2 }" />
<echo value="$basket->reduce(fn(total, count) => $total + $count)" /> <!-- 10 because 3 + 5 is 8, then 8 + 2 is 10 -->
<echo value="$basket->reduce(fn(total, count) => $total + $count, 100)" /> <!-- 110 because the total starts at 100 -->
<echo value="$basket->reduce(fn(list, count, fruit) => &quot;{ $list } { $fruit }&quot;, 'Bought:')" /> <!-- 'Bought: apples pears plums' -->
$basket = { apples: 3, pears: 5, plums: 2 }
echo $basket->reduce(fn(total, count) => $total + $count)       // 10 because 3 + 5 is 8, then 8 + 2 is 10
echo $basket->reduce(fn(total, count) => $total + $count, 100)  // 110 because the total starts at 100
echo $basket->reduce(fn(list, count, fruit) => "{ $list } { $fruit }", 'Bought:') // 'Bought: apples pears plums'
ParameterTakes
fn requiredfn
initial optionalany value

Arguments can be named: ->reduce(…, initial: …).

Example
<echo>{ { apples: 3, pears: 5 }->reduce(fn(total, n) => $total + $n, 0) }</echo>
echo { apples: 3, pears: 5 }->reduce(fn(total, n) => $total + $n, 0)

#map->reject(fn(value, key?)) → map

The entries for which fn(value, key) is false.

->reject(fn(value, key?)) drops the entries for which the function is true and keeps the rest. It is ->filter() the other way round:

<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<echo value="$stock->reject(fn(count) => $count == 0)" /> <!-- { apples: 3, plums: 2 } because pears are at 0 -->
$stock = { apples: 3, pears: 0, plums: 2 }
echo $stock->reject(fn(count) => $count == 0)   // { apples: 3, plums: 2 } because pears are at 0
ParameterTakes
fn requiredfn
Example
<echo>{ { apples: 3, pears: 0, plums: 2 }->reject(fn(n) => $n > 0) }</echo>
echo { apples: 3, pears: 0, plums: 2 }->reject(fn(n) => $n > 0)

#map->remove(key) → map

A new map without the key.

->remove(key) gives a copy without one key. A key the map doesn't have is no error; you just get the same entries back:

<let name="person" value="{ name: 'Ada', age: 36 }" />
<echo value="$person->remove('age')" /> <!-- { name: 'Ada' } -->
<echo value="$person->remove('town')" /> <!-- { name: 'Ada', age: 36 } because there was no town to remove -->
$person = { name: 'Ada', age: 36 }
echo $person->remove('age')    // { name: 'Ada' }
echo $person->remove('town')   // { name: 'Ada', age: 36 } because there was no town to remove
Example
<echo>{ { name: 'Joan', age: 82 }->remove('age') }</echo>
echo { name: 'Joan', age: 82 }->remove('age')

#map->set(key, value) → map

A new map with the key set.

->set(key, value) gives a copy with the key set to the value. An existing key keeps its place, and a new key goes on the end:

<let name="person" value="{ name: 'Ada', age: 36 }" />
<echo value="$person->set('age', 37)" /> <!-- { name: 'Ada', age: 37 } because age keeps its place -->
<echo value="$person->set('town', 'Leeds')" /> <!-- { name: 'Ada', age: 36, town: 'Leeds' } because town is new, so it goes last -->
$person = { name: 'Ada', age: 36 }
echo $person->set('age', 37)        // { name: 'Ada', age: 37 } because age keeps its place
echo $person->set('town', 'Leeds')  // { name: 'Ada', age: 36, town: 'Leeds' } because town is new, so it goes last

Arguments can be named: ->set(…, value: …).

Example
<echo>{ { name: 'Joan' }->set('age', 82) }</echo>
echo { name: 'Joan' }->set('age', 82)

#map->sort(by: fn(value, key?), order?: asc|desc) → map

A copy with its entries sorted by by: fn(value, key), as a list's ->sort(by:) is; order: desc puts the largest first.

->sort(by: fn(value, key?), order?: asc|desc) gives a copy with the entries in a new order, sorted by what by gives for each one, smallest first. order: desc puts the largest first. To sort by key, have by give the key:

<let name="votes" value="{ tea: 5, coffee: 9, juice: 2 }" />
<echo value="$votes->sort(by: fn(count) => $count)" /> <!-- { juice: 2, tea: 5, coffee: 9 } because 2 is the fewest votes -->
<echo value="$votes->sort(by: fn(count) => $count, order: desc)->keys()->first()" /> <!-- 'coffee' because it has the most votes -->
<echo value="$votes->sort(by: fn(count, drink) => $drink)->keys()" /> <!-- ['coffee', 'juice', 'tea'] because the keys are in alphabetical order -->
$votes = { tea: 5, coffee: 9, juice: 2 }
echo $votes->sort(by: fn(count) => $count)                // { juice: 2, tea: 5, coffee: 9 } because 2 is the fewest votes
echo $votes->sort(by: fn(count) => $count, order: desc)->keys()->first() // 'coffee' because it has the most votes
echo $votes->sort(by: fn(count, drink) => $drink)->keys() // ['coffee', 'juice', 'tea'] because the keys are in alphabetical order
ParameterTakes
by requiredfn
order optionalone of these words: asc|desc

Arguments can be named: ->sort(…, order: …).

Example
<echo>{ { pears: 5, apples: 3, plums: 9 }->sort(by: fn(n) => $n, order: desc)->keys() }</echo>
echo { pears: 5, apples: 3, plums: 9 }->sort(by: fn(n) => $n, order: desc)->keys()

#map->values() → list

The values, as a list.

->values() gives the values as a list, in order, so you can use list methods such as ->sum():

<let name="basket" value="{ apples: 3, pears: 5 }" />
<echo value="$basket->values()" /> <!-- [3, 5] -->
<echo value="$basket->values()->sum()" /> <!-- 8 because 3 + 5 is 8 -->
$basket = { apples: 3, pears: 5 }
echo $basket->values()          // [3, 5]
echo $basket->values()->sum()   // 8 because 3 + 5 is 8
Example
<echo>{ { name: 'Joan', age: 82 }->values() }</echo>
echo { name: 'Joan', age: 82 }->values()

Methods from any