Arrays
const names: string[] = ["Ada", "Linus"];
const first: string = names[0]; // "Ada"
const count: usize = names.length; // 2
let statuses: Array<i32> = [200, 201];
statuses[1] = 204; // [200, 204]
statuses.push(202); // [200, 204, 202]
const successful: boolean = statuses.includes(200); // true
const page: i32[] = statuses.slice(0, 2); // [200, 204]
const immutableReverse: i32[] = statuses.toReversed(); // [202, 204, 200]Ambas formas T[] y Array<T> son válidas. Las lecturas y escrituras indexadas realizan chequeos de límite en tiempo de ejecución. Los métodos mutantes requieren un receiver let. length informa la cantidad de elementos, mientras que capacity es una extensión de tyrus de solo lectura que expone el almacenamiento nativo reservado.
Literales de array y valores repetidos
El tipo [T; N] declara un array con exactamente N elementos. Inicialízalo con una lista que contenga exactamente N valores o con [valor; N] para repetir un valor. Los literales de array sin una anotación de tamaño fijo, como T[], siguen teniendo tamaño dinámico.
const repeated: [i32; 5] = [0; 5];
const values: [i32; 5] = [1, 2, 3, 4, 5];
print(repeated); // [0, 0, 0, 0, 0]
print(values); // [1, 2, 3, 4, 5]error
const most: [u8; 3] = [10, 20, 30, 40]; error[E0308]: fixed-length type requires 3 elements, but this initializer contains 4
at /src/main.tyr:1:23
const most: [u8; 3] = [10, 20, 30, 40];
^^^^^^^^^^^^^^^^
help: provide exactly 3 elements in this initializerArrays construidos por una secuencia de push
Un array local que empieza vacío y se llena con una secuencia directa de push se compila como el literal de array equivalente, lo que le permite vivir en el stack en vez del heap:
function build(seed: i32): i32[] {
let values: i32[] = [];
values.push(seed);
values.push(seed + 1);
values.push(seed + 2);
return values;
}La reescritura es exacta, mismos elementos, mismo orden, mismo tamaño, y el array sigue creciendo después. Solo se aplica mientras nada haya podido observar el array en el medio: la secuencia se detiene en el primer statement que no es un push sobre ese array, un elemento que lee el array en construcción nunca se mueve delante de él, y un elemento con spread descalifica la secuencia porque aporta un número desconocido de elementos. Los tipos de elemento se limitan a los copiados por valor.
Nada de esto es visible en el comportamiento, solo en cuánto asigna el programa. Hacer crecer un array de otro modo asigna incluso en una build de release, ya que el crecimiento es una llamada dentro de la cual el optimizador no puede mirar.
Chequeos de límite que un bucle ya probó
Toda lectura y escritura indexada se chequea en tiempo de ejecución, excepto donde un bucle alrededor ya probó que el chequeo no puede fallar. En la forma de conteo de abajo el cuerpo solo se alcanza cuando i < values.length, y nada entre esa prueba y el acceso al elemento puede cambiar ninguno de los dos lados, así que la comparación que el acceso emitiría es la condición del bucle escrita una segunda vez:
function sweep(values: i32[]): i32 {
let sum = 0;
for (let i: usize = 0; i < values.length; i += 1) {
sum += values[i];
}
return sum;
}La prueba es deliberadamente estrecha, porque equivocarse en ella quita lo único que hay entre un índice malo y una lectura fuera del buffer. Un bucle solo califica cuando el contador se declara en su propio init a partir de un literal no negativo, la condición es exactamente contador < array.length, la actualización solo aumenta el contador por una constante, el array es un local, un parámetro o un global const que nada puede hacer crecer y, dentro del cuerpo, el array nunca se usa para nada más que indexación y length, mientras el contador nunca se escribe. Cualquier otra cosa mantiene el chequeo: un push en el cuerpo, un índice distinto del contador, una redeclaración de cualquiera de los dos nombres o una mención a cualquiera de ellos desde dentro de una closure.
Un chequeo que se mantiene se comporta exactamente como siempre, nombrando el índice ofensor y el tamaño del array en stderr antes de terminar con status distinto de cero.
Chequeos de límite que una tabla fija ya probó
Un bucle no es lo único que puede resolver un índice. Cuando un binding se declara const a partir de un literal de array, su cantidad de elementos está escrita en el código, y un índice literal por debajo de esa cantidad está dentro del rango sin ningún bucle involucrado:
readonly const PRIMES: i32[] = [2, 3, 5, 7, 11, 13, 17, 19];
function third(): i32 {
return PRIMES[2];
}El chequeo de PRIMES[2] se elimina, y un índice más allá del final es un error de compilación en vez de uno de ejecución, PRIMES[8] se rechaza con E0606, nombrando el rango válido. Lo que fija el tamaño es el const, no la anotación: el binding no puede reasignarse, y un método mutante sobre él se rechaza. readonly const es como se escribe normalmente una tabla fija, pero un literal de array const simple prueba lo mismo.
El binding también tiene que ser solo leído y nada más. Pasarlo a una función, capturarlo en una closure o llamar cualquier método sobre él termina la prueba y el chequeo permanece, la misma regla estrecha que sigue la forma de bucle, y por el mismo motivo.
Los métodos mutables requieren let
Un array const es profundamente inmutable. Llamar a push, sort, reverse o a cualquier otro método mutable en un array const produce un error de compilación.
error
const fixed: i32[] = [1, 2, 3];
fixed.push(4); error[E0384]: cannot call mutating method `push` on immutable array `fixed`
at /src/main.tyr:3:1
fixed.push(4);
^^^^^
help: declare the binding with `let` to allow assignmentPropiedades
| Miembro | Tipo | Comportamiento |
|---|---|---|
length | usize | Cantidad actual de elementos. |
capacity | usize | Almacenamiento nativo reservado; es una extensión de Tyrus. |
Métodos mutables
Estos métodos modifican el array y, por eso, requieren un binding let mutable. pop() y shift() devuelven T?, así que un array vacío produce ausencia.
| Método | Firma | Comportamiento |
|---|---|---|
push | push(...items: T[]): usize | Añade valores al final y devuelve la nueva longitud. |
pop | pop(): T? | Elimina y devuelve el último valor, o ausencia. |
unshift | unshift(...items: T[]): usize | Añade valores al inicio y devuelve la nueva longitud. |
shift | shift(): T? | Elimina y devuelve el primer valor, o ausencia. |
splice | splice(start: i64, deleteCount?: i64, ...items: T[]): T[] | Elimina, reemplaza o inserta valores y devuelve los valores eliminados. |
sort, reverse, rotate, fill y copyWithin también modifican el receiver. Su comportamiento se explica en Métodos funcionales.
Métodos estáticos
| Método | Firma | Comportamiento |
|---|---|---|
Array.of | Array.of(...items: T[]): T[] | Crea un array con sus argumentos. |
Array.from | Array.from(items: T[]): T[] | Copia un array en un array de tamaño dinámico. |
Array.withCapacity | Array.withCapacity(capacity: usize): T[] | Crea un array vacío con capacidad reservada. |
Array.isArray | Array.isArray(value: unknown): boolean | Comprueba si un valor es un array. |
Métodos Funcionales
| Categoría | Métodos |
|---|---|
| Iteración & Transformación | map(), filter(), partition(), reduce(), reduceRight(), forEach() |
| Ventanas y Matrices | windows(), scan(), cartesianProduct(), zip(), transpose() |
| Deduplicación y Agrupación | unique(), uniqueBy(), groupBy() |
| Toggle | toggle(), toggleAll() |
| Búsqueda & Test | find(), findLast(), findIndex(), findLastIndex(), some(), every(), includes(), equals(), indexOf(), lastIndexOf() |
| Flatten & Reordenación | flat(), flatMap(), sort(), toSorted(), sortBy(), sortedBy(), reverse(), rotate(), toReversed(), random(), shuffle(), sample() |
| Corte | slice(), splitAt() |
| Agregación | sum(), product(), avg(), sumBy(), avgBy(), count(), concat(), join() |
| Mutación | splice(), fill(), copyWithin() |
| Acceso & Iteración | first(), last(), at(), keys(), values(), entries() |
| Copia Inmutable | with() |
Iteración & Transformación
Los métodos basados en predicados (filter, partition, some, every, find, findLast, findIndex, findLastIndex, uniqueBy y groupBy) aceptan una callback arrow explícita o una expresión implícita como value > 2; el tipo del elemento se infiere a partir del array receptor.
map()
Crea un nuevo array aplicando una transformación a cada elemento.
map<U>(callback: (element: T, index?: i64) => U): U[]const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: f64[] = prices.map(price => price * 1.08);
// [10.7892, 21.5892, 32.3892]error
const prices: f64[] = [9.99, 19.99, 29.99];
const withTax: string[] = prices.map(price => price * 1.08); error[E0308]: type mismatch for `withTax`: expected `string[]`, found `f64[]`
at /src/main.tyr:2:7
const withTax: string[] = prices.map(price => price * 1.08);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`filter()
Selecciona elementos que satisfacen un predicado.
filter(predicate: (element: T) => boolean): T[]const scores: i32[] = [85, 42, 91, 38, 76, 55];
const passing: i32[] = scores.filter(score => score >= 60);
// [85, 91, 76]error
const scores: i32[] = [85, 42, 91, 38, 76, 55];
const result: i32[] = scores.filter(score => score * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:46
const result: i32[] = scores.filter(score => score * 2);
^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`partition()
Separa los elementos en dos arrays estables según un predicado. El primer array contiene los elementos que coinciden; el segundo contiene los demás. El receiver no se modifica.
partition(predicate: (element: T) => boolean): [T[], T[]]partition(field: string): [T[], T[]]partition(field: string, ...values: string[]): [T[], T[]]const values: i32[] = [1, 2, 3, 4];
const [evenValues, oddValues] = values.partition(value % 2 === 0);
print(evenValues); // [2, 4]
print(oddValues); // [1, 3]
print(values); // [1, 2, 3, 4]Los arrays de objetos pueden usar directamente el nombre de un campo booleano, o un campo string seguido de uno o más valores coincidentes. Los nombres de los campos se verifican contra el tipo del elemento en tiempo de compilación.
interface Ticket {
title: string;
completed: boolean;
category: string;
}
const tickets: Ticket[] = [
{ title: "Plan", completed: true, category: "work" },
{ title: "Read", completed: false, category: "learning" },
{ title: "Review", completed: true, category: "work" },
{ title: "Archive", completed: false, category: "personal" }
];
const [completed, pending] = tickets.partition("completed");
print(completed); // [{ title: "Plan", completed: true, category: "work" }, { title: "Review", completed: true, category: "work" }]
print(pending); // [{ title: "Read", completed: false, category: "learning" }, { title: "Archive", completed: false, category: "personal" }]
const [focused, deferred] = tickets.partition("category", "work", "learning");
print(focused); // [{ title: "Plan", completed: true, category: "work" }, { title: "Read", completed: false, category: "learning" }, { title: "Review", completed: true, category: "work" }]
print(deferred); // [{ title: "Archive", completed: false, category: "personal" }]Un campo desconocido se rechaza en tiempo de compilación.
error
interface Ticket {
completed: boolean;
}
const tickets: Ticket[] = [{ completed: true }];
const [completed, pending] = tickets.partition("archived"); error[E0609]: `partition` key `archived` is not a field of `Ticket`
at /src/main.tyr:6:30
const [completed, pending] = tickets.partition("archived");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its typePara predicados más complejos, usa una arrow function explícita. Puede recibir el elemento, su índice y el array original:
const readings: i32[] = [1, 2, 3, 4, 5, 6, 7, 8];
const [selected, remaining] = readings.partition((reading, index) => {
return reading > 1 && index < 3;
});
print(selected); // [2, 3]
print(remaining); // [1, 4, 5, 6, 7, 8]
print(readings); // [1, 2, 3, 4, 5, 6, 7, 8]partition() evalúa el predicado una vez por elemento y conserva el orden original dentro de los dos arrays de salida. Al igual que count(), una expresión común con exactamente un identificador libre se trata como predicado implícito por elemento; una arrow function explícita sigue disponible para casos más complejos. Por seguridad de memoria, T debe ser Copy, string o un objeto cuyos campos son Copy o string.
reduce()
Acumula elementos en un único valor, de izquierda a derecha.
reduce<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst values: i32[] = [10, 20, 30, 40];
const total: i32 = values.reduce((sum, value) => sum + value, 0);
// 100error
const values: i32[] = [10, 20, 30, 40];
const total: i64 = values.reduce((sum, value) => sum + value, 0); error[E0308]: type mismatch for `total`: expected `i64`, found `i32`
at /src/main.tyr:2:7
const total: i64 = values.reduce((sum, value) => sum + value, 0);
^^^^^
help: `i32` does not convert to `i64` on its own; write the conversion explicitly with `as i64`reduceRight()
Acumula elementos en un único valor, de derecha a izquierda.
reduceRight<U>(callback: (accumulator: U, element: T) => U, initial: U): Uconst letters: string[] = ["a", "b", "c", "d"];
const reversed: string = letters.reduceRight(
(acc, letter) => acc + letter, "",
);
// "dcba"error
const letters: string[] = ["a", "b", "c", "d"];
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, ""); error[E0308]: type mismatch for `reversed`: expected `i64`, found `string`
at /src/main.tyr:2:7
const reversed: i64 = letters.reduceRight((acc, letter) => acc + letter, "");
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`forEach()
Ejecuta un callback para cada elemento. El valor de retorno se descarta.
forEach(callback: (element: T) => void): voidconst colors: string[] = ["red", "green", "blue"];
colors.forEach(color => print(color));
// red
// green
// blueerror
const colors: string[] = ["red", "green", "blue"];
colors.forEach((color: i32) => print(color)); error[E0308]: type mismatch for callback parameter `color` of `forEach`: expected `string`, found `i32`
at /src/main.tyr:2:24
colors.forEach((color: i32) => print(color));
^^^
help: change the callback parameter type to `string`Búsqueda & Test
find()
Devuelve el primer elemento que coincide con un predicado, o ausencia si ninguno coincide.
find(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string? = users.find(name => name.startsWith("G"));
// "Grace"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const match: string = users.find(name => name.startsWith("G")); error[E0003]: `match` is a reserved keyword in tyrus and cannot be used as an identifier
at /src/main.tyr:2:7
const match: string = users.find(name => name.startsWith("G"));
^^^^^
help: rename `match` to an identifier that is not a reserved keywordfindLast()
Devuelve el último elemento que coincide con un predicado, o ausencia si ninguno coincide.
findLast(predicate: (element: T) => boolean): T?const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string? = users.findLast(name => name.startsWith("G"));
// "Gordon"error
const users: string[] = ["Ada", "Grace", "Linus", "Gordon", "Margaret"];
const last: string = users.findLast(name => name.startsWith("G")); error[E0308]: type mismatch for `last`: expected `string`, found `string?`
at /src/main.tyr:2:7
const last: string = users.findLast(name => name.startsWith("G"));
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findIndex()
Devuelve el índice del primer elemento que coincide, o -1.
findIndex(predicate: (element: T) => boolean): i64const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item === "banana");
// 1error
const items: string[] = ["apple", "banana", "cherry"];
const index: i64 = items.findIndex(item => item.length); error[E0308]: type mismatch for `return`: expected `boolean`, found `usize`
at /src/main.tyr:2:44
const index: i64 = items.findIndex(item => item.length);
^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`findLastIndex()
Devuelve el índice del último elemento que coincide, o -1.
findLastIndex(predicate: (element: T) => boolean): i64const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n === 2);
// 3error
const duplicates: i32[] = [1, 2, 3, 4, 1];
const lastIdx: i64 = duplicates.findLastIndex(n => n); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:52
const lastIdx: i64 = duplicates.findLastIndex(n => n);
^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`some()
Comprueba si al menos un elemento satisface una condición.
some(predicate: (element: T) => boolean): booleanconst ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age < 18);
// trueerror
const ages: i32[] = [15, 22, 17, 30];
const hasMinor: boolean = ages.some(age => age * 2); error[E0308]: type mismatch for `return`: expected `boolean`, found `i32`
at /src/main.tyr:2:44
const hasMinor: boolean = ages.some(age => age * 2);
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`every()
Comprueba si todos los elementos satisfacen una condición.
every(predicate: (element: T) => boolean): booleanconst temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t >= 36.0 && t <= 37.5);
// trueerror
const temperatures: f64[] = [36.5, 37.0, 36.8];
const allNormal: boolean = temperatures.every(t => t + 1); error[E0369]: operator `+` cannot be applied to `f64` and `integer literal`
at /src/main.tyr:2:52
const allNormal: boolean = temperatures.every(t => t + 1);
^^^^^includes()
Comprueba si un valor específico existe en el array.
includes(value: T): booleanconst fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes("banana");
// trueerror
const fruits: string[] = ["apple", "banana", "cherry"];
const hasBanana: boolean = fruits.includes(42); error[E0308]: type mismatch for `includes`: expected `string`, found `integer literal`
at /src/main.tyr:2:28
const hasBanana: boolean = fruits.includes(42);
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`equals()
Compara dos arrays elemento a elemento: la misma longitud, los mismos elementos, en el mismo orden. === y !== no comparan arrays; el compilador informa E0369 y remite aquí.
equals(other: T[]): booleanconst left: i32[] = [1, 2, 3];
const right: i32[] = [1, 2, 3];
const same: boolean = left.equals(right);
// true
const reordered: boolean = left.equals([3, 2, 1]);
// falseerror
const grid: i32[][] = [[1], [2]];
const same: boolean = grid.equals([[1], [2]]); error[E0277]: array method `equals` compares arrays of numbers, `boolean`, `char` or `string`, but the elements are `i32[]`
at /src/main.tyr:2:23
const same: boolean = grid.equals([[1], [2]]);
^^^^^^^^^^^^^^^^^^^^^^^indexOf()
Devuelve el primer índice de un valor, o -1 si no se encuentra.
indexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf(2);
// 1error
const digits: i32[] = [1, 2, 3, 2, 1];
const first: i64 = digits.indexOf("2"); error[E0308]: type mismatch for `indexOf`: expected `i32`, found `string`
at /src/main.tyr:2:20
const first: i64 = digits.indexOf("2");
^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`lastIndexOf()
Devuelve el último índice de un valor, o -1 si no se encuentra.
lastIndexOf(value: T, fromIndex?: i64): i64const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf(2);
// 3error
const digits: i32[] = [1, 2, 3, 2, 1];
const last: i64 = digits.lastIndexOf("2"); error[E0308]: type mismatch for `lastIndexOf`: expected `i32`, found `string`
at /src/main.tyr:2:19
const last: i64 = digits.lastIndexOf("2");
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Ventanas, Acumulación y Matrices
windows()
windows(size) devuelve copias superpuestas de size elementos consecutivos. El receiver no cambia; windows(0) se rechaza y un tamaño mayor que el array devuelve un array vacío.
const readings: i32[] = [2, 4, 6, 8];
const windows: i32[][] = readings.windows(3); // [[2, 4, 6], [4, 6, 8]]
print(windows);scan()
scan(initial, callback) devuelve el acumulador inicial seguido por cada valor acumulado. La callback recibe el acumulador y el elemento actual, y el receiver no cambia.
const values: i32[] = [2, 3, 4];
const totals: i32[] = values.scan(0, (total, value) => total + value); // [0, 2, 5, 9]
print(totals);cartesianProduct()
cartesianProduct(other) devuelve pares en orden lexicográfico del receiver y del argumento. Cualquier entrada vacía produce un resultado vacío, y el receiver no cambia.
const left: i32[] = [1, 2];
const right: i32[] = [10, 20];
const pairs: [i32, i32][] = left.cartesianProduct(right); // [[1, 10], [1, 20], [2, 10], [2, 20]]
print(pairs);zip()
zip(other) intercala el receiver y el argumento en un array de pares (T, U)[], donde T es el tipo de elemento del receiver y U es el tipo de elemento del argumento. La longitud del resultado es igual a la de ambas entradas, que deben coincidir; los arrays de origen no cambian.
const names: string[] = ["ana", "bia"];
const scores: i32[] = [30, 25];
try {
const pairs: [string, i32][] = names.zip(scores); // [["ana", 30], ["bia", 25]]
print(pairs);
} catch (error: ZipError) {
print(error.code);
}Una diferencia de longitud lanza un ZipError recuperable (code ERR_ARRAY_ZIP_MISMATCH) en lugar de abortar, por lo que la llamada debe cubrirse con un catch o con una cláusula throws ZipError en la función que la contiene:
const names: string[] = ["ana", "bia"];
const scores: i32[] = [30];
try {
const pairs: [string, i32][] = names.zip(scores);
print(pairs.length);
} catch (error: ZipError) {
print(error.code); // ERR_ARRAY_ZIP_MISMATCH
}transpose()
transpose() convierte una matriz rectangular en columnas. Las matrices vacías y las matrices con filas de ancho cero devuelven arrays vacíos; las filas irregulares fallan antes de producir un resultado parcial.
const matrix: i32[][] = [[1, 2], [3, 4], [5, 6]];
const columns: i32[][] = matrix.transpose(); // [[1, 3, 5], [2, 4, 6]]
print(columns);unique()
unique() devuelve la primera aparición de cada valor distinto en el orden de entrada. No muta el receiver y usa la política nativa de igualdad para strings y números.
const values: i32[] = [3, 1, 3, 2, 1];
const distinct: i32[] = values.unique(); // [3, 1, 2]
print(distinct);uniqueBy()
uniqueBy(selector) conserva el primer elemento para cada clave hashable distinta. El selector puede ser el nombre de un campo para elementos objeto, una callback explícita o una expresión implícita, cuyo tipo de elemento se infiere automáticamente.
const values: i32[] = [1, 2, 3, 4, 5];
const oddAndEven: i32[] = values.uniqueBy(value => value % 2); // [1, 2]
const oddAndEvenImplicit: i32[] = values.uniqueBy(value % 2); // [1, 2]
print(oddAndEven);groupBy()
groupBy(selector) crea un mapa desde cada clave hashable hacia un array de elementos en su orden original. El selector puede ser el nombre de un campo para elementos objeto, una callback explícita o una expresión implícita, cuyo tipo de elemento se infiere automáticamente. La primera implementación exige elementos Copy para que cada grupo sea propietario de sus valores de forma segura.
const values: i32[] = [1, 2, 3, 4];
const groups: Map<i32, i32[]> = values.groupBy(value => value % 2); // { 1: [1, 3], 0: [2, 4] }
const groupsImplicit: Map<i32, i32[]> = values.groupBy(value % 2); // { 1: [1, 3], 0: [2, 4] }
print(groups.keys());Flatten & Reordenación
flat()
Aplana arrays anidados en un nivel.
flat(): T[]const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: i32[] = matrix.flat();
// [1, 2, 3, 4, 5]error
const matrix: i32[][] = [[1, 2], [3, 4], [5]];
const flat: string[] = matrix.flat(); error[E0308]: type mismatch for `flat`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const flat: string[] = matrix.flat();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`flatMap()
Mapea cada elemento a un array y aplana el resultado en un nivel.
flatMap<U>(callback: (element: T) => U[]): U[]const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence.split(" "));
// ["hello", "world", "goodbye", "moon"]error
const sentences: string[] = ["hello world", "goodbye moon"];
const words: string[] = sentences.flatMap(sentence => sentence); error[E0308]: `flatMap` callback must return an array, found `string`
at /src/main.tyr:2:25
const words: string[] = sentences.flatMap(sentence => sentence);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sort()
Ordena el array in place usando una función de comparación.
sort(compare?: (left: T, right: T) => i32): thislet numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left - right);
// [4, 8, 15, 23, 42]error
let numbers: i32[] = [42, 8, 15, 23, 4];
numbers.sort((left, right) => left < right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:31
numbers.sort((left, right) => left < right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`toSorted()
Devuelve una nueva copia ordenada sin mutar el original.
toSorted(compare?: (left: T, right: T) => i32): T[]const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left - right);
// [4, 8, 15, 23, 42]
// original is unchangederror
const original: i32[] = [42, 8, 15, 23, 4];
const sorted: i32[] = original.toSorted((left, right) => left > right); error[E0308]: type mismatch for `return`: expected `i32`, found `boolean`
at /src/main.tyr:2:58
const sorted: i32[] = original.toSorted((left, right) => left > right);
^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`sortBy()
Ordena un array in place por un campo resuelto estáticamente. La clave debe ser un literal string con el nombre de un campo numérico, booleano, de carácter o string. El segundo argumento es opcional: el orden predeterminado es ascendente y "desc" selecciona el orden descendente.
sortBy(key: keyof T, order?: "asc" | "desc"): thisinterface Score {
name: string;
points: i32;
}
let scores: Score[] = [
{ name: "Ada", points: 30 },
{ name: "Grace", points: 10 },
{ name: "Linus", points: 20 },
];
scores.sortBy("points"); // [{ name: "Grace", points: 10 }, { name: "Linus", points: 20 }, { name: "Ada", points: 30 }]
scores.sortBy("points", "desc"); // [{ name: "Ada", points: 30 }, { name: "Linus", points: 20 }, { name: "Grace", points: 10 }]El campo se resuelve en compile-time, por lo que el bucle de merge sort estable generado lo lee directamente sin reflexión en runtime. sortBy() requiere un receiver mutable en let y funciona en O(n log n) con O(n) de espacio auxiliar.
sortedBy()
Devuelve una copia ordenada por un campo resuelto estáticamente y deja el receiver sin cambios. El segundo argumento es opcional: el orden predeterminado es ascendente y "desc" selecciona el orden descendente. La primera versión requiere que los campos del elemento sean Copy, evitando una copia superficial insegura de valores poseídos. Usa merge sort estable O(n log n) con O(n) de espacio auxiliar.
sortedBy(key: keyof T, order?: "asc" | "desc"): T[]interface Coordinate {
x: i32;
y: i32;
}
const points: Coordinate[] = [
{ x: 3, y: 9 },
{ x: 1, y: 4 },
{ x: 2, y: 7 },
];
const byX: Coordinate[] = points.sortedBy("x"); // [{ x: 1, y: 4 }, { x: 2, y: 7 }, { x: 3, y: 9 }]
const byYDesc: Coordinate[] = points.sortedBy("y", "desc"); // [{ x: 3, y: 9 }, { x: 2, y: 7 }, { x: 1, y: 4 }]reverse()
Invierte el orden de los elementos in place.
reverse(): thislet stack: i32[] = [1, 2, 3];
stack.reverse();
// [3, 2, 1]error
const stack: i32[] = [1, 2, 3];
stack.reverse(); error[E0384]: cannot call mutating method `reverse` on immutable array `stack`
at /src/main.tyr:2:1
stack.reverse();
^^^^^
help: declare the binding with `let` to allow assignmentrotate()
Rota el array in place. Los valores positivos rotan hacia la izquierda; los negativos rotan hacia la derecha. El valor se normaliza por la longitud del array, y los arrays vacíos o de un solo elemento no cambian.
rotate(amount: i64): thislet values: i32[] = [1, 2, 3, 4, 5];
values.rotate(2); // [3, 4, 5, 1, 2]
values.rotate(-1); // [2, 3, 4, 5, 1]rotate() requiere un receiver mutable en let y se ejecuta en O(n) con espacio auxiliar O(1), sin asignar un segundo array.
toReversed()
Devuelve una nueva copia con orden invertido sin mutar el original.
toReversed(): T[]const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: string[] = days.toReversed();
// ["Wed", "Tue", "Mon"]
// days is unchangederror
const days: string[] = ["Mon", "Tue", "Wed"];
const reversed: i32[] = days.toReversed(); error[E0308]: type mismatch for `reversed`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const reversed: i32[] = days.toReversed();
^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`random()
Devuelve un T seleccionado uniformemente. Un array vacío aborta en runtime.
random(): Tconst fruits = ["grape", "banana", "orange", "strawberry"];
const chosen = fruits.random();
print(chosen); // "orange"error
const fruits: string[] = [];
const chosen = fruits.random(); error[E0606]: array.random requires at least 1 element(s), found 0
at /src/main.tyr:2:16
const chosen = fruits.random();
^^^^^^shuffle()
Devuelve un nuevo array mezclado uniformemente sin mutar el receptor. Los arrays con menos de dos elementos abortan en runtime.
shuffle(): T[]const fruits = ["grape", "banana", "orange", "strawberry"];
const shuffled = fruits.shuffle();
print(shuffled); // ["banana", "strawberry", "grape", "orange"]error
const value = [1];
const shuffled = value.shuffle(); error[E0606]: array.shuffle requires at least 2 element(s), found 1
at /src/main.tyr:2:18
const shuffled = value.shuffle();
^^^^^sample()
Devuelve un nuevo array con count elementos seleccionados uniformemente. count debe estar entre 1 y la longitud del receptor, inclusive. Sin opciones, las posiciones de origen no se repiten. { repeat: true } permite repeticiones de posiciones, pero no las garantiza.
sample(count: usize, options?: { repeat?: boolean }): T[]const teams = ["Arsenal", "Barcelona", "Bayern Munich", "Inter Milan"];
const distinct = teams.sample(2);
const independent = teams.sample(2, { repeat: true });
print(distinct); // ["Bayern Munich", "Barcelona"]
print(independent); // ["Inter Milan", "Inter Milan"]error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const none = teams.sample(0); error[E0606]: sample count 0 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:27
const none = teams.sample(0);
^error
const teams = ["Arsenal", "Barcelona", "Bayern Munich"];
const tooMany = teams.sample(4); error[E0606]: sample count 4 is out of bounds: valid counts are 1 to 3 (length 3)
at /src/main.tyr:2:30
const tooMany = teams.sample(4);
^Corte
slice()
Extrae una copia de un subarray contiguo.
slice(start?: i64, end?: i64): T[]const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: string[] = letters.slice(1, 4);
// ["b", "c", "d"]error
const letters: string[] = ["a", "b", "c", "d", "e"];
const middle: i32[] = letters.slice(1, 4); error[E0308]: type mismatch for `middle`: expected `i32[]`, found `string[]`
at /src/main.tyr:2:7
const middle: i32[] = letters.slice(1, 4);
^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Indexar con un Range es azúcar para .slice(): arr[a..b] es arr.slice(a, b), y toda forma abierta también funciona, arr[a..], arr[..b], arr[..=b] y el rango completo arr[..]. Igual que .slice(), esto siempre copia a un array nuevo; los arrays de tyrus todavía no tienen representación de slice prestado sin copia.
const letters: string[] = ["a", "b", "c", "d", "e"];
print(letters[1..4]);
// ["b", "c", "d"] same as letters.slice(1, 4)
print(letters[1..=3]);
// ["b", "c", "d"] inclusive of index 3
print(letters[2..]);
// ["c", "d", "e"]
print(letters[..3]);
// ["a", "b", "c"]
print(letters[..]);
// ["a", "b", "c", "d", "e"]splitAt()
Divide el array en dos arrays en un índice dado.
splitAt(index: i64): [T[], T[]]const letters: string[] = ["a", "b", "c", "d", "e"];
const parts: [string[], string[]] = letters.splitAt(2);
// [["a", "b"], ["c", "d", "e"]]error
const letters: string[] = ["a", "b"];
const parts: [string[], string[]] = letters.splitAt(10); error[E0606]: splitAt index 10 is out of bounds: valid indices are 0 to 2 (length 2)
at /src/main.tyr:2:53
const parts: [string[], string[]] = letters.splitAt(10);
^^splitAt siempre devuelve dos arrays comunes de tamaño dinámico ([T[], T[]]), incluso cuando se llama sobre un array de tamaño fijo. index puede ser igual a la longitud del array, produciendo una segunda mitad vacía, pero un índice mayor es un error de compilación cuando la longitud del array se conoce estáticamente, y un abort en tiempo de ejecución en caso contrario.
Agregación
count()
Devuelve la longitud, o cuenta ocurrencias de un valor o predicado.
count(value?: T | (element: T) => boolean): i64const numbers: i32[] = [1, 2, 3, 4, 5, 6];
print(numbers.count()); // 6
print(numbers.count(3)); // 1
print(numbers.count(value % 2 === 0)); // 3
print(numbers.count(value > 3)); // 3error
const numbers: i32[] = [1, 2, 3, 4, 5, 6];
const total: i64 = numbers.count(value => value.toString()); error[E0282]: cannot infer type of parameter `value`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^
error[E0599]: no method named `toString` for type `<inferred>`
at /src/main.tyr:2:43
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^
help: check the member name and the receiver type; hover the value to see its type
error[E0308]: `count` expects a value assignable to `i32`, found `(<inferred>) => void`
at /src/main.tyr:2:34
const total: i64 = numbers.count(value => value.toString());
^^^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`
error[E0308]: type mismatch for `total`: expected `i64`, found `usize`
at /src/main.tyr:2:7
const total: i64 = numbers.count(value => value.toString());
^^^^^
help: `usize` does not convert to `i64` on its own; write the conversion explicitly with `as i64`count() devuelve la longitud; count(valor) cuenta elementos iguales a valor; count(condición), una expresión común que referencia exactamente un identificador todavía no declarado en el ámbito actual, se convierte en una condición implícita por elemento, azúcar para count((implicitParam): boolean => condición) sin necesidad de escribir ninguna arrow function. Un identificador que ya resuelve en el ámbito no es libre, así que la expresión se comprueba como una llamada común count(valor), comparar su resultado (constante) boolean contra el tipo del elemento es un error de compilación que cita el identificador que ensombreció el parámetro implícito. Una expresión que referencia más de un identificador no declarado también es un error de compilación, ya que el azúcar solo introduce un parámetro implícito.
sum()
Devuelve la suma de todos los elementos numéricos usando el tipo de los elementos del array. Un array numérico vacío devuelve el valor cero de ese tipo.
sum(): Tconst values: i32[] = [2, 3, 4];
const total = values.sum(); // inferred as i32
print(total); // 9
const empty: i32[] = [];
print(empty.sum()); // 0sum() se rechaza para tipos de elemento no numéricos y se compila como un bucle nativo directo, sin callback ni despacho al runtime por elemento.
product()
Devuelve el producto de todos los elementos numéricos usando el tipo de los elementos del array. Un array numérico vacío devuelve el valor uno de ese tipo.
product(): Tconst values: i32[] = [2, 3, 4];
const product = values.product(); // inferred as i32
print(product); // 24
const empty: i32[] = [];
print(empty.product()); // 1product() sigue las mismas reglas de tipo numérico y bucle nativo que sum().
avg()
Devuelve el promedio aritmético de los elementos numéricos. Los arrays de enteros, f32 y f64 devuelven f64?; los arrays de f128 devuelven f128?. Un array vacío produce ausencia.
avg(): f64? | f128?const values: i32[] = [2, 3, 4];
const average = values.avg(); // inferred as f64?
print(average ?? 0.0); // 3.0
const empty: i32[] = [];
print(empty.avg() ?? 0.0); // 0.0El resultado opcional debe tratarse con ??, narrowing u otra operación válida de opcionales antes del uso numérico directo.
sumBy()
Retorna la suma de un campo numérico en todos los elementos. La clave debe ser un literal de string que nombre un campo numérico.
sumBy(key: string): T[K]interface Item {
name: string;
quantity: i32;
price: f64;
}
const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const totalQuantity = items.sumBy("quantity"); // 4 (i32)
const totalPrice = items.sumBy("price"); // 124.99 (f64)avgBy()
Retorna el promedio aritmético de un campo numérico en todos los elementos. La clave debe ser un literal de string que nombre un campo numérico. Siempre retorna f64? (o f128? para campos f128).
avgBy(key: string): f64? | f128?const items: Item[] = [
{ name: "Widget", quantity: 3, price: 25.0 },
{ name: "Gadget", quantity: 1, price: 99.99 }
];
const avgPrice = items.avgBy("price"); // 62.495 (f64?)concat()
Fusiona dos arrays en uno nuevo.
concat(...items: (T | T[])[]): T[]const front: i32[] = [1, 2];
const back: i32[] = [3, 4];
const merged: i32[] = front.concat(back);
// [1, 2, 3, 4]error
const front: string[] = ["a", "b"];
const merged: string[] = front.concat(42); error[E0308]: type mismatch for `concat`: expected `string[]`, found `integer literal`
at /src/main.tyr:2:26
const merged: string[] = front.concat(42);
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`join()
Une todos los elementos en una sola cadena usando un separador.
join(separator: string): stringconst parts: string[] = ["tyrus", "is", "native"];
const sentence: string = parts.join(" ");
// "tyrus is native"error
const numbers: i32[] = [1, 2, 3];
const text: string = numbers.join(", "); error[E0277]: `join` currently requires a `string[]` receiver
at /src/main.tyr:2:22
const text: string = numbers.join(", ");
^^^^^^^^^^^^^^^^^^Mutación
splice()
Elimina, reemplaza o inserta elementos in place.
splice(start: i64, deleteCount?: i64, ...items: T[]): T[]let values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8);
print(values[1]);
print(removed[0]);error
const values: i32[] = [1, 2, 3, 4];
const removed: i32[] = values.splice(1, 2, 7, 8); error[E0384]: cannot call mutating method `splice` on immutable array `values`
at /src/main.tyr:2:24
const removed: i32[] = values.splice(1, 2, 7, 8);
^^^^^^
help: declare the binding with `let` to allow assignmentsplice(start, deleteCount?, ...items) modifica el receptor y devuelve un nuevo array con los elementos eliminados. Los índices iniciales negativos cuentan desde el final, la eliminación se limita al intervalo disponible y los valores insertados deben coincidir con el tipo de los elementos del array.
fill()
Reemplaza todos los elementos con un valor fijo.
fill(value: T): thislet buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill(7);
// [7, 7, 7, 7, 7]error
let buffer: i32[] = [0, 0, 0, 0, 0];
buffer.fill("x"); error[E0308]: type mismatch for `fill`: expected `i32`, found `string`
at /src/main.tyr:2:1
buffer.fill("x");
^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`copyWithin()
Copia una sección contigua del array a otra posición en el mismo array.
copyWithin(target: i64, start: i64, end?: i64): thislet data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin(0, 3);
// [4, 5, 3, 4, 5]error
let data: i32[] = [1, 2, 3, 4, 5];
data.copyWithin("x", 3); error[E0308]: type mismatch for `copyWithin`: expected `i64`, found `string`
at /src/main.tyr:2:1
data.copyWithin("x", 3);
^^^^^^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Acceso & Iteración
first()
Devuelve el primer elemento como T?. Un array vacío produce ausencia. La anotación de tipo es opcional: cuando values es i32[], tyrus infiere i32? automáticamente. Optional<i32> es la forma explícita equivalente.
first(): T?const values: i32[] = [10, 20, 30];
const firstValue = values.first(); // inferred as i32?
const explicitFirst: Optional<i32> = values.first();
if (firstValue) {
print(firstValue + 1); // 11
}
const firstOrDefault: i32 = firstValue ?? 0;
print(firstOrDefault);
const empty: i32[] = [];
print(empty.first() ?? -1); // -1T? es intencional: first() devuelve un valor, no una colección, y sigue siendo O(1) sin asignar un array vacío como resultado. El uso directo como i32 se rechaza hasta que un if, ??, ternario, optional chaining u otra operación válida de narrowing trate la ausencia.
last()
Devuelve el último elemento como T?. Un array vacío produce ausencia, y tyrus infiere automáticamente el tipo opcional del elemento cuando se omite la anotación.
last(): T?const values: i32[] = [10, 20, 30];
const lastValue = values.last(); // inferred as i32?
const explicitLast: Optional<i32> = values.last();
const lastOrDefault: i32 = lastValue ? lastValue : 0;
print(lastOrDefault);
const empty: i32[] = [];
print(empty.last() ?? -1); // -1last() sigue las mismas reglas de ausencia y narrowing que first(), leyendo el elemento final en O(1) sin asignar un array de resultado.
at()
Devuelve el elemento en un índice, soportando indexación negativa desde el final.
at(index: i64): Tconst main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at(-1);
print(last ?? "none"); // blue
};error
const main = (): void => {
const colors: string[] = ["red", "green", "blue"];
const last: string? = colors.at("x");
};error[E0308]: type mismatch for `at`: expected `i64`, found `string`
at /src/main.tyr:3:27
const last: string? = colors.at("x"); // [!code error]
^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`keys()
Devuelve un iterador sobre los índices del array.
keys(): Iterable<i64>const items: string[] = ["x", "y", "z"];
for (const index of items.keys()) {
print(index); // 0, 1, 2
}error
const items: string[] = ["x", "y", "z"];
const keys: i64[] = items.keys(); error[E0308]: type mismatch for `keys`: expected `i64[]`, found `usize[]`
at /src/main.tyr:2:7
const keys: i64[] = items.keys();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`values()
Devuelve un iterador sobre los valores del array.
values(): Iterable<T>const items: i32[] = [10, 20, 30];
let total: i32 = 0;
for (const value of items.values()) {
total += value;
}
print(total); // 60error
const items: i32[] = [10, 20, 30];
const vals: string[] = items.values(); error[E0308]: type mismatch for `vals`: expected `string[]`, found `i32[]`
at /src/main.tyr:2:7
const vals: string[] = items.values();
^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`entries()
Devuelve un iterador sobre pares índice-valor.
entries(): Iterable<[i64, T]>const fruits: string[] = ["apple", "banana", "cherry"];
for (const [index, fruit] of fruits.entries()) {
print(`${index}: ${fruit}`);
// 0: apple
// 1: banana
// 2: cherry
}error
const fruits: string[] = ["apple", "banana", "cherry"];
const entries: [i64, string][] = fruits.entries(); error[E0308]: type mismatch for `entries`: expected `[i64, string][]`, found `[usize, string][]`
at /src/main.tyr:2:7
const entries: [i64, string][] = fruits.entries();
^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Copia Inmutable
with()
Devuelve un nuevo array con un único elemento reemplazado en un índice dado.
with(index: i64, value: T): T[]const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, "yellow");
// ["red", "yellow", "blue"]
// colors is unchangederror
const colors: string[] = ["red", "green", "blue"];
const updated: string[] = colors.with(1, 42); error[E0308]: type mismatch for `with`: expected `string`, found `integer literal`
at /src/main.tyr:2:27
const updated: string[] = colors.with(1, 42);
^^^^^^^^^^^^^^^^^^
help: change the value or the annotation so their types match; convert numbers explicitly with `value as <type>`Toggle
toggle()
Agrega un elemento al array si no está presente y lo elimina si está presente, devolviendo un array nuevo y sin mutar nunca el receptor.
toggle(item: T): T[]toggle(item: T, key: string): T[]const values: i32[] = [1, 2, 3];
print(values.toggle(4)); // [1, 2, 3, 4]
print(values.toggle(2)); // [1, 3]
print(values); // [1, 2, 3]Cuando se proporciona un nombre de campo key, la comparación se hace por ese campo en lugar de por el elemento completo. El campo debe existir en el tipo del elemento.
interface Pet {
name: string;
age: i32;
}
const pets: Pet[] = [
{ name: "rex", age: 2 },
{ name: "mia", age: 5 },
];
const adopted: Pet[] = pets.toggle({ name: "rex", age: 99 }, "name");
print(adopted.length); // 1toggleAll()
Aplica el mismo comportamiento de agregar o eliminar a cada elemento del array argumento, preservando el orden. No muta nada.
toggleAll(items: T[]): T[]const values: i32[] = [1, 2, 3];
print(values.toggleAll([2, 4])); // [1, 3, 4]Encadenamiento
Los métodos funcionales se encadenan en pipelines de datos legibles:
interface Product {
name: string;
price: f64;
inStock: boolean;
}
const products: Product[] = [
{ name: "Keyboard", price: 79.99, inStock: true },
{ name: "Mouse", price: 29.99, inStock: false },
{ name: "Monitor", price: 349.99, inStock: true },
{ name: "Headset", price: 59.99, inStock: true },
];
const availableNames: string[] = products
.filter(product => product.inStock)
.map(product => product.name);
// ["Keyboard", "Monitor", "Headset"]
const totalRevenue: f64 = products
.filter(product => product.inStock)
.reduce((sum, product) => sum + product.price, 0.0);
// 489.97