Prism · Composition
Calculated fields
Derived fields from raw input: the lines of a cart become a subtotal, tax and total. $with names the subtotal once, and $round fixes the digits.
{
items: [
{ name: 'Widget', price: 9.99, qty: 3 },
{ name: 'Gadget', price: 19.5, qty: 2 },
{ name: 'Sprocket', price: 4.25, qty: 5 },
],
taxRate: 0.08,
}{
$with: {
let: {
subtotal: {
$sum: {
over: {
$map: {
over: { $ref: '$.items' },
as: 'item',
body: {
$mul: [
{ $get: { from: { $var: 'item' }, path: ['price'] } },
{ $get: { from: { $var: 'item' }, path: ['qty'] } },
],
},
},
},
},
},
},
value: {
subtotal: { $round: { value: { $var: 'subtotal' }, digits: 2 } },
tax: {
$round: {
value: { $mul: [{ $var: 'subtotal' }, { $ref: '$.taxRate' }] },
digits: 2,
},
},
total: {
$round: {
value: {
$add: [
{ $var: 'subtotal' },
{ $mul: [{ $var: 'subtotal' }, { $ref: '$.taxRate' }] },
],
},
digits: 2,
},
},
itemCount: { $count: { over: { $ref: '$.items' } } },
},
},
}{
subtotal: 90.22,
tax: 7.22,
total: 97.44,
itemCount: 3,
}Runs in this page on the installed package. The input and the expected output are defined by the example.