Skip to main content

Pipes and Collections

The pipe operator |> with map, filter, reduce, groupBy, sortBy, and keyBy.

Source

examples/pipes-and-collections/main.rank
/// Demonstrates the pipe operator and stdlib collection functions:
/// map, filter, reduce, groupBy, sortBy, and keyBy.

use std::collections::{ map, filter, reduce, groupBy, sortBy, keyBy }
use std::object::{ mapValues }

Service = Object {
name: string,
team: string,
port: number,
replicas: number,
}

services: [Service] = [
{ name: `api`, team: `backend`, port: 8080, replicas: 3 },
{ name: `worker`, team: `backend`, port: 9090, replicas: 2 },
{ name: `web`, team: `frontend`, port: 3000, replicas: 4 },
{ name: `admin`, team: `frontend`, port: 7070, replicas: 1 },
]

active_services = services |> filter(|svc: Service| svc.replicas > 1)

named_services = services |> map(|svc: Service| `${svc.name}:${svc.team}`)

total_replicas = services |> reduce(0, |acc: number, svc: Service| acc + svc.replicas)

by_team = services |> groupBy(|svc: Service| svc.team)

by_name = services |> keyBy(|svc: Service| svc.name)

sorted_by_port = services |> sortBy(|svc: Service| svc.port)

replica_map = services
|> keyBy(|svc: Service| svc.name)
|> mapValues(|svc: Service, name: string| svc.replicas)

pub main = || {
active_services,
named_services,
total_replicas,
by_team,
by_name,
sorted_by_port,
replica_map,
}

Output

{
"active_services": [
{ "name": "api", "team": "backend", "port": 8080, "replicas": 3 },
{ "name": "worker", "team": "backend", "port": 9090, "replicas": 2 },
{ "name": "web", "team": "frontend", "port": 3000, "replicas": 4 }
],
"named_services": ["api:backend", "worker:backend", "web:frontend", "admin:frontend"],
"total_replicas": 10,
"by_team": {
"backend": [
{ "name": "api", "team": "backend", "port": 8080, "replicas": 3 },
{ "name": "worker", "team": "backend", "port": 9090, "replicas": 2 }
],
"frontend": [
{ "name": "web", "team": "frontend", "port": 3000, "replicas": 4 },
{ "name": "admin", "team": "frontend", "port": 7070, "replicas": 1 }
]
},
"sorted_by_port": [
{ "name": "web", "team": "frontend", "port": 3000, "replicas": 4 },
{ "name": "admin", "team": "frontend", "port": 7070, "replicas": 1 },
{ "name": "api", "team": "backend", "port": 8080, "replicas": 3 },
{ "name": "worker", "team": "backend", "port": 9090, "replicas": 2 }
],
"replica_map": { "api": 3, "worker": 2, "web": 4, "admin": 1 }
}

Key concepts

  • Pipe |>services |> filter(...) passes services as the first argument to filter. Chains read left-to-right.
  • groupBy — partitions a list into an object whose keys are the return values of the callback.
  • keyBy — like groupBy but asserts each key appears exactly once, returning an object of single values.
  • mapValues — transforms only the values of an object, leaving keys intact.
  • reduce — folds a list to a single value. The accumulator type is inferred from the initial argument.

Run it

rank examples/pipes-and-collections