@earnestjs/model 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/values.js ADDED
@@ -0,0 +1,695 @@
1
+ const WHERE_SURROGATES_SORT_LAST = 0x2000;
2
+ const WHERE_HIGH_UNITS_MOVE_DOWN = 0x800;
3
+ const FIRST_SURROGATE = 0xd800;
4
+ const FIRST_UNIT_AFTER_SURROGATES = 0xe000;
5
+ const byCodePoint = (unit) => {
6
+ if (unit >= FIRST_UNIT_AFTER_SURROGATES) {
7
+ return unit - WHERE_HIGH_UNITS_MOVE_DOWN;
8
+ }
9
+ return unit >= FIRST_SURROGATE ? unit + WHERE_SURROGATES_SORT_LAST : unit;
10
+ };
11
+ /**
12
+ * Compares two texts by code point, the order of Rust's `str` and of the UTF-8 bytes, which is
13
+ * the order every set, map and record is kept in. JavaScript's own `<` compares UTF-16 code
14
+ * units, and so puts a character past U+FFFF before one from U+E000 to U+FFFF.
15
+ */
16
+ export const compareText = (left, right) => {
17
+ const shortest = Math.min(left.length, right.length);
18
+ for (let position = 0; position < shortest; position += 1) {
19
+ const order = byCodePoint(left.charCodeAt(position)) - byCodePoint(right.charCodeAt(position));
20
+ if (order !== 0) {
21
+ return order;
22
+ }
23
+ }
24
+ return left.length - right.length;
25
+ };
26
+ /**
27
+ * The base of every collection, lock, timer, request and retry value. Two values with the same
28
+ * content are the same object, so `===` compares them by content.
29
+ */
30
+ export class ModelValue {
31
+ }
32
+ /** Tells a record, which is a plain object, from every other value a model can hold. */
33
+ export const isRecord = (value) => typeof value === "object" &&
34
+ value !== null &&
35
+ !Array.isArray(value) &&
36
+ !(value instanceof ModelValue);
37
+ /**
38
+ * Text that is equal for two model values exactly when their content is equal. A record's key
39
+ * does not depend on the order its fields were written in. Throws for anything a model can't
40
+ * hold, such as `undefined` or a function.
41
+ */
42
+ export const keyOf = (value) => {
43
+ if (value instanceof ModelValue) {
44
+ return value.key;
45
+ }
46
+ if (value === null || typeof value === "boolean") {
47
+ return String(value);
48
+ }
49
+ if (typeof value === "number") {
50
+ return value === 0 ? "0" : String(value);
51
+ }
52
+ if (typeof value === "string") {
53
+ return JSON.stringify(value);
54
+ }
55
+ if (isRecord(value)) {
56
+ const fields = Object.keys(value)
57
+ .sort(compareText)
58
+ .map((name) => `${JSON.stringify(name)}:${keyOf(value[name])}`);
59
+ return `{${fields.join(",")}}`;
60
+ }
61
+ throw new Error(`${String(value)} is not a value a model can hold`);
62
+ };
63
+ /** Turns a model value into the form `earnest verify --json` prints. */
64
+ export const toJson = (value) => {
65
+ if (value instanceof ModelValue) {
66
+ return value.toJSON();
67
+ }
68
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
69
+ return value;
70
+ }
71
+ if (typeof value === "number") {
72
+ return value === 0 ? 0 : value;
73
+ }
74
+ if (isRecord(value)) {
75
+ return Object.fromEntries(Object.keys(value)
76
+ .sort(compareText)
77
+ .map((name) => [name, toJson(value[name])]));
78
+ }
79
+ throw new Error(`${String(value)} is not a value a model can hold`);
80
+ };
81
+ /**
82
+ * Makes a record, and every record inside it, read-only, and gives the same value back. Other
83
+ * values are already immutable.
84
+ */
85
+ export const frozen = (value) => {
86
+ if (isRecord(value) && !Object.isFrozen(value)) {
87
+ Object.values(value).forEach(frozen);
88
+ Object.freeze(value);
89
+ }
90
+ return value;
91
+ };
92
+ /** Tells a JSON array from every other JSON value. */
93
+ export const isJsonList = (json) => Array.isArray(json);
94
+ /** Tells a JSON object from every other JSON value. */
95
+ export const isJsonObject = (json) => typeof json === "object" && json !== null && !Array.isArray(json);
96
+ const rank = (json) => {
97
+ if (json === null) {
98
+ return 0;
99
+ }
100
+ if (typeof json === "boolean") {
101
+ return 1;
102
+ }
103
+ if (typeof json === "number") {
104
+ return 2;
105
+ }
106
+ if (typeof json === "string") {
107
+ return 3;
108
+ }
109
+ return isJsonList(json) ? 5 : 4;
110
+ };
111
+ const compareLists = (left, right) => {
112
+ for (const [position, item] of left.entries()) {
113
+ const other = right[position];
114
+ if (other === undefined) {
115
+ return 1;
116
+ }
117
+ const order = compareJson(item, other);
118
+ if (order !== 0) {
119
+ return order;
120
+ }
121
+ }
122
+ return left.length - right.length;
123
+ };
124
+ const flattened = (json) => Object.keys(json)
125
+ .sort(compareText)
126
+ .flatMap((name) => [name, json[name] ?? null]);
127
+ /**
128
+ * The order set members and map keys are kept and printed in: `null`, then booleans, numbers,
129
+ * text in code point order (see `compareText`), records by their field names in that order, and
130
+ * collections item by item. Returns a negative number, zero or a
131
+ * positive number, as a sort comparator does.
132
+ */
133
+ export const compareJson = (left, right) => {
134
+ if (typeof left === "boolean" && typeof right === "boolean") {
135
+ return Number(left) - Number(right);
136
+ }
137
+ if (typeof left === "number" && typeof right === "number") {
138
+ return left - right;
139
+ }
140
+ if (typeof left === "string" && typeof right === "string") {
141
+ return compareText(left, right);
142
+ }
143
+ if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {
144
+ return rank(left) - rank(right);
145
+ }
146
+ if (isJsonList(left) && isJsonList(right)) {
147
+ return compareLists(left, right);
148
+ }
149
+ if (!isJsonList(left) && !isJsonList(right)) {
150
+ return compareLists(flattened(left), flattened(right));
151
+ }
152
+ return rank(left) - rank(right);
153
+ };
154
+ const shared = new Map();
155
+ const forgotten = new FinalizationRegistry((key) => {
156
+ if (shared.get(key)?.deref() === undefined) {
157
+ shared.delete(key);
158
+ }
159
+ });
160
+ const isSameValue = (found, made) => found !== undefined && found.constructor === made.constructor && found.key === made.key;
161
+ const one = (made) => {
162
+ const found = shared.get(made.key)?.deref();
163
+ if (isSameValue(found, made)) {
164
+ return found;
165
+ }
166
+ shared.set(made.key, new WeakRef(made));
167
+ forgotten.register(made, made.key);
168
+ return made;
169
+ };
170
+ const member = (item) => ({
171
+ item: frozen(item),
172
+ key: keyOf(item),
173
+ json: toJson(item),
174
+ });
175
+ const inOrder = (left, right) => compareJson(left.json, right.json) || (left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
176
+ const sortedMembers = (items) => {
177
+ const byKey = new Map([...items].map(member).map((each) => [each.key, each]));
178
+ return [...byKey.values()].sort(inOrder);
179
+ };
180
+ const listed = (items) => [...items].map(frozen);
181
+ const orNull = (found) => (found === undefined ? null : found);
182
+ /**
183
+ * An immutable set. Members are compared by content and kept in the order of `compareJson`,
184
+ * whatever order they were added in. `has`, `isSubset`, `size`, `isEmpty`, `every` and `some`
185
+ * read the set; `add`, `delete`, `union`, `intersect`, `subtract` and `filter` give back another
186
+ * set and leave this one as it was.
187
+ */
188
+ export class SetValue extends ModelValue {
189
+ #items;
190
+ #keys;
191
+ key;
192
+ constructor(members) {
193
+ super();
194
+ this.#items = members.map((each) => each.item);
195
+ this.#keys = new Set(members.map((each) => each.key));
196
+ this.key = `set(${members.map((each) => each.key).join(",")})`;
197
+ }
198
+ /** The set of the given items; an item given twice is in the set once. */
199
+ static of(items) {
200
+ return one(new SetValue(sortedMembers(items)));
201
+ }
202
+ get size() {
203
+ return this.#items.length;
204
+ }
205
+ get isEmpty() {
206
+ return this.#items.length === 0;
207
+ }
208
+ has(item) {
209
+ return this.#keys.has(keyOf(item));
210
+ }
211
+ add(item) {
212
+ return SetValue.of([...this.#items, item]);
213
+ }
214
+ delete(item) {
215
+ const gone = keyOf(item);
216
+ return SetValue.of(this.#items.filter((each) => keyOf(each) !== gone));
217
+ }
218
+ union(other) {
219
+ return SetValue.of([...this.#items, ...other]);
220
+ }
221
+ intersect(other) {
222
+ return SetValue.of(this.#items.filter((each) => other.has(each)));
223
+ }
224
+ subtract(other) {
225
+ return SetValue.of(this.#items.filter((each) => !other.has(each)));
226
+ }
227
+ isSubset(other) {
228
+ return this.#items.every((each) => other.has(each));
229
+ }
230
+ every(test) {
231
+ return this.#items.every((each) => test(each));
232
+ }
233
+ some(test) {
234
+ return this.#items.some((each) => test(each));
235
+ }
236
+ filter(test) {
237
+ return SetValue.of(this.#items.filter((each) => test(each)));
238
+ }
239
+ [Symbol.iterator]() {
240
+ return this.#items[Symbol.iterator]();
241
+ }
242
+ toJSON() {
243
+ return this.#items.map(toJson);
244
+ }
245
+ }
246
+ /**
247
+ * An immutable map. Keys are compared by content and kept in the order of `compareJson`.
248
+ * `get` gives `null` for a key the map does not have. `set` and `delete` give back another map
249
+ * and leave this one as it was. Iterating gives `[key, value]` pairs.
250
+ */
251
+ export class MapValue extends ModelValue {
252
+ #entries;
253
+ key;
254
+ constructor(entries) {
255
+ super();
256
+ this.#entries = new Map(entries.map((entry) => [keyOf(entry[0]), entry]));
257
+ const shown = entries.map(([key, value]) => `${keyOf(key)}=>${keyOf(value)}`);
258
+ this.key = `map(${shown.join(",")})`;
259
+ }
260
+ /** The map of the given pairs; when a key is given twice, the later pair wins. */
261
+ static of(entries) {
262
+ const latest = new Map([...entries].map((entry) => [keyOf(entry[0]), entry]));
263
+ const ordered = [...latest.values()]
264
+ .map(([key, value]) => ({ at: member(key), value: frozen(value) }))
265
+ .sort((left, right) => inOrder(left.at, right.at));
266
+ return one(new MapValue(ordered.map((each) => [each.at.item, each.value])));
267
+ }
268
+ get size() {
269
+ return this.#entries.size;
270
+ }
271
+ get isEmpty() {
272
+ return this.#entries.size === 0;
273
+ }
274
+ get keys() {
275
+ return SetValue.of([...this.#entries.values()].map(([key]) => key));
276
+ }
277
+ has(key) {
278
+ return this.#entries.has(keyOf(key));
279
+ }
280
+ get(key) {
281
+ const found = this.#entries.get(keyOf(key));
282
+ return found === undefined ? null : found[1];
283
+ }
284
+ set(key, value) {
285
+ return MapValue.of([...this.#entries.values(), [key, value]]);
286
+ }
287
+ delete(key) {
288
+ const gone = keyOf(key);
289
+ return MapValue.of([...this.#entries].filter(([known]) => known !== gone).map(([, entry]) => entry));
290
+ }
291
+ [Symbol.iterator]() {
292
+ return this.#entries.values();
293
+ }
294
+ toJSON() {
295
+ return [...this.#entries.values()].map(([key, value]) => [toJson(key), toJson(value)]);
296
+ }
297
+ }
298
+ /**
299
+ * An immutable sequence. `get`, `first` and `last` give `null` where there is no item. `push`
300
+ * adds at the end, `shift` drops the first item and `pop` drops the last; each gives back
301
+ * another sequence, and `shift` and `pop` on an empty sequence give the empty sequence. Pushing
302
+ * past the declared `max` is not an error here: the checker reports the state as out of range.
303
+ */
304
+ export class SeqValue extends ModelValue {
305
+ #items;
306
+ key;
307
+ constructor(items) {
308
+ super();
309
+ this.#items = items;
310
+ this.key = `seq(${items.map(keyOf).join(",")})`;
311
+ }
312
+ /** The sequence of the given items, in the order given. */
313
+ static of(items) {
314
+ return one(new SeqValue(listed(items)));
315
+ }
316
+ get size() {
317
+ return this.#items.length;
318
+ }
319
+ get isEmpty() {
320
+ return this.#items.length === 0;
321
+ }
322
+ get first() {
323
+ return orNull(this.#items[0]);
324
+ }
325
+ get last() {
326
+ return orNull(this.#items[this.#items.length - 1]);
327
+ }
328
+ get(position) {
329
+ return orNull(this.#items[position]);
330
+ }
331
+ push(item) {
332
+ return SeqValue.of([...this.#items, item]);
333
+ }
334
+ shift() {
335
+ return SeqValue.of(this.#items.slice(1));
336
+ }
337
+ pop() {
338
+ return SeqValue.of(this.#items.slice(0, -1));
339
+ }
340
+ includes(item) {
341
+ const wanted = keyOf(item);
342
+ return this.#items.some((each) => keyOf(each) === wanted);
343
+ }
344
+ every(test) {
345
+ return this.#items.every((each) => test(each));
346
+ }
347
+ some(test) {
348
+ return this.#items.some((each) => test(each));
349
+ }
350
+ filter(test) {
351
+ return SeqValue.of(this.#items.filter((each) => test(each)));
352
+ }
353
+ [Symbol.iterator]() {
354
+ return this.#items[Symbol.iterator]();
355
+ }
356
+ toJSON() {
357
+ return this.#items.map(toJson);
358
+ }
359
+ }
360
+ /**
361
+ * An immutable first-in, first-out queue with a capacity. `head` is the item `receive` would
362
+ * drop, or `null`. `send`, `receive` and `clear` give back another queue. Sending to a full
363
+ * queue is not an error here: the checker reports the state as out of range.
364
+ */
365
+ export class QueueValue extends ModelValue {
366
+ #items;
367
+ #capacity;
368
+ key;
369
+ constructor(capacity, items) {
370
+ super();
371
+ this.#capacity = capacity;
372
+ this.#items = items;
373
+ this.key = `queue/${capacity}(${items.map(keyOf).join(",")})`;
374
+ }
375
+ /** The queue of the given capacity holding the given items, the first of them at the head. */
376
+ static of(capacity, items) {
377
+ return one(new QueueValue(capacity, listed(items)));
378
+ }
379
+ get size() {
380
+ return this.#items.length;
381
+ }
382
+ get isEmpty() {
383
+ return this.#items.length === 0;
384
+ }
385
+ get capacity() {
386
+ return this.#capacity;
387
+ }
388
+ get isFull() {
389
+ return this.#items.length >= this.#capacity;
390
+ }
391
+ get head() {
392
+ return orNull(this.#items[0]);
393
+ }
394
+ send(item) {
395
+ return QueueValue.of(this.#capacity, [...this.#items, item]);
396
+ }
397
+ receive() {
398
+ return QueueValue.of(this.#capacity, this.#items.slice(1));
399
+ }
400
+ includes(item) {
401
+ const wanted = keyOf(item);
402
+ return this.#items.some((each) => keyOf(each) === wanted);
403
+ }
404
+ clear() {
405
+ return QueueValue.of(this.#capacity, []);
406
+ }
407
+ every(test) {
408
+ return this.#items.every((each) => test(each));
409
+ }
410
+ some(test) {
411
+ return this.#items.some((each) => test(each));
412
+ }
413
+ [Symbol.iterator]() {
414
+ return this.#items[Symbol.iterator]();
415
+ }
416
+ toJSON() {
417
+ return this.#items.map(toJson);
418
+ }
419
+ }
420
+ /**
421
+ * A lock with no owner: free or held. `acquire` and `release` give back another lock; acquiring
422
+ * a held lock gives a held lock, so guard with `isFree` in the action's `when`.
423
+ */
424
+ export class LockValue extends ModelValue {
425
+ #isHeld;
426
+ key;
427
+ constructor(isHeld) {
428
+ super();
429
+ this.#isHeld = isHeld;
430
+ this.key = `lock(${isHeld ? "held" : "free"})`;
431
+ }
432
+ /** The held lock when `isHeld` is true, the free lock otherwise. */
433
+ static of(isHeld) {
434
+ return one(new LockValue(isHeld));
435
+ }
436
+ get isFree() {
437
+ return !this.#isHeld;
438
+ }
439
+ get isHeld() {
440
+ return this.#isHeld;
441
+ }
442
+ acquire() {
443
+ return LockValue.of(true);
444
+ }
445
+ release() {
446
+ return LockValue.of(false);
447
+ }
448
+ toJSON() {
449
+ return this.#isHeld;
450
+ }
451
+ }
452
+ /**
453
+ * A lock that remembers who holds it. `holder` is `null` when the lock is free. `acquire(owner)`
454
+ * and `release` give back another lock; acquiring a held lock hands it to the new owner, so
455
+ * guard with `isFree` in the action's `when`.
456
+ */
457
+ export class OwnedLockValue extends ModelValue {
458
+ #holder;
459
+ key;
460
+ constructor(holder) {
461
+ super();
462
+ this.#holder = holder;
463
+ this.key = `owned-lock(${keyOf(holder)})`;
464
+ }
465
+ /** The lock held by `holder`, or the free lock for `null`. */
466
+ static of(holder) {
467
+ return one(new OwnedLockValue(frozen(holder)));
468
+ }
469
+ get isFree() {
470
+ return this.#holder === null;
471
+ }
472
+ get isHeld() {
473
+ return this.#holder !== null;
474
+ }
475
+ get holder() {
476
+ return this.#holder;
477
+ }
478
+ isHeldBy(owner) {
479
+ return this.#holder !== null && keyOf(this.#holder) === keyOf(owner);
480
+ }
481
+ acquire(owner) {
482
+ return OwnedLockValue.of(owner);
483
+ }
484
+ release() {
485
+ return OwnedLockValue.of(null);
486
+ }
487
+ toJSON() {
488
+ return toJson(this.#holder);
489
+ }
490
+ }
491
+ /** The stages of a timer, in the order a declaration lists them. */
492
+ export const TIMER_STAGES = ["idle", "running", "fired"];
493
+ /**
494
+ * A timer: idle, running or fired. `start`, `fire`, `cancel` and `reset` give back another timer
495
+ * from any stage; `cancel` and `reset` both give the idle timer.
496
+ */
497
+ export class TimerValue extends ModelValue {
498
+ #stage;
499
+ key;
500
+ constructor(stage) {
501
+ super();
502
+ this.#stage = stage;
503
+ this.key = `timer(${stage})`;
504
+ }
505
+ /** The timer at the given stage. */
506
+ static at(stage) {
507
+ return one(new TimerValue(stage));
508
+ }
509
+ get isIdle() {
510
+ return this.#stage === "idle";
511
+ }
512
+ get isRunning() {
513
+ return this.#stage === "running";
514
+ }
515
+ get hasFired() {
516
+ return this.#stage === "fired";
517
+ }
518
+ start() {
519
+ return TimerValue.at("running");
520
+ }
521
+ fire() {
522
+ return TimerValue.at("fired");
523
+ }
524
+ cancel() {
525
+ return TimerValue.at("idle");
526
+ }
527
+ reset() {
528
+ return TimerValue.at("idle");
529
+ }
530
+ toJSON() {
531
+ return this.#stage;
532
+ }
533
+ }
534
+ /** The stages of an async request, in the order a declaration lists them. */
535
+ export const REQUEST_STAGES = ["idle", "pending", "succeeded", "failed"];
536
+ /**
537
+ * An async request: idle, pending, succeeded or failed. `isSettled` is true once it succeeded or
538
+ * failed. `send`, `succeed`, `fail` and `reset` give back another request from any stage.
539
+ */
540
+ export class RequestValue extends ModelValue {
541
+ #stage;
542
+ key;
543
+ constructor(stage) {
544
+ super();
545
+ this.#stage = stage;
546
+ this.key = `request(${stage})`;
547
+ }
548
+ /** The request at the given stage. */
549
+ static at(stage) {
550
+ return one(new RequestValue(stage));
551
+ }
552
+ get isIdle() {
553
+ return this.#stage === "idle";
554
+ }
555
+ get isPending() {
556
+ return this.#stage === "pending";
557
+ }
558
+ get hasSucceeded() {
559
+ return this.#stage === "succeeded";
560
+ }
561
+ get hasFailed() {
562
+ return this.#stage === "failed";
563
+ }
564
+ get isSettled() {
565
+ return this.#stage === "succeeded" || this.#stage === "failed";
566
+ }
567
+ send() {
568
+ return RequestValue.at("pending");
569
+ }
570
+ succeed() {
571
+ return RequestValue.at("succeeded");
572
+ }
573
+ fail() {
574
+ return RequestValue.at("failed");
575
+ }
576
+ reset() {
577
+ return RequestValue.at("idle");
578
+ }
579
+ toJSON() {
580
+ return this.#stage;
581
+ }
582
+ }
583
+ /**
584
+ * A count of attempts with a most. `canRetry` is true below the most and `isExhausted` at it.
585
+ * `again` counts one more attempt and `reset` goes back to zero; both give back another counter.
586
+ * Counting past the most is not an error here: the checker reports the state as out of range.
587
+ */
588
+ export class RetryValue extends ModelValue {
589
+ #max;
590
+ #attempts;
591
+ key;
592
+ constructor(max, attempts) {
593
+ super();
594
+ this.#max = max;
595
+ this.#attempts = attempts;
596
+ this.key = `retry/${max}(${attempts})`;
597
+ }
598
+ /** The counter that allows `max` attempts and has counted `attempts` of them. */
599
+ static of(max, attempts) {
600
+ return one(new RetryValue(max, attempts));
601
+ }
602
+ get max() {
603
+ return this.#max;
604
+ }
605
+ get attempts() {
606
+ return this.#attempts;
607
+ }
608
+ get canRetry() {
609
+ return this.#attempts < this.#max;
610
+ }
611
+ get isExhausted() {
612
+ return this.#attempts >= this.#max;
613
+ }
614
+ again() {
615
+ return RetryValue.of(this.#max, this.#attempts + 1);
616
+ }
617
+ reset() {
618
+ return RetryValue.of(this.#max, 0);
619
+ }
620
+ toJSON() {
621
+ return this.#attempts;
622
+ }
623
+ }
624
+ /** Writes a set value: `m.setOf("a", "b")`. Members keep their literal types. */
625
+ export const setOf = (...items) => SetValue.of(items);
626
+ /** Writes a sequence value: `m.seqOf("a", "b")`. It is also how a queue's `.initial` is written. */
627
+ export const seqOf = (...items) => SeqValue.of(items);
628
+ /** Writes a map value from `[key, value]` pairs: `m.mapOf(["a", 1], ["b", 2])`. */
629
+ export const mapOf = (...entries) => MapValue.of(entries);
630
+ const BY_ZERO = "takes a division or a remainder by zero";
631
+ /** Thrown by `rem` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
632
+ export class RemainderFault extends Error {
633
+ constructor() {
634
+ super(BY_ZERO);
635
+ this.name = "RemainderFault";
636
+ }
637
+ }
638
+ /** Thrown by `div` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
639
+ export class DivisionFault extends Error {
640
+ constructor() {
641
+ super(BY_ZERO);
642
+ this.name = "DivisionFault";
643
+ }
644
+ }
645
+ /** Thrown by `some` for a `null`; `explore` and `replay` report it as a read of a null value. */
646
+ export class NullFault extends Error {
647
+ constructor() {
648
+ super("reads a value that is null");
649
+ this.name = "NullFault";
650
+ }
651
+ }
652
+ /**
653
+ * Writes the value inside an optional: `m.some(s.chosen).qty`. A `null` is a fault, as in
654
+ * `earnest verify`, because JavaScript would go on with `null` as a number. Use it where
655
+ * TypeScript would want a postfix `!`, which a model file may not have.
656
+ */
657
+ export const some = (value) => {
658
+ if (value === null || value === undefined) {
659
+ throw new NullFault();
660
+ }
661
+ return value;
662
+ };
663
+ const numbers = (a, b) => {
664
+ if (Number.isNaN(a) || Number.isNaN(b)) {
665
+ throw new TypeError("m.div and m.rem take numbers, and NaN is not one");
666
+ }
667
+ };
668
+ /**
669
+ * Writes the remainder of `a` divided by `b`, JavaScript's `a % b`: `m.rem(7, 3)` is 1,
670
+ * `m.rem(-7, 2)` is -1 and `m.rem(7, -2)` is 1, with the sign of `a` as Rust's `%` has it. A
671
+ * zero result is 0, never -0. A `b` of zero is a fault, as in `earnest verify`, where JavaScript
672
+ * would go on with `NaN`, and so is a `NaN`. Use it where JavaScript would use `%`, which a model
673
+ * file may not.
674
+ */
675
+ export const rem = (a, b) => {
676
+ numbers(a, b);
677
+ if (b === 0) {
678
+ throw new RemainderFault();
679
+ }
680
+ return (a % b) + 0;
681
+ };
682
+ /**
683
+ * Writes the whole number of times `b` goes into `a`, `Math.trunc(a / b)`: `m.div(7, 2)` is 3,
684
+ * `m.div(-7, 2)` is -3 and `m.div(-7, -2)` is 3, as Rust's `/` on integers. It is exact for
685
+ * every safe integer, and a zero result is 0, never -0. A `b` of zero is a fault, as in
686
+ * `earnest verify` and as Rust panics, and so is a `NaN`. Use it where JavaScript would use
687
+ * `/`, which a model file may not, since it gives a fraction.
688
+ */
689
+ export const div = (a, b) => {
690
+ numbers(a, b);
691
+ if (b === 0) {
692
+ throw new DivisionFault();
693
+ }
694
+ return Math.trunc(a / b) + 0;
695
+ };