Prism · guide

Lists

A list filtered, sorted, mapped and added up, each a step you can read.

Install it
pnpm add @niscorp/prism @niscorp/strata zod
Step 1 of 3

Three bookings

A night at the box office: three bookings, each with a member and a number of seats.

Three bookings
import { evaluate } from '@niscorp/prism';

const night = {
  bookings: [
    { member: 'Linus', seats: 4 },
    { member: 'Ada', seats: 1 },
    { member: 'Grace', seats: 2 },
  ],
};
Step 2 of 3

Filter, then sort

An operator over a list names each element with as, and reads it as a variable. $var is the element, and $get reaches into it.

Operators nest: the list $sortBy sorts is the one $filter let through.

Filter, then sort
const seatsOf = { $get: { from: { $var: 'booking' }, path: ['seats'] } };
const parties = {
  $sortBy: {
    over: { $filter: { over: { $ref: '$.bookings' }, as: 'booking', when: { $gte: [seatsOf, { $const: 2 }] } } },
    as: 'booking',
    by: seatsOf,
    dir: 'desc',
  },
};
console.log(evaluate(parties, night));
Step 3 of 3

Map, and add up

$map makes a new list of an old one. $pluck and $sum are sugar for the two commonest cases: one field of every element, and the total of a list.

Map, and add up
const memberOf = { $get: { from: { $var: 'booking' }, path: ['member'] } };
const door = {
  names: { $map: { over: { $ref: '$.bookings' }, as: 'booking', body: { $upper: memberOf } } },
  seats: { $sum: { over: { $pluck: { over: { $ref: '$.bookings' }, key: 'seats' } } } },
};
console.log(evaluate(door, night));
Then

Run it.

The parties of two or more, the largest first, and then every name in capitals with the seats added up.

Run it
npx tsx lists.mts
It prints
[ { member: 'Linus', seats: 4 }, { member: 'Grace', seats: 2 } ]
{ names: [ 'LINUS', 'ADA', 'GRACE' ], seats: 7 }