shipping.cost
What does it cost to ship this parcel?
POST the call — JSON in, JSON out, pinned to this versionPAGE the same formula as one screen, for somebody who wants the answer
What it does
A rate card: a base price per zone, a price per kilo over the first two, a surcharge for express, and a free-shipping threshold on the order value that the express surcharge survives. Volumetric weight — the carrier charges for the space a light, bulky parcel takes — is the part people forget.
Call it
One request, JSON in, JSON out. Each example is filled in with the formula's own first case, so it answers as it stands.
curl
curl -X POST 'https://ofi.dev/@stdlib/shipping.cost@1.0.0/call' \ -H 'Content-Type: application/json' \ -d '{"weightKg":1.2,"lengthCm":20,"widthCm":15,"heightCm":10,"zone":"domestic","express":false,"orderValue":40}' # the same call as a URL, which is linkable and cacheable curl 'https://ofi.dev/@stdlib/shipping.cost@1.0.0/call?weightKg=1.2&lengthCm=20&widthCm=15&heightCm=10&zone=domestic&express=false&orderValue=40'
JavaScript
const response = await fetch('https://ofi.dev/@stdlib/shipping.cost@1.0.0/call', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "weightKg": 1.2, "lengthCm": 20, "widthCm": 15, "heightCm": 10, "zone": "domestic", "express": false, "orderValue": 40 }) }); const answer = await response.json(); if (!response.ok) throw new Error(answer.message); // 422 carries kind, path, field, label console.log(answer);
Python
import json, urllib.error, urllib.request request = urllib.request.Request( 'https://ofi.dev/@stdlib/shipping.cost@1.0.0/call', data=json.dumps({'weightKg': 1.2, 'lengthCm': 20, 'widthCm': 15, 'heightCm': 10, 'zone': "domestic", 'express': False, 'orderValue': 40}).encode(), headers={'Content-Type': 'application/json'}, ) try: with urllib.request.urlopen(request) as response: print(json.load(response)) except urllib.error.HTTPError as refusal: print(refusal.code, json.load(refusal))
Ruby
require 'json' require 'net/http' response = Net::HTTP.post( URI('https://ofi.dev/@stdlib/shipping.cost@1.0.0/call'), JSON.generate({ 'weightKg' => 1.2, 'lengthCm' => 20, 'widthCm' => 15, 'heightCm' => 10, 'zone' => "domestic", 'express' => false, 'orderValue' => 40 }), 'Content-Type' => 'application/json' ) answer = JSON.parse(response.body) raise answer['message'] unless response.code == '200' pp answer
A refusal comes back as 422, naming the field that caused it.
It proves itself7 / 7
7 cases, named in business language. The build does not produce this page unless every one of them passes, and the answers below are the compiled formula's rather than a transcription.
small domestic parcel
Try itweightKg 1.2lengthCm 20widthCm 15heightCm 10zone domesticexpress falseorderValue 40→cost 4.95billableWeight 1.2volumetric 0.6freeShipping falseetaDays 2heavy domestic parcel
Try itweightKg 8lengthCm 30widthCm 20heightCm 20zone domesticexpress falseorderValue 40→cost 9.75billableWeight 8volumetric 2.4freeShipping falseetaDays 2light but bulky, billed by volume
Try itweightKg 1lengthCm 60widthCm 40heightCm 40zone domesticexpress falseorderValue 40→cost 18.71billableWeight 19.2volumetric 19.2freeShipping falseetaDays 2European, express
Try itweightKg 3lengthCm 20widthCm 15heightCm 10zone euexpress trueorderValue 40→cost 17.33billableWeight 3volumetric 0.6freeShipping falseetaDays 1free shipping over the threshold
Try itweightKg 3lengthCm 20widthCm 15heightCm 10zone euexpress falseorderValue 200→cost 0billableWeight 3volumetric 0.6freeShipping trueetaDays 4free shipping still pays for express
Try itweightKg 3lengthCm 20widthCm 15heightCm 10zone euexpress trueorderValue 200→cost 5.78billableWeight 3volumetric 0.6freeShipping trueetaDays 1rest of the world
Try itweightKg 5lengthCm 20widthCm 15heightCm 10zone worldexpress falseorderValue 90→cost 37.55billableWeight 5volumetric 0.6freeShipping falseetaDays 9
What it refuses6 / 6
A refusal is correct behaviour, so it is specified too. Each of these raises the failure the bundle wrote down — try one and watch the message land on the field that caused it.
a parcel of no weight
Try itweightKg 0lengthCm 20widthCm 15heightCm 10zone domesticexpress falseorderValue 40→a parcel over the seventy kilos a carrier takes
Try itweightKg 100lengthCm 20widthCm 15heightCm 10zone domesticexpress falseorderValue 40→a zone nobody ships to
Try itweightKg 1.2lengthCm 20widthCm 15heightCm 10zone moonexpress falseorderValue 40→an order worth less than nothing
Try itweightKg 1.2lengthCm 20widthCm 15heightCm 10zone domesticexpress falseorderValue -5→express asked for with a word rather than a flag
Try itweightKg 1.2lengthCm 20widthCm 15heightCm 10zone domesticexpress yesorderValue 40→no zone at all
Try itweightKg 1.2lengthCm 20widthCm 15heightCm 10zone missingexpress falseorderValue 40→
The function
This is the whole of it. There is no other copy: the endpoint above runs this program, and the cases were run against its compilation during the build.
formula.elo
# What does it cost to ship this parcel?## A rate card: a base price per zone, a price per kilo over the first two, a# surcharge for express, and a free-shipping threshold on the order value that# the express surcharge survives. Volumetric weight — the carrier charges for# the space a light, bulky parcel takes — is the part people forget. let freeFrom = 150.0, baseOf = fn( zone ~> if zone == 'domestic' then 4.95 else if zone == 'eu' then 9.95 else 24.95 ), perKiloOf = fn( zone ~> if zone == 'domestic' then 0.80 else if zone == 'eu' then 1.60 else 4.20 ), shippingCost = fn( input ~> let # The carrier bills whichever is heavier: the scale, or the box. volumetric = input.lengthCm * input.widthCm * input.heightCm / 5000, billable = round(max(input.weightKg, volumetric), 1), overweight = max(0.0, billable - 2.0), base = baseOf(input.zone) + round(overweight * perKiloOf(input.zone), 2), freeShipping = input.orderValue >= freeFrom, surcharge = if input.express then round(base * 0.5, 2) else 0.0 in { cost: round((if freeShipping then 0.0 else base) + surcharge, 2), billableWeight: billable, volumetric: round(volumetric, 1), freeShipping: freeShipping, etaDays: if input.express then 1 else if input.zone == 'domestic' then 2 else if input.zone == 'eu' then 4 else 9 } )in { formula: shippingCost }
types.elo
Zone = String(z | known: z == 'domestic' || z == 'eu' || z == 'world') Input = { weightKg: Float(w | positive: w > 0 && w <= 70), lengthCm: Float(l | positive: l > 0), widthCm: Float(w | positive: w > 0), heightCm: Float(h | positive: h > 0), zone: Zone, express: Bool, orderValue: Float(v | notNegative: v >= 0)} Output = { cost: Float, billableWeight: Float, volumetric: Float, freeShipping: Bool, etaDays: Int}
Compiled · JavaScript
(function(_) { function kAdd(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.plus(r); if (Duration.isDuration(l) && DateTime.isDateTime(r)) return r.plus(l); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.plus(r); return l + r; } function kDiv(l, r) { if (Duration.isDuration(l) && typeof r === 'number') return Duration.fromMillis(l.toMillis() / r); return l / r; } function kEq(l, r) { if (Duration.isDuration(l) && Duration.isDuration(r)) return l.toMillis() === r.toMillis(); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return l.toMillis() === r.toMillis(); if (Array.isArray(l) && Array.isArray(r)) { if (l.length !== r.length) return false; for (let i = 0; i < l.length; i++) if (!kEq(l[i], r[i])) return false; return true; } if (typeof l === 'object' && typeof r === 'object' && l !== null && r !== null && !Array.isArray(l) && !Array.isArray(r)) { const keysL = Object.keys(l); const keysR = Object.keys(r); if (keysL.length !== keysR.length) return false; for (const key of keysL) if (!(key in r) || !kEq(l[key], r[key])) return false; return true; } return l == r; } function kMax2(a, b) { return a > b ? a : b; } function kMember(o, k) { if (o === null || typeof o !== 'object') return null; return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : null; } function kMul(l, r) { if (Array.isArray(l) || Array.isArray(r)) throw new Error("Array multiplication is not supported"); if (Duration.isDuration(l)) return Number.isInteger(r) ? l.mapUnits(u => u * r) : Duration.fromMillis(l.toMillis() * r); if (Duration.isDuration(r)) return Number.isInteger(l) ? r.mapUnits(u => u * l) : Duration.fromMillis(r.toMillis() * l); return l * r; } function kRound(x) { return x < 0 ? -Math.round(-x) : Math.round(x); } function kRoundTo(x, n) { const f = Math.pow(10, n); return kRound(x * f) / f; } function kSub(l, r) { if (DateTime.isDateTime(l) && Duration.isDuration(r)) return l.minus(r); if (DateTime.isDateTime(l) && DateTime.isDateTime(r)) return Duration.fromMillis(l.toMillis() - r.toMillis()); if (Duration.isDuration(l) && Duration.isDuration(r)) return l.minus(r); return l - r; } function pBool(v, p) { if (typeof v === 'boolean') return pOk(v, p); if (v === 'true') return pOk(true, p); if (v === 'false') return pOk(false, p); return pFail(p, 'expected Bool, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pFail(p, m, c, k, l) { return { success: false, path: p, message: m || '', value: null, cause: c || [], kind: k || 'schema', label: l }; } function pFloat(v, p) { if (typeof v === 'number') return pOk(v, p); if (typeof v === 'string' && /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(v.trim())) return pOk(parseFloat(v.trim()), p); return pFail(p, 'expected Float, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pInt(v, p) { if (typeof v === 'number' && Number.isInteger(v)) return pOk(v, p); if (typeof v === 'string' && /^[+-]?\d+$/.test(v.trim())) return pOk(parseInt(v.trim(), 10), p); return pFail(p, 'expected Int, got ' + (v === null ? 'Null' : typeof v === 'string' ? JSON.stringify(v) : typeof v)); } function pOk(v, p) { return { success: true, path: p, message: '', value: v, cause: [] }; } function pSchema(props, extrasMode, extrasParser) { const known = props.map(pr => pr[0]); return (v, p) => { if (typeof v !== 'object' || v === null || Array.isArray(v)) return pFail(p, 'expected object, got ' + (v === null ? 'Null' : typeof v)); const o = {}; for (const [key, parser, optional] of props) { if (optional && v[key] == null) continue; const r = parser(v[key], p + '.' + key); if (!r.success) return pFail(p, null, [Object.prototype.hasOwnProperty.call(v, key) ? r : { ...r, kind: 'missing' }]); o[key] = r.value; } if (extrasMode === 'closed') { for (const k in v) if (!known.includes(k)) return pFail(p + '.' + k, 'unexpected attribute'); } else if (extrasMode === 'typed' && extrasParser) { for (const k in v) { if (known.includes(k)) continue; const re = extrasParser(v[k], p + '.' + k); if (!re.success) return pFail(p, null, [re]); o[k] = re.value; } } return pOk(o, p); }; } function pString(v, p) { if (typeof v === 'string') return pOk(v, p); return pFail(p, 'expected String, got ' + (v === null ? 'Null' : typeof v)); } function pSubtype(baseParser, checks) { return (v, p) => { const r = baseParser(v, p); if (!r.success) return r; for (const [message, label, fn] of checks) { if (!fn(r.value)) return pFail(p, message, [], 'constraint', label); } return r; }; } function pUnwrap(r) { if (r.success) return r.value; function findError(e) { if (e.message) return e; if (e.cause && e.cause[0]) return findError(e.cause[0]); return e; } const err = findError(r); const e = new Error((err.path || '.') + ': ' + (err.message || 'type error')); e.kind = err.kind || 'schema'; e.path = err.path || '.'; if (err.label) e.label = err.label; throw e; } return (() => { const _module_0 = (() => { const freeFrom = 150.0; const baseOf = (zone) => ((kEq(zone, "domestic")) ? (4.95) : (((kEq(zone, "eu")) ? (9.95) : (24.95)))); const perKiloOf = (zone) => ((kEq(zone, "domestic")) ? (0.8) : (((kEq(zone, "eu")) ? (1.6) : (4.2)))); const shippingCost = (input) => (() => { const volumetric = kDiv(kMul(kMul(kMember(input, "lengthCm"), kMember(input, "widthCm")), kMember(input, "heightCm")), 5000); const billable = kRoundTo(kMax2(kMember(input, "weightKg"), volumetric), 1); const overweight = kMax2(0.0, kSub(billable, 2.0)); const base = kAdd(baseOf(kMember(input, "zone")), kRoundTo(kMul(overweight, perKiloOf(kMember(input, "zone"))), 2)); const freeShipping = kMember(input, "orderValue") >= freeFrom; const surcharge = ((kMember(input, "express")) ? (kRoundTo(kMul(base, 0.5), 2)) : (0.0)); return ({cost: kRoundTo(kAdd(((freeShipping) ? (0.0) : (base)), surcharge), 2), billableWeight: billable, volumetric: kRoundTo(volumetric, 1), freeShipping: freeShipping, etaDays: ((kMember(input, "express")) ? (1) : (((kEq(kMember(input, "zone"), "domestic")) ? (2) : (((kEq(kMember(input, "zone"), "eu")) ? (4) : (9))))))}); })(); return ({formula: shippingCost}); })(); const formula = kMember(_module_0, "formula"); return (() => { const _p_Input = pSchema([["weightKg", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (w) => w > 0 && w <= 70]]), false], ["lengthCm", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (l) => l > 0]]), false], ["widthCm", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (w) => w > 0]]), false], ["heightCm", pSubtype(pFloat, [["constraint 'positive' failed", "positive", (h) => h > 0]]), false], ["zone", pSubtype(pString, [["constraint 'known' failed", "known", (z) => kEq(z, "domestic") || kEq(z, "eu") || kEq(z, "world")]]), false], ["express", pBool, false], ["orderValue", pSubtype(pFloat, [["constraint 'notNegative' failed", "notNegative", (v) => v >= 0]]), false]], 'closed', null); const Input = (v) => pUnwrap(_p_Input(v, '')); const _p_Output = pSchema([["cost", pFloat, false], ["billableWeight", pFloat, false], ["volumetric", pFloat, false], ["freeShipping", pBool, false], ["etaDays", pInt, false]], 'closed', null); const Output = (v) => pUnwrap(_p_Output(v, '')); return Output(formula(Input(_))); })(); })(); })