Comparison with native code
Eight typical tasks. Each has two tabs: the ActiveModel solution and the same behavior written by hand in plain TypeScript. The native versions are working code, shown in full, so you can compare both the size and the number of places where mistakes are easy to make.
1. Money without rounding errors
Requirement: a price in USD, addition, 7.5% tax, a split into three payments without losing a cent.
import { ActiveModel } from '@alt-point/active-models/ActiveModel'
import { ActiveField } from '@alt-point/active-models/decorators'
import { Money } from '@alt-point/active-models/scalars/Money'
class Order extends ActiveModel {
@ActiveField({ coerce: Money, min: Money.of(0, 'USD') })
total: Money = Money.of(0, 'USD')
}
const order = Order.create({ total: '19.99 USD' })
order.total = order.total.multiply(3) // 59.97 USD
const withTax = order.total.multiply('1.075') // 64.47 USD (half-even)
withTax.allocate([1, 1, 1]).map(String) // ['21.49 USD', '21.49 USD', '21.49 USD']
order.total = '5 EUR' // ValidationError: currency does not match the min bound
JSON.stringify(order) // {"total":{"amount":"59.97","currency":"USD"}}// Floating-point numbers: 0.1 + 0.2 !== 0.3, so store whole cents.
type Money = { cents: number, currency: string }
const usd = (cents: number): Money => ({ cents, currency: 'USD' })
function assertSame (a: Money, b: Money) {
if (a.currency !== b.currency) throw new TypeError(`Currency mismatch: ${a.currency} and ${b.currency}`)
}
function multiply (m: Money, factor: number): Money {
// factor * cents is a float too: 1999 * 1.075 = 2149.2249999999997
return usd(Math.round(m.cents * factor)) // half-up; banker's rounding must be written by hand
}
function allocate (m: Money, ratios: number[]): Money[] {
const total = ratios.reduce((a, b) => a + b, 0)
if (ratios.length === 0 || total === 0 || ratios.some((r) => r < 0)) throw new RangeError('bad ratios')
const shares = ratios.map((r) => Math.floor((m.cents * r) / total))
let rest = m.cents - shares.reduce((a, b) => a + b, 0)
for (let i = 0; rest > 0; i = (i + 1) % shares.length) {
if (ratios[i] > 0) { shares[i]++; rest-- }
}
return shares.map(usd) // negative amounts and currencies with 0/3 decimals are extra work
}
const order = { total: usd(0) }
function setTotal (next: Money) {
assertSame(next, order.total)
if (next.cents < 0) throw new RangeError('total must be >= 0')
order.total = next // every write must go through the function: order.total = ... bypasses the checks
}
const toJSON = (m: Money) => ({ amount: (m.cents / 100).toFixed(2), currency: m.currency })
// parsing '19.99 USD' -> cents is yet another function; JSON.stringify(order) yields {"total":{"cents":...}}Money stores the amount as a Decimal on BigInt: the result does not depend on Number, currency decimal places (JPY — 0, KWD — 3) are respected, and JSON.stringify yields strings with no loss of precision.
2. Form: normalization, type coercion, validation
Requirement: e-mail lowercased and trimmed, age arrives as a string, errors are collected in full.
import { ActiveModel } from '@alt-point/active-models/ActiveModel'
import { ActiveField } from '@alt-point/active-models/decorators'
import { ValidationError } from '@alt-point/active-models/pipeline'
class Signup extends ActiveModel {
@ActiveField({ trim: true, lowercase: true, required: true, pattern: /^[^@\s]+@[^@\s]+$/ })
email: string = ''
@ActiveField({ coerce: 'integer', min: 18, max: 120 })
age: number = 0
}
const form = Signup.create({ email: ' Ann@Example.COM ', age: '32' })
form.email // 'ann@example.com'
form.age // 32
form.age = 'abc' // ValidationError: "age" cannot be converted to integer
form.age = 10 // ValidationError: "age" must be at least 18
Signup.create({ email: 'x' }) // ValidationError: data passed to create() goes through the same rules
const { valid, issues } = Signup.create({}).validate() // fields with default values are validated too
// valid: false; issues: [{ path: 'email', code: 'required' }, { path: 'age', code: 'min' }]type Issue = { path: string, message: string }
type Signup = { email: string, age: number }
function normalize (input: { email?: unknown, age?: unknown }): Signup {
return {
email: typeof input.email === 'string' ? input.email.trim().toLowerCase() : '',
age: typeof input.age === 'string' && input.age.trim() !== '' ? Number(input.age) : (input.age as number) ?? 0,
}
}
function validate (form: Signup): Issue[] {
const issues: Issue[] = []
if (!/^[^@\s]+@[^@\s]+$/.test(form.email)) issues.push({ path: 'email', message: 'invalid email' })
if (!Number.isInteger(form.age)) issues.push({ path: 'age', message: 'must be an integer' })
else if (form.age < 18) issues.push({ path: 'age', message: 'must be at least 18' })
else if (form.age > 120) issues.push({ path: 'age', message: 'must be at most 120' })
return issues
}
// Coercion and validation live apart from the data: the assignment form.age = 'abc' checks nothing.
const form = normalize({ email: ' Ann@Example.COM ', age: '32' })
const issues = validate(form)
if (issues.length) throw Object.assign(new Error('invalid'), { issues })
function update<K extends keyof Signup> (key: K, value: unknown) {
const next = normalize({ ...form, [key]: value }) // the whole form would have to be renormalized
const problems = validate(next)
if (problems.length) throw Object.assign(new Error('invalid'), { issues: problems })
Object.assign(form, next)
}3. Unsaved changes and rollback
Requirement: show "there are unsaved edits", a list of differences, rollback of a single field and of the whole form.
class Profile extends ActiveModel {
@ActiveField() name: string = ''
@ActiveField() bio: string = ''
}
const profile = Profile.create(saved, { tracked: true })
profile.name = 'Bob'
profile.isTouched() // true
profile.changes() // { name: { from: 'Ann', to: 'Bob' } }
profile.dirtyFields() // ['name']
profile.revert('name') // reverted one field
profile.reset() // reverted everything
profile.name = 'Ann'
profile.isTouched() // false: compared by value, not by "was the field written to"import isEqual from 'lodash/isEqual'
type Profile = { name: string, bio: string }
function createForm (saved: Profile) {
const baseline = structuredClone(saved)
const current = structuredClone(saved)
return {
current,
isTouched: () => !isEqual(current, baseline),
changes: () => {
const result: Record<string, { from: unknown, to: unknown }> = {}
for (const key of Object.keys(baseline) as Array<keyof Profile>) {
if (!isEqual(current[key], baseline[key])) result[key] = { from: baseline[key], to: current[key] }
}
return result
},
revert: (key: keyof Profile) => { current[key] = baseline[key] },
reset: () => Object.assign(current, structuredClone(baseline)),
}
}
// UI reactivity (Vue: reactive + computed, React: useState + useMemo) is added separately;
// nested objects in baseline and current must be deep-cloned, otherwise they share references.4. Undo / redo
const doc = Doc.create({ title: 'A' }, { history: { limit: 50 } })
doc.title = 'B'
doc.title = 'C'
doc.undo() // 'B'
doc.undo() // 'A'
doc.redo() // 'B'
doc.canUndo() // true
doc.transaction((d) => { d.title = 'X'; d.body = 'Y' })
doc.undo() // one entry undoes the whole transactiontype Snapshot = { title: string, body: string }
class DocHistory {
private undoStack: Snapshot[] = []
private redoStack: Snapshot[] = []
constructor (private state: Snapshot, private limit = 50) {}
set<K extends keyof Snapshot> (key: K, value: Snapshot[K]) {
if (this.state[key] === value) return
this.push()
this.state = { ...this.state, [key]: value }
this.redoStack = []
}
batch (change: (state: Snapshot) => Snapshot) {
this.push()
this.state = change({ ...this.state })
this.redoStack = []
}
undo () {
const previous = this.undoStack.pop()
if (!previous) return
this.redoStack.push(this.state)
this.state = previous
}
redo () {
const next = this.redoStack.pop()
if (!next) return
this.undoStack.push(this.state)
this.state = next
}
private push () {
this.undoStack.push(this.state)
if (this.undoStack.length > this.limit) this.undoStack.shift()
}
}
// Writing to state directly, bypassing set(), skips the history; nested structures require deep copying.5. Transaction with an invariant
Requirement: a trip changes both dates; the end is not before the start; on violation nothing stays modified.
class Trip extends ActiveModel {
@ActiveField({ coerce: 'date' }) start?: Date
@ActiveField({ coerce: 'date' }) end?: Date
@InvariantMethod('end must not be before start')
static endAfterStart (trip: Trip) {
return !trip.start || !trip.end || trip.end >= trip.start
}
}
const trip = Trip.create({ start: '2026-01-01', end: '2026-01-05' })
trip.transaction((t) => {
t.start = '2026-03-01' // the invariant is not checked between writes
t.end = '2026-03-10'
}) // checked on exit; on violation both fields are rolled backtype Trip = { start: Date, end: Date }
function updateTrip (trip: Trip, change: (draft: Trip) => void): Trip {
const draft: Trip = { start: new Date(trip.start), end: new Date(trip.end) } // deep copy
change(draft)
if (draft.end < draft.start) throw new RangeError('end must not be before start')
return draft // the caller must swap the reference
}
let trip: Trip = { start: new Date('2026-01-01'), end: new Date('2026-01-05') }
trip = updateTrip(trip, (d) => {
d.start = new Date('2026-03-01')
d.end = new Date('2026-03-10')
})
// The copy is made by hand, async code inside change() needs separate handling,
// and a direct write trip.end = ... still bypasses the check.6. Sorted list of one model
const tasks = ActiveCollection.create(Task, [{ id: 3 }, { id: 1 }], { sortBy: 'id', unique: 'id' })
tasks.push({ id: 2 }) // [1, 2, 3], inserted in place
tasks.push({ id: 2 }) // ValidationError (unique)
tasks[0].id = 10 // the item moved: [2, 3, 10]
tasks.findByKey(3) // binary search
tasks.range(2, 5) // [2, 3]
tasks.push(42 as never) // TypeError: accepts only Tasktype Task = { id: number, title: string }
class SortedTasks {
private items: Task[] = []
add (task: Task) {
if (typeof task?.id !== 'number') throw new TypeError('not a Task')
let lo = 0
let hi = this.items.length
while (lo < hi) {
const mid = (lo + hi) >> 1
if (this.items[mid].id < task.id) lo = mid + 1
else hi = mid
}
if (this.items[lo]?.id === task.id) throw new Error(`duplicate id ${task.id}`)
this.items.splice(lo, 0, task)
}
find (id: number) {
const i = this.lowerBound(id)
return this.items[i]?.id === id ? this.items[i] : undefined
}
range (min: number, max: number) {
return this.items.slice(this.lowerBound(min), this.lowerBound(max + Number.EPSILON))
}
private lowerBound (id: number) {
let lo = 0
let hi = this.items.length
while (lo < hi) {
const mid = (lo + hi) >> 1
if (this.items[mid].id < id) lo = mid + 1
else hi = mid
}
return lo
}
}
// Changing task.id from outside breaks the order, and the array cannot be exposed at all
// (or must be frozen), losing push/map/filter. The runtime type check is left to add().7. Allowed state transitions
class Order extends ActiveModel {
@ActiveField({ transitions: { new: ['paid', 'cancelled'], paid: ['shipped'], shipped: [], cancelled: [] } })
status: string = 'new'
}
const order = Order.create({})
order.status = 'paid'
order.status = 'new' // ValidationError: transition paid -> new is not allowed
order.canTransition('status', 'shipped') // trueconst transitions: Record<string, string[]> = {
new: ['paid', 'cancelled'],
paid: ['shipped'],
shipped: [],
cancelled: [],
}
const order = { status: 'new' }
function moveTo (next: string) {
if (next === order.status) return
if (!transitions[order.status]?.includes(next)) {
throw new Error(`Transition ${order.status} -> ${next} is not allowed`)
}
order.status = next
}
// order.status = 'new' bypassing moveTo() passes silently; forbidding it needs a Proxy or a getter/setter on every field.8. Field change events
import { EventType } from '@alt-point/active-models/types'
User.on(EventType.afterSetValue, ({ prop, value, oldValue }) => audit(prop, oldValue, value)) // all instances of the class
const user = User.create({ name: 'Ann' })
user.on(EventType.touched, () => saveButton.enable()) // one instance
user.name = 'Bob' // both listeners fired; an error in one does not block the otherstype Listener<T> = (change: { prop: keyof T, value: unknown, oldValue: unknown }) => void
function observable<T extends object> (target: T, classListeners: Listener<T>[] = []) {
const own: Listener<T>[] = []
const proxy = new Proxy(target, {
set (obj, prop, value, receiver) {
const oldValue = Reflect.get(obj, prop, receiver)
const ok = Reflect.set(obj, prop, value, receiver)
if (ok && oldValue !== value) {
const errors: unknown[] = []
for (const listener of [...classListeners, ...own]) {
try { listener({ prop: prop as keyof T, value, oldValue }) } catch (error) { errors.push(error) }
}
if (errors.length) throw errors[0]
}
return ok
},
})
return { proxy, on: (listener: Listener<T>) => { own.push(listener); return () => own.splice(own.indexOf(listener), 1) } }
}
// Class-wide listeners, subscription inheritance and change "bubbling" from nested objects and collections
// must be added by hand; nested objects must be wrapped in a Proxy recursively.