mambascript 0.5.5 → 2.0.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/CHANGELOG.md +326 -0
- package/README.md +509 -267
- package/bin/mamba +1 -258
- package/decision.js +1 -246
- package/docs/coverage.md +70 -0
- package/docs/features.md +3348 -0
- package/docs/perf.md +94 -0
- package/docs/reference.md +1295 -0
- package/docs/vs-coffeescript.md +1593 -0
- package/docs/vs-iced-coffeescript.md +626 -0
- package/docs/vs-typescript.md +107 -0
- package/esm.js +8 -0
- package/jest.js +33 -0
- package/lib/black.js +17 -13
- package/lib/browser.js +2 -4
- package/lib/cli.js +207 -136
- package/lib/compiler.js +1162 -93
- package/lib/decision.js +10 -10
- package/lib/diagnostics.js +219 -0
- package/lib/esm-hooks.js +60 -0
- package/lib/fast-parser.js +3469 -0
- package/lib/functional-helpers.js +26 -9
- package/lib/helpers.js +67 -50
- package/lib/js-nodes.js +151 -12
- package/lib/lexer.js +1499 -0
- package/lib/light-module.js +200 -63
- package/lib/mamba.js +372 -0
- package/lib/module.js +23 -172
- package/lib/nodes.js +84 -21
- package/lib/optimiser.js +29 -9
- package/lib/optparse.js +32 -15
- package/lib/parser.js +9433 -4840
- package/lib/preprocessor.js +3 -5
- package/lib/register.js +49 -56
- package/lib/repl.js +28 -9
- package/lib/reporter.js +106 -69
- package/lib/run.js +3 -5
- package/lib/string-scanner.js +94 -0
- package/lib/syntax-tables.js +480 -0
- package/lib/type-checker.js +258 -44
- package/lib/type-helpers.js +28 -10
- package/lib/type-resolver.js +256 -34
- package/lib/type-scope.js +10 -6
- package/lib/type-walker.js +664 -85
- package/lib/types.js +17 -7
- package/lib/underscore.js +170 -76
- package/lib/unicode-classes.js +122 -0
- package/mambaview.js +1 -0
- package/package.json +49 -46
- package/stdlib.js +1 -0
- package/vendor/README.md +40 -0
- package/vendor/escodegen/LICENSE.BSD +19 -0
- package/vendor/escodegen/escodegen.js +2289 -0
- package/vendor/estraverse/LICENSE.BSD +19 -0
- package/vendor/estraverse/estraverse.js +706 -0
- package/vendor/mambacodegen/LICENSE +24 -0
- package/vendor/mambacodegen/lib/mscodegen.js +620 -0
- package/vendor/patches/escodegen.diff +130 -0
- package/vendor/patches/estraverse.diff +51 -0
- package/vendor/patches/pegjs.diff +70 -0
- package/vendor/patches/source-map.diff +160 -0
- package/vendor/source-map/LICENSE +28 -0
- package/vendor/source-map/lib/source-map/array-set.js +92 -0
- package/vendor/source-map/lib/source-map/base64-vlq.js +140 -0
- package/vendor/source-map/lib/source-map/base64.js +38 -0
- package/vendor/source-map/lib/source-map/binary-search.js +77 -0
- package/vendor/source-map/lib/source-map/source-map-consumer.js +404 -0
- package/vendor/source-map/lib/source-map/source-map-generator.js +229 -0
- package/vendor/source-map/lib/source-map/source-node.js +201 -0
- package/vendor/source-map/lib/source-map/util.js +57 -0
- package/vendor/source-map/lib/source-map.js +8 -0
- package/bin/fix +0 -17
- package/bin/updateImports +0 -46
- package/build.js +0 -25
- package/lib/module-esm.js +0 -901
- package/lib/pegjs-kofu-plugin.js +0 -35
- package/lib/pegjs-mamba-plugin.js +0 -35
- package/lib/processor-esm.js +0 -507
- package/mamba +0 -259
- package/msast.js +0 -1
- package/utils/gulp-mamba.js +0 -29
- /package/{lib/esm.js → vendor/patches/mambacodegen.diff} +0 -0
package/docs/features.md
ADDED
|
@@ -0,0 +1,3348 @@
|
|
|
1
|
+
# MambaScript 2.0: the 100 most distinctive features
|
|
2
|
+
|
|
3
|
+
Each feature below is shown the same way: an **Explanation** (what it is, what it compiles to, the
|
|
4
|
+
rule or quirk you must know, and when to reach for it) and a **Demonstration** (a complete program
|
|
5
|
+
you can paste into a file and run with `mamba file.mamba`, followed by the exact output it prints).
|
|
6
|
+
Every demonstration compiles under both parsers with type checking set to fail on error
|
|
7
|
+
(`mamba --strict` and `mamba --strict --parser peg`), and the output shown is the real
|
|
8
|
+
output of running it.
|
|
9
|
+
|
|
10
|
+
The examples follow the Super Coder course: orders, menus, guilds and players. Where MambaScript
|
|
11
|
+
gives a word and a symbol for the same thing, the word is used. The full rules are in
|
|
12
|
+
[reference.md](reference.md); the JavaScript each form becomes is shown there next to it.
|
|
13
|
+
|
|
14
|
+
## Contents
|
|
15
|
+
|
|
16
|
+
1. [Variables](#variables) (1–8)
|
|
17
|
+
2. [Types](#types) (9–18)
|
|
18
|
+
3. [Control flow](#control-flow) (19–28)
|
|
19
|
+
4. [Arrays](#arrays) (29–36)
|
|
20
|
+
5. [Objects](#objects) (37–44)
|
|
21
|
+
6. [Blueprints](#blueprints) (45–53)
|
|
22
|
+
7. [Functions](#functions) (54–62)
|
|
23
|
+
8. [OOP](#oop) (63–69)
|
|
24
|
+
9. [Complex data structures](#complex-data-structures) (70–77)
|
|
25
|
+
10. [Functional programming](#functional-programming) (78–85)
|
|
26
|
+
11. [Design patterns](#design-patterns) (86–93)
|
|
27
|
+
12. [Algorithms](#algorithms) (94–100)
|
|
28
|
+
|
|
29
|
+
## Variables
|
|
30
|
+
|
|
31
|
+
### 1. The first assignment declares
|
|
32
|
+
|
|
33
|
+
**Explanation.** There is no `let`, `const` or `var`: the first assignment to a name declares it,
|
|
34
|
+
and the compiler writes one `var` line at the top of the enclosing function. That means variables
|
|
35
|
+
are function scoped and hoisted, exactly like JavaScript's `var`: a name assigned inside an `if`
|
|
36
|
+
is visible after it, and reading a name before its assignment gives `undefined` instead of a
|
|
37
|
+
temporal-dead-zone error. Assigning to a name that an outer function already declared updates
|
|
38
|
+
that outer variable, which is how closures share state.
|
|
39
|
+
|
|
40
|
+
**Demonstration.**
|
|
41
|
+
```mamba
|
|
42
|
+
total = 0
|
|
43
|
+
addToOrder = (price) ->
|
|
44
|
+
total = total + price # the outer total: no new variable is made
|
|
45
|
+
count = 1 # count is local to addToOrder
|
|
46
|
+
total
|
|
47
|
+
|
|
48
|
+
if total is 0
|
|
49
|
+
status = 'empty cart' # declared for the whole file, not just the if
|
|
50
|
+
|
|
51
|
+
present status
|
|
52
|
+
addToOrder 4.5
|
|
53
|
+
addToOrder 3
|
|
54
|
+
present total
|
|
55
|
+
present typeof count
|
|
56
|
+
present tip # hoisted: exists, but not yet assigned
|
|
57
|
+
tip = 2
|
|
58
|
+
```
|
|
59
|
+
```text
|
|
60
|
+
empty cart
|
|
61
|
+
7.5
|
|
62
|
+
undefined
|
|
63
|
+
undefined
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 2. Words for values: yes, no, on, off, nothing, missing
|
|
67
|
+
|
|
68
|
+
**Explanation.** `yes`/`on` are `true`, `no`/`off` are `false`, `nothing` is `null` and `missing`
|
|
69
|
+
is `undefined` (the JavaScript spellings still work). Pick the word that reads best in the
|
|
70
|
+
sentence: `on`/`off` for switches, `yes`/`no` for answers. `nothing` and `missing` are different
|
|
71
|
+
values (`nothing is missing` is false), but every existence check in the language (`?`, `exists`,
|
|
72
|
+
`orElse`, defaults) treats both as absent.
|
|
73
|
+
|
|
74
|
+
**Demonstration.**
|
|
75
|
+
```mamba
|
|
76
|
+
player =
|
|
77
|
+
name: 'Mia'
|
|
78
|
+
online: on
|
|
79
|
+
banned: no
|
|
80
|
+
guild: nothing
|
|
81
|
+
|
|
82
|
+
present player.online, player.banned
|
|
83
|
+
present player.guild, player.title
|
|
84
|
+
present player.guild is nothing, player.title is missing
|
|
85
|
+
present nothing is missing
|
|
86
|
+
lights = off
|
|
87
|
+
present "lights are #{if lights then 'on' otherwise 'off'}"
|
|
88
|
+
```
|
|
89
|
+
```text
|
|
90
|
+
true false
|
|
91
|
+
null undefined
|
|
92
|
+
true true
|
|
93
|
+
false
|
|
94
|
+
lights are off
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 3. Existence: `x?` and `x exists`
|
|
98
|
+
|
|
99
|
+
**Explanation.** `x?` (or the word form `x exists`) is true when `x` is neither `nothing` nor
|
|
100
|
+
`missing`, so `0`, `''` and `no` all exist. On a name that was never declared anywhere it compiles
|
|
101
|
+
to a `typeof` guard, so it never throws a `ReferenceError`; on a known variable it is a plain
|
|
102
|
+
`x != null`. Use it instead of truthiness whenever zero or the empty string is a real value.
|
|
103
|
+
|
|
104
|
+
**Demonstration.**
|
|
105
|
+
```mamba
|
|
106
|
+
order = {id: 7, tip: 0, note: '', coupon: nothing}
|
|
107
|
+
|
|
108
|
+
present order.tip?, order.note?, order.coupon?, order.missingField?
|
|
109
|
+
if order.tip exists
|
|
110
|
+
present "tip recorded: #{order.tip}"
|
|
111
|
+
present 'no coupon' unless order.coupon exists
|
|
112
|
+
present neverDeclaredAnywhere?
|
|
113
|
+
```
|
|
114
|
+
```text
|
|
115
|
+
true true false false
|
|
116
|
+
tip recorded: 0
|
|
117
|
+
no coupon
|
|
118
|
+
false
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### 4. Defaults: `orElse`, `?` and `?=`
|
|
122
|
+
|
|
123
|
+
**Explanation.** `a orElse b` (or `a ? b`) gives `a` unless it is `nothing` or `missing`, and only
|
|
124
|
+
then evaluates `b`; unlike `or`, it keeps `0`, `''` and `no`. `x ?= v` assigns only when `x` is
|
|
125
|
+
absent and, unlike `x or= v`, it also declares `x`, so it works as the first line that mentions a
|
|
126
|
+
name. `or=` and `and=` need the name to exist already (assign it earlier in the file).
|
|
127
|
+
Fancy tier (`?=` and `orElse` chains); the plain form is `cache = {} unless cache?`.
|
|
128
|
+
|
|
129
|
+
**Demonstration.**
|
|
130
|
+
```mamba
|
|
131
|
+
settings = {volume: 0, theme: nothing}
|
|
132
|
+
|
|
133
|
+
volume = settings.volume orElse 50
|
|
134
|
+
theme = settings.theme ? 'dark'
|
|
135
|
+
loose = settings.volume or 50 # or throws away the 0
|
|
136
|
+
present volume, theme, loose
|
|
137
|
+
|
|
138
|
+
cache ?= {} # declares cache and assigns it
|
|
139
|
+
cache.menu ?= ['tacos']
|
|
140
|
+
cache.menu ?= ['ignored'] # already there: left alone
|
|
141
|
+
present cache
|
|
142
|
+
|
|
143
|
+
greeting = ''
|
|
144
|
+
greeting or= 'welcome'
|
|
145
|
+
present greeting
|
|
146
|
+
```
|
|
147
|
+
```text
|
|
148
|
+
0 dark 50
|
|
149
|
+
{ menu: [ 'tacos' ] }
|
|
150
|
+
welcome
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 5. Numbers: separators, BigInt, bases and `**`
|
|
154
|
+
|
|
155
|
+
**Explanation.** Numbers take `_` between digits (`1_000_000`), and hex `0xFF`, binary `0b1010`
|
|
156
|
+
and octal `0o17` are all available. A whole number followed by `n` is a BigInt, printed verbatim so
|
|
157
|
+
no digit is rounded; mixing a BigInt with an ordinary number in arithmetic is a type error (see
|
|
158
|
+
feature 17). `a ** b` compiles to `Math.pow(a, b)`, so it does not work on BigInts. A fraction
|
|
159
|
+
needs a digit before the point: `0.5`, never `.5`.
|
|
160
|
+
|
|
161
|
+
**Demonstration.**
|
|
162
|
+
```mamba
|
|
163
|
+
goldCap = 1_000_000
|
|
164
|
+
flags = 0b1010_1010
|
|
165
|
+
colour = 0xFF
|
|
166
|
+
perms = 0o755
|
|
167
|
+
huge = 9_007_199_254_740_993n
|
|
168
|
+
present goldCap, flags, colour, perms
|
|
169
|
+
present huge, huge * 2n
|
|
170
|
+
present 9007199254740993 # an ordinary number rounds
|
|
171
|
+
present 2 ** 10, 0.5 * 3
|
|
172
|
+
```
|
|
173
|
+
```text
|
|
174
|
+
1000000 170 255 493
|
|
175
|
+
9007199254740993n 18014398509481986n
|
|
176
|
+
9007199254740992
|
|
177
|
+
1024 1.5
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### 6. Strings: interpolation, line breaks and heredocs
|
|
181
|
+
|
|
182
|
+
**Explanation.** Only double-quoted strings interpolate with `#{…}`; single quotes are literal, and
|
|
183
|
+
`\#{` keeps a literal `#{`. Any string may span lines and keeps the line break (a quirk coming from
|
|
184
|
+
JavaScript: there is no implicit joining). Triple-quoted heredocs `"""…"""` strip the common
|
|
185
|
+
indentation and the newlines right after the opening and before the closing quotes, and need no
|
|
186
|
+
escaping of quotes inside. Use heredocs for templates and messages that run over several lines.
|
|
187
|
+
|
|
188
|
+
**Demonstration.**
|
|
189
|
+
```mamba
|
|
190
|
+
dish = 'ramen'
|
|
191
|
+
qty = 2
|
|
192
|
+
present "#{qty} x #{dish.toUpperCase()} = $#{qty * 6.5}"
|
|
193
|
+
present 'single quotes stay #{literal}'
|
|
194
|
+
present "escaped \#{not interpolated}"
|
|
195
|
+
receipt = "line one
|
|
196
|
+
line two"
|
|
197
|
+
present receipt
|
|
198
|
+
menu = """
|
|
199
|
+
Today's menu:
|
|
200
|
+
- #{dish}
|
|
201
|
+
- "chef's" special
|
|
202
|
+
"""
|
|
203
|
+
present menu
|
|
204
|
+
```
|
|
205
|
+
```text
|
|
206
|
+
2 x RAMEN = $13
|
|
207
|
+
single quotes stay #{literal}
|
|
208
|
+
escaped #{not interpolated}
|
|
209
|
+
line one
|
|
210
|
+
line two
|
|
211
|
+
Today's menu:
|
|
212
|
+
- ramen
|
|
213
|
+
- "chef's" special
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### 7. Regular expressions and heregexes
|
|
217
|
+
|
|
218
|
+
**Explanation.** Regex literals are written as in JavaScript (`/a+/g`) and accept every flag
|
|
219
|
+
(`g i m s u y d v`). A heregex `///…///` ignores whitespace and `#` comments and interpolates
|
|
220
|
+
`#{…}`, so a long pattern can be laid out and annotated line by line; it compiles to a `RegExp`
|
|
221
|
+
built from the pieces. Reach for a heregex whenever a pattern needs a comment to be understood.
|
|
222
|
+
Fancy tier (heregex with interpolation); the plain form is
|
|
223
|
+
`make RegExp '^' + prefix + '-(\\d{4})-(\\d+)$', 'i'`.
|
|
224
|
+
|
|
225
|
+
**Demonstration.**
|
|
226
|
+
```mamba
|
|
227
|
+
prefix = 'ORD'
|
|
228
|
+
orderId = ///
|
|
229
|
+
^ #{prefix} - # the order prefix and a dash
|
|
230
|
+
(\d{4}) # the year
|
|
231
|
+
- (\d+) $ # the sequence number
|
|
232
|
+
///i
|
|
233
|
+
match = orderId.exec 'ord-2026-42'
|
|
234
|
+
present match[1], match[2]
|
|
235
|
+
present 'a1b22c333'.match /\d+/g
|
|
236
|
+
present /^taco$/i.test 'TACO'
|
|
237
|
+
```
|
|
238
|
+
```text
|
|
239
|
+
2026 42
|
|
240
|
+
[ '1', '22', '333' ]
|
|
241
|
+
true
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### 8. Compile-time macros and embedded JavaScript
|
|
245
|
+
|
|
246
|
+
**Explanation.** `__LINE__`, `__FILENAME__`, `__DATE__`, `__TIME__`, `__DATETIMEMS__` and
|
|
247
|
+
`__MAMBA_VERSION__` are replaced by constants when the file is compiled; any other `__NAME__` is
|
|
248
|
+
an error (MS1115). A backtick literal is JavaScript evaluated where it stands, with the surrounding
|
|
249
|
+
variables in scope (it compiles to a direct `eval`). Keep backticks for the rare lesson about a
|
|
250
|
+
JavaScript-only behaviour, such as loose `==`, which MambaScript does not have.
|
|
251
|
+
Fancy tier (macros and embedded JavaScript); the plain form is ordinary MambaScript with a `# differs from JavaScript:` comment.
|
|
252
|
+
|
|
253
|
+
**Demonstration.**
|
|
254
|
+
```mamba
|
|
255
|
+
present "compiled by MambaScript #{__MAMBA_VERSION__}"
|
|
256
|
+
present "this is line #{__LINE__}"
|
|
257
|
+
mask = `0xFF & ~0x0F`
|
|
258
|
+
present mask
|
|
259
|
+
qty = '1'
|
|
260
|
+
present `qty == 1` # loose equality, only through JavaScript
|
|
261
|
+
present qty is 1 # is is always strict
|
|
262
|
+
```
|
|
263
|
+
```text
|
|
264
|
+
compiled by MambaScript 2.0.0
|
|
265
|
+
this is line 2
|
|
266
|
+
240
|
|
267
|
+
true
|
|
268
|
+
false
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## Types
|
|
272
|
+
|
|
273
|
+
The type checker runs on every compile. By default (`warn`) it prints problems and carries on;
|
|
274
|
+
`mamba --strict` (or `typeCheck: 'error'` in the API, `MAMBA_TYPECHECK=error` for the require hook
|
|
275
|
+
and jest) makes them fail the compile; `--no-typecheck` skips it. Several demonstrations below
|
|
276
|
+
compile a broken snippet through the API, so the program itself still compiles under `--strict`
|
|
277
|
+
and prints the diagnostic the snippet would produce.
|
|
278
|
+
|
|
279
|
+
### 9. Optional annotations that leave no trace
|
|
280
|
+
|
|
281
|
+
**Explanation.** `name :: Type` declares a type for a variable, `(a :: Int) :: String ->` types a
|
|
282
|
+
function's parameters and its return value, and anything without an annotation is `Any`. The
|
|
283
|
+
annotations are checked at compile time and erased: the JavaScript is exactly what the program
|
|
284
|
+
would compile to without them, so adding types never changes behaviour or speed. Built-in types are
|
|
285
|
+
`Any`, `String`, `Int`, `Float`, `Number`, `Boolean`, `Null`, `Undefined`, `Void` and `BigInt`.
|
|
286
|
+
|
|
287
|
+
**Demonstration.**
|
|
288
|
+
```mamba
|
|
289
|
+
grab MambaScript from 'mambascript'
|
|
290
|
+
|
|
291
|
+
price :: Float = 6.5
|
|
292
|
+
label = (name :: String, qty :: Int) :: String -> "#{qty} x #{name}"
|
|
293
|
+
present label 'ramen', 2
|
|
294
|
+
present price * 2
|
|
295
|
+
|
|
296
|
+
js = MambaScript.cs2js """
|
|
297
|
+
price :: Float = 6.5
|
|
298
|
+
label = (name :: String, qty :: Int) :: String -> qty
|
|
299
|
+
""", bare: yes, typeCheck: 'off'
|
|
300
|
+
present js
|
|
301
|
+
```
|
|
302
|
+
```text
|
|
303
|
+
2 x ramen
|
|
304
|
+
13
|
|
305
|
+
// Generated by MambaScript 2.0.0
|
|
306
|
+
var label, price;
|
|
307
|
+
price = 6.5;
|
|
308
|
+
label = function (name, qty) {
|
|
309
|
+
return qty;
|
|
310
|
+
};
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### 10. Nullable and nested types: `T?`, `T[]`, `T[][]`
|
|
314
|
+
|
|
315
|
+
**Explanation.** `T?` accepts `nothing` as well as a `T`; a plain `T` does not, so `nothing`
|
|
316
|
+
assigned to an `Int` is MS2001. `T[]` is an array of `T`, and arrays nest (`String[][]`,
|
|
317
|
+
`Int[][][]`): a list literal of lists is inferred as one, a loop variable walking it is one level
|
|
318
|
+
down, and the depths must match. `T?[]` is a list of nullable elements and `T[]?` a list that may
|
|
319
|
+
itself be absent.
|
|
320
|
+
|
|
321
|
+
**Demonstration.**
|
|
322
|
+
```mamba
|
|
323
|
+
grab MambaScript from 'mambascript'
|
|
324
|
+
firstError = (source) ->
|
|
325
|
+
attempt
|
|
326
|
+
MambaScript.cs2js source, typeCheck: 'error', filename: 'menu.mamba'
|
|
327
|
+
'compiles'
|
|
328
|
+
onFail e
|
|
329
|
+
e.message.split('\n')[0]
|
|
330
|
+
|
|
331
|
+
discount :: Float? = nothing
|
|
332
|
+
seating :: String[][] = [['A1', 'A2'], ['B1']]
|
|
333
|
+
forEvery row in seating
|
|
334
|
+
present row.join ' '
|
|
335
|
+
present discount
|
|
336
|
+
present firstError 'tip :: Float = nothing'
|
|
337
|
+
present firstError "seats :: String[][] = ['A1']"
|
|
338
|
+
present firstError 'tips :: Int?[] = [1, nothing, 3]'
|
|
339
|
+
```
|
|
340
|
+
```text
|
|
341
|
+
A1 A2
|
|
342
|
+
B1
|
|
343
|
+
null
|
|
344
|
+
menu.mamba:1:1 TypeError tip is declared as Float, but this value is Null
|
|
345
|
+
menu.mamba:1:1 TypeError seats is declared as String[][], but this value is String[]
|
|
346
|
+
compiles
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
### 11. `struct`: named structural types
|
|
350
|
+
|
|
351
|
+
**Explanation.** `struct Name` followed by indented `member :: Type` lines names a shape. Any value
|
|
352
|
+
with those members fits it, whether it is an object literal or an instance of some blueprint:
|
|
353
|
+
typing is structural, not nominal. Members typed `T?` (or `T[]?`) are optional. A `struct`
|
|
354
|
+
produces no JavaScript at all, and it may extend others (`struct Combo implements Item, Drink`)
|
|
355
|
+
and take type parameters (`struct Pair<T>`).
|
|
356
|
+
|
|
357
|
+
**Demonstration.**
|
|
358
|
+
```mamba
|
|
359
|
+
struct Item
|
|
360
|
+
name :: String
|
|
361
|
+
price :: Float
|
|
362
|
+
note :: String?
|
|
363
|
+
|
|
364
|
+
struct Pair<T>
|
|
365
|
+
left :: T
|
|
366
|
+
right :: T
|
|
367
|
+
|
|
368
|
+
lunch :: Item = {name: 'ramen', price: 6.5}
|
|
369
|
+
dinner :: Item = {name: 'curry', price: 9, note: 'extra spicy'}
|
|
370
|
+
seats :: Pair<Int> = {left: 4, right: 7}
|
|
371
|
+
priceOf = (item :: Item) :: Float -> item.price
|
|
372
|
+
present priceOf(lunch) + priceOf(dinner)
|
|
373
|
+
present dinner.note, lunch.note
|
|
374
|
+
present seats.left + seats.right
|
|
375
|
+
```
|
|
376
|
+
```text
|
|
377
|
+
15.5
|
|
378
|
+
extra spicy undefined
|
|
379
|
+
11
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
### 12. `implements`: a blueprint must define the whole struct
|
|
383
|
+
|
|
384
|
+
**Explanation.** `blueprint Dog implements Named` asks the checker to prove that every instance has
|
|
385
|
+
every required member of the struct; leaving one out is MS2008 ("Dog implements Named but does not
|
|
386
|
+
define name"). A member counts wherever the blueprint defines it: a constructor `@` parameter, an
|
|
387
|
+
`@x = …` in any method, a method, or something inherited. Use it to pin a blueprint to the shape
|
|
388
|
+
the rest of the program expects.
|
|
389
|
+
|
|
390
|
+
**Demonstration.**
|
|
391
|
+
```mamba
|
|
392
|
+
grab MambaScript from 'mambascript'
|
|
393
|
+
|
|
394
|
+
struct Priced
|
|
395
|
+
name :: String
|
|
396
|
+
price :: Float
|
|
397
|
+
|
|
398
|
+
blueprint MenuItem implements Priced
|
|
399
|
+
constructor: (@name, @price) ->
|
|
400
|
+
|
|
401
|
+
taco = make MenuItem 'taco', 3.5
|
|
402
|
+
present "#{taco.name} costs #{taco.price}"
|
|
403
|
+
|
|
404
|
+
attempt
|
|
405
|
+
MambaScript.cs2js """
|
|
406
|
+
struct Priced
|
|
407
|
+
name :: String
|
|
408
|
+
price :: Float
|
|
409
|
+
blueprint Freebie implements Priced
|
|
410
|
+
constructor: (@name) ->
|
|
411
|
+
""", typeCheck: 'error', filename: 'menu.mamba'
|
|
412
|
+
onFail e
|
|
413
|
+
present e.message.split('\n')[0]
|
|
414
|
+
```
|
|
415
|
+
```text
|
|
416
|
+
taco costs 3.5
|
|
417
|
+
menu.mamba:4:1 TypeError Freebie implements Priced but does not define price
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
### 13. MS2009: members a type does not have
|
|
421
|
+
|
|
422
|
+
**Explanation.** Reading a member that a struct, a known blueprint instance, or `@` inside such a
|
|
423
|
+
blueprint does not have is an error: `p.z` on a `Point`, or a typo like `@nmae` in a method, is
|
|
424
|
+
MS2009 "Point has no member z". Members defined anywhere in the blueprint count, in any order, as do
|
|
425
|
+
inherited ones and ones the program assigns from outside. A blueprint that extends something the
|
|
426
|
+
checker cannot see (`Error`, `React.Component`), a plain object literal and an `Any` value stay
|
|
427
|
+
open, so ordinary dynamic code is never flagged.
|
|
428
|
+
|
|
429
|
+
**Demonstration.**
|
|
430
|
+
```mamba
|
|
431
|
+
grab MambaScript from 'mambascript'
|
|
432
|
+
firstError = (source) ->
|
|
433
|
+
attempt
|
|
434
|
+
MambaScript.cs2js source, typeCheck: 'error', filename: 'guild.mamba'
|
|
435
|
+
'compiles'
|
|
436
|
+
onFail e
|
|
437
|
+
e.message.split('\n')[0]
|
|
438
|
+
|
|
439
|
+
present firstError """
|
|
440
|
+
blueprint Player
|
|
441
|
+
constructor: (@name) ->
|
|
442
|
+
greet: -> "hi " + @nmae
|
|
443
|
+
"""
|
|
444
|
+
present firstError """
|
|
445
|
+
blueprint Player
|
|
446
|
+
constructor: (@name) ->
|
|
447
|
+
promote: -> @rank = 'captain'
|
|
448
|
+
title: -> @rank + ' ' + @name
|
|
449
|
+
"""
|
|
450
|
+
present firstError 'config = {port: 3000}\npresent config.host'
|
|
451
|
+
```
|
|
452
|
+
```text
|
|
453
|
+
guild.mamba:3:21 TypeError Player has no member nmae
|
|
454
|
+
compiles
|
|
455
|
+
compiles
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
### 14. Every branch must agree, and `Mixed`
|
|
459
|
+
|
|
460
|
+
**Explanation.** Because everything is an expression, the value of an `if`, a `consider` or a
|
|
461
|
+
comprehension can be assigned to an annotated name, and the checker requires every branch (and
|
|
462
|
+
every list member) to fit. When branches disagree the checker calls the value `Mixed`, so
|
|
463
|
+
`n :: Int = if c then 1 otherwise ''` is MS2001. A mixed list is not given that internal name: the
|
|
464
|
+
message calls it a list of mixed values and names the member types, and the fix is to make the
|
|
465
|
+
values agree or annotate the list `Any[]`. A list of objects that differ only in optional members
|
|
466
|
+
still fits.
|
|
467
|
+
|
|
468
|
+
**Demonstration.**
|
|
469
|
+
```mamba
|
|
470
|
+
grab MambaScript from 'mambascript'
|
|
471
|
+
firstError = (source) ->
|
|
472
|
+
attempt
|
|
473
|
+
MambaScript.cs2js source, typeCheck: 'error', filename: 'menu.mamba'
|
|
474
|
+
'compiles'
|
|
475
|
+
onFail e
|
|
476
|
+
e.message.split('\n')[0]
|
|
477
|
+
|
|
478
|
+
present firstError "qty :: Int = if yes then 1 otherwise 'one'"
|
|
479
|
+
present firstError "prices :: Int[] = [1, 'two']"
|
|
480
|
+
present firstError 'labels :: Int[] = ("#" + n forEvery n in [1, 2, 3])'
|
|
481
|
+
loose :: Any[] = [1, 'two', nothing]
|
|
482
|
+
present loose
|
|
483
|
+
```
|
|
484
|
+
```text
|
|
485
|
+
menu.mamba:1:1 TypeError qty is declared as Int, but this value is Mixed
|
|
486
|
+
menu.mamba:1:1 TypeError prices is declared as Int[], but this value is a list of mixed values (Int, String)
|
|
487
|
+
menu.mamba:1:1 TypeError labels is declared as Int[], but this value is String
|
|
488
|
+
[ 1, 'two', null ]
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
### 15. Function types and curried types
|
|
492
|
+
|
|
493
|
+
**Explanation.** A function type is written `(A, B) -> R` (or `A * B -> R`), and `A -> B -> C` is a
|
|
494
|
+
curried function that takes an `A` and returns a function from `B` to `C`. Annotating a variable
|
|
495
|
+
with a function type checks the arguments at every call, and a callback passed to a typed
|
|
496
|
+
parameter is checked against it. `()` is the `Void` type.
|
|
497
|
+
|
|
498
|
+
**Demonstration.**
|
|
499
|
+
```mamba
|
|
500
|
+
grab MambaScript from 'mambascript'
|
|
501
|
+
|
|
502
|
+
add :: (Int, Int) -> Int = (a, b) -> a + b
|
|
503
|
+
times :: Int * Int -> Int = (a, b) -> a * b
|
|
504
|
+
addTax :: Float -> Float -> Float = (rate) -> (price) -> price * (1 + rate)
|
|
505
|
+
present add(2, 3), times(4, 5)
|
|
506
|
+
present addTax(0.5)(10)
|
|
507
|
+
|
|
508
|
+
attempt
|
|
509
|
+
MambaScript.cs2js """
|
|
510
|
+
add :: (Int, Int) -> Int = (a, b) -> a + b
|
|
511
|
+
add 1, 'two'
|
|
512
|
+
""", typeCheck: 'error', filename: 'menu.mamba'
|
|
513
|
+
onFail e
|
|
514
|
+
present e.message.split('\n')[0]
|
|
515
|
+
```
|
|
516
|
+
```text
|
|
517
|
+
5 20
|
|
518
|
+
15
|
|
519
|
+
menu.mamba:2:1 TypeError expected Int, but this value is String
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
### 16. Generics
|
|
523
|
+
|
|
524
|
+
**Explanation.** Structs, blueprints and functions take type parameters: `struct Box<T>`,
|
|
525
|
+
`blueprint Shelf<T>` (built with `make Shelf<String>`), and a generic function declared as
|
|
526
|
+
`identity<T> :: T -> T` with its value on the next line. A call may name the type
|
|
527
|
+
(`identity<Int> 3`), and then the result has that type; called without type arguments, the
|
|
528
|
+
parameters are `Any` for that call. Like all types, the angle brackets are erased. (The one-line
|
|
529
|
+
form `identity<T> :: T -> T = (x) -> x` type-checks, but the fallback parser miscompiles it in 2.0,
|
|
530
|
+
so declare the type and the value on separate lines.)
|
|
531
|
+
Fancy tier (generics at call sites); the plain form leaves the type argument out (`identity 3`).
|
|
532
|
+
|
|
533
|
+
**Demonstration.**
|
|
534
|
+
```mamba
|
|
535
|
+
grab MambaScript from 'mambascript'
|
|
536
|
+
|
|
537
|
+
struct Box<T>
|
|
538
|
+
value :: T
|
|
539
|
+
|
|
540
|
+
blueprint Shelf<T>
|
|
541
|
+
constructor: -> @items = []
|
|
542
|
+
add: (item :: T) -> @items.push item
|
|
543
|
+
|
|
544
|
+
box :: Box<Int> = {value: 6}
|
|
545
|
+
shelf = make Shelf<String>
|
|
546
|
+
shelf.add 'ramen'
|
|
547
|
+
identity<T> :: T -> T
|
|
548
|
+
identity = (x) -> x
|
|
549
|
+
present box.value, shelf.items, identity<Int> 3
|
|
550
|
+
present identity 'no type arguments: Any'
|
|
551
|
+
|
|
552
|
+
attempt
|
|
553
|
+
MambaScript.cs2js """
|
|
554
|
+
identity<T> :: T -> T
|
|
555
|
+
identity = (x) -> x
|
|
556
|
+
name :: String = identity<Int> 3
|
|
557
|
+
""", typeCheck: 'error', filename: 'menu.mamba'
|
|
558
|
+
onFail e
|
|
559
|
+
present e.message.split('\n')[0]
|
|
560
|
+
```
|
|
561
|
+
```text
|
|
562
|
+
6 [ 'ramen' ] 3
|
|
563
|
+
no type arguments: Any
|
|
564
|
+
menu.mamba:3:1 TypeError name is declared as String, but this value is Int
|
|
565
|
+
```
|
|
566
|
+
|
|
567
|
+
### 17. BigInt and Int cannot be mixed (MS2007)
|
|
568
|
+
|
|
569
|
+
**Explanation.** A literal like `10n` has the type `BigInt`, and arithmetic that mixes a `BigInt`
|
|
570
|
+
with an `Int` is a compile-time error, because JavaScript throws a `TypeError` at run time when the
|
|
571
|
+
two kinds of number meet. The fix line says what to do: write both operands as BigInt, or convert
|
|
572
|
+
explicitly with `Number(big)` or `BigInt(n)`.
|
|
573
|
+
|
|
574
|
+
**Demonstration.**
|
|
575
|
+
```mamba
|
|
576
|
+
grab MambaScript from 'mambascript'
|
|
577
|
+
|
|
578
|
+
gold = 9_007_199_254_740_993n
|
|
579
|
+
present gold + 1n
|
|
580
|
+
present Number(10n) + 1
|
|
581
|
+
|
|
582
|
+
attempt
|
|
583
|
+
MambaScript.cs2js 'total = 10n + 1', typeCheck: 'error', filename: 'bank.mamba'
|
|
584
|
+
onFail e
|
|
585
|
+
present e.message
|
|
586
|
+
```
|
|
587
|
+
```text
|
|
588
|
+
9007199254740994n
|
|
589
|
+
11
|
|
590
|
+
bank.mamba:1:9 TypeError BigInt and Int cannot be mixed
|
|
591
|
+
|
|
592
|
+
> 1 | total = 10n + 1
|
|
593
|
+
| ^^^^^^^
|
|
594
|
+
|
|
595
|
+
JavaScript throws a TypeError when a BigInt meets a Number in arithmetic; the two kinds of number never convert on their own.
|
|
596
|
+
|
|
597
|
+
Fix: write both operands as BigInt (1n + 1n), or convert explicitly: Number(big) + 1.
|
|
598
|
+
|
|
599
|
+
See https://mambascript.org/docs/reference/errors#ms2007
|
|
600
|
+
```
|
|
601
|
+
|
|
602
|
+
### 18. Diagnostics with a Fix line
|
|
603
|
+
|
|
604
|
+
**Explanation.** Every error, from both parsers and the type checker, has one shape:
|
|
605
|
+
`file:line:column Kind headline`, a code frame with the whole span underlined, a paragraph on why
|
|
606
|
+
it is wrong, a `Fix:` built from the program's own names, and a `See` link to a stable code
|
|
607
|
+
(`MS1107`, `MS2001`, …). JavaScript habits are caught by name (`===`, `import`, `//`).
|
|
608
|
+
`mamba --json` prints the same fields as JSON for editors. With the default `warn` mode a type
|
|
609
|
+
problem goes to the `warn` callback and the compile continues.
|
|
610
|
+
|
|
611
|
+
**Demonstration.**
|
|
612
|
+
```mamba
|
|
613
|
+
grab MambaScript from 'mambascript'
|
|
614
|
+
|
|
615
|
+
attempt
|
|
616
|
+
MambaScript.cs2js 'total = 0\nif total === 0 then present total', filename: 'cart.mamba'
|
|
617
|
+
onFail e
|
|
618
|
+
present e.message
|
|
619
|
+
|
|
620
|
+
warnings = []
|
|
621
|
+
MambaScript.cs2js "qty :: Int = 'two'", filename: 'cart.mamba', warn: (message) -> warnings.push message
|
|
622
|
+
present warnings.length, 'warning; the compile still finished'
|
|
623
|
+
```
|
|
624
|
+
```text
|
|
625
|
+
cart.mamba:2:10 SyntaxError === is JavaScript; MambaScript spells it is
|
|
626
|
+
|
|
627
|
+
1 | total = 0
|
|
628
|
+
> 2 | if total === 0 then present total
|
|
629
|
+
| ^^^
|
|
630
|
+
|
|
631
|
+
Every comparison in MambaScript is strict, so there is no separate === spelling: is (and the two-character ==) compile to ===.
|
|
632
|
+
|
|
633
|
+
Fix: write a is b.
|
|
634
|
+
|
|
635
|
+
See https://mambascript.org/docs/reference/errors#ms1124
|
|
636
|
+
1 warning; the compile still finished
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
## Control flow
|
|
640
|
+
|
|
641
|
+
### 19. Everything is an expression
|
|
642
|
+
|
|
643
|
+
**Explanation.** `if`, `consider`, `attempt` and loops all produce values, so they can sit on the
|
|
644
|
+
right of `=`, be passed as arguments, or end a function (whose last expression is returned). An
|
|
645
|
+
`if` without an `otherwise` gives `missing` when the test fails, and a loop used as a value
|
|
646
|
+
collects its body into a list. The compiler turns statements into expressions only where a value
|
|
647
|
+
is actually used, so a plain `if` statement still compiles to a plain `if`.
|
|
648
|
+
|
|
649
|
+
**Demonstration.**
|
|
650
|
+
```mamba
|
|
651
|
+
order = {total: 42, paid: yes}
|
|
652
|
+
|
|
653
|
+
status = if order.paid then 'ready to cook' otherwise 'awaiting payment'
|
|
654
|
+
size = consider
|
|
655
|
+
when order.total > 100 then 'large'
|
|
656
|
+
when order.total > 20 then 'medium'
|
|
657
|
+
otherwise 'small'
|
|
658
|
+
parsed = attempt JSON.parse '{"table": 4}' onFail then {table: 0}
|
|
659
|
+
doubled = forEvery n in [1, 2, 3]
|
|
660
|
+
n * 2
|
|
661
|
+
present status, size, parsed.table, doubled
|
|
662
|
+
present (if no then 'never')
|
|
663
|
+
```
|
|
664
|
+
```text
|
|
665
|
+
ready to cook medium 4 [ 2, 4, 6 ]
|
|
666
|
+
undefined
|
|
667
|
+
```
|
|
668
|
+
|
|
669
|
+
### 20. `if`, `unless`, `otherwise` and postfix conditions
|
|
670
|
+
|
|
671
|
+
**Explanation.** `if c then a otherwise b` fits on one line; the block form indents the branches
|
|
672
|
+
and `otherwise` (or `else`) introduces the last one. `unless c` is `if not c`. Any statement can
|
|
673
|
+
take its condition after it (`present x if ready`), which reads well for guards. Quirk: a postfix
|
|
674
|
+
loop written after a one-line `if … then a otherwise b` attaches to the `otherwise` branch only, so
|
|
675
|
+
parenthesise the `if` or write a block loop.
|
|
676
|
+
|
|
677
|
+
**Demonstration.**
|
|
678
|
+
```mamba
|
|
679
|
+
stock = {ramen: 3, udon: 0}
|
|
680
|
+
|
|
681
|
+
forEvery dish in ['ramen', 'udon', 'soba']
|
|
682
|
+
if stock[dish] > 0
|
|
683
|
+
present "#{dish}: #{stock[dish]} left"
|
|
684
|
+
otherwise if stock[dish] is 0
|
|
685
|
+
present "#{dish}: sold out"
|
|
686
|
+
otherwise
|
|
687
|
+
present "#{dish}: not on the menu"
|
|
688
|
+
|
|
689
|
+
present 'restock udon' unless stock.udon > 0
|
|
690
|
+
present 'ramen is popular' if stock.ramen < 5
|
|
691
|
+
labels = ((if n > 1 then 'many' otherwise 'one') forEvery n in [1, 2])
|
|
692
|
+
present labels
|
|
693
|
+
```
|
|
694
|
+
```text
|
|
695
|
+
ramen: 3 left
|
|
696
|
+
udon: sold out
|
|
697
|
+
soba: not on the menu
|
|
698
|
+
restock udon
|
|
699
|
+
ramen is popular
|
|
700
|
+
[ 'one', 'many' ]
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### 21. `consider`: a switch without fallthrough
|
|
704
|
+
|
|
705
|
+
**Explanation.** `consider value` with `when a, b then …` branches and an `otherwise` compiles to a
|
|
706
|
+
`switch` in which every branch ends on its own: there is no fallthrough and no `break` to forget.
|
|
707
|
+
One `when` may list several values. `consider` with no subject tests each `when` as a boolean,
|
|
708
|
+
which replaces an `if`/`otherwise if` ladder. Comparison is strict (`===`).
|
|
709
|
+
Fancy tier (`consider` without a subject, `when a, b then`); the plain form is an `if` / `otherwise if` / `otherwise` ladder.
|
|
710
|
+
|
|
711
|
+
**Demonstration.**
|
|
712
|
+
```mamba
|
|
713
|
+
describeRank = (rank) ->
|
|
714
|
+
consider rank
|
|
715
|
+
when 'S', 'A' then 'elite'
|
|
716
|
+
when 'B' then 'veteran'
|
|
717
|
+
otherwise 'recruit'
|
|
718
|
+
|
|
719
|
+
describeLevel = (level) ->
|
|
720
|
+
consider
|
|
721
|
+
when level >= 50 then 'guild master'
|
|
722
|
+
when level >= 10 then 'adventurer'
|
|
723
|
+
otherwise 'novice'
|
|
724
|
+
|
|
725
|
+
present describeRank('A'), describeRank('B'), describeRank('Z')
|
|
726
|
+
present describeLevel(60), describeLevel(12), describeLevel(1)
|
|
727
|
+
present describeRank 'a' # strict and case-sensitive
|
|
728
|
+
```
|
|
729
|
+
```text
|
|
730
|
+
elite veteran recruit
|
|
731
|
+
guild master adventurer novice
|
|
732
|
+
recruit
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
### 22. `bail` inside `consider` leaves the `consider`
|
|
736
|
+
|
|
737
|
+
**Explanation.** Because `consider` compiles to a JavaScript `switch`, a `bail` (break) inside a
|
|
738
|
+
`when` leaves the `consider`, not the loop around it. This is the most common surprise for people
|
|
739
|
+
coming from other languages. To stop the loop from inside a `consider`, label the loop and write
|
|
740
|
+
`bail label` (see the next feature), or set a flag and test it after the `consider`.
|
|
741
|
+
|
|
742
|
+
**Demonstration.**
|
|
743
|
+
```mamba
|
|
744
|
+
commands = ['move', 'quit', 'move', 'move']
|
|
745
|
+
|
|
746
|
+
steps = 0
|
|
747
|
+
forEvery command in commands
|
|
748
|
+
consider command
|
|
749
|
+
when 'move' then steps += 1
|
|
750
|
+
when 'quit' then bail # leaves only the consider
|
|
751
|
+
present 'without a label:', steps
|
|
752
|
+
|
|
753
|
+
steps = 0
|
|
754
|
+
reading: forEvery command in commands
|
|
755
|
+
consider command
|
|
756
|
+
when 'move' then steps += 1
|
|
757
|
+
when 'quit' then bail reading # leaves the loop
|
|
758
|
+
present 'with a label:', steps
|
|
759
|
+
```
|
|
760
|
+
```text
|
|
761
|
+
without a label: 3
|
|
762
|
+
with a label: 1
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
### 23. Labeled loops: `bail name` and `keepGoing name`
|
|
766
|
+
|
|
767
|
+
**Explanation.** Writing `name:` before a `forEvery`, `while`, `until` or `loop` on its own line
|
|
768
|
+
labels it, and `bail name` (break) or `keepGoing name` (continue) acts on that loop from inside a
|
|
769
|
+
nested one. `bail name` outside the loop it names is MS1131. Quirk: the line is read as an object
|
|
770
|
+
with one member whose value is a loop, so as the last line of a function it stays an object; put a
|
|
771
|
+
result line after a labeled loop that ends a function.
|
|
772
|
+
Fancy tier; the plain form sets a `found` flag and tests it after the inner loop.
|
|
773
|
+
|
|
774
|
+
**Demonstration.**
|
|
775
|
+
```mamba
|
|
776
|
+
grid = [
|
|
777
|
+
['.', '.', '.']
|
|
778
|
+
['.', 'T', '.']
|
|
779
|
+
['.', '.', 'T']
|
|
780
|
+
]
|
|
781
|
+
findTreasure = (grid) ->
|
|
782
|
+
found = nothing
|
|
783
|
+
rows: forEvery row, r in grid
|
|
784
|
+
forEvery cell, c in row
|
|
785
|
+
keepGoing rows if r is 0 # skip the whole first row
|
|
786
|
+
if cell is 'T'
|
|
787
|
+
found = [r, c]
|
|
788
|
+
bail rows
|
|
789
|
+
found
|
|
790
|
+
present findTreasure grid
|
|
791
|
+
```
|
|
792
|
+
```text
|
|
793
|
+
[ 1, 1 ]
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
### 24. Ranges, `by`, and the `[1...n]` quirk
|
|
797
|
+
|
|
798
|
+
**Explanation.** `[a..b]` includes `b`, `[a...b]` stops before it, and `by step` sets the stride;
|
|
799
|
+
in a loop a range compiles to a counted `for`, not an array. Without `by`, a range whose bounds are
|
|
800
|
+
variables picks its direction at run time, so `[1...n]` with `n = 0` counts down and visits `1`
|
|
801
|
+
once. Writing `by 1` pins the direction: it then runs zero times. A step with the wrong sign gives
|
|
802
|
+
no iterations, never an endless loop.
|
|
803
|
+
|
|
804
|
+
**Demonstration.**
|
|
805
|
+
```mamba
|
|
806
|
+
present (n forEvery n in [1..5])
|
|
807
|
+
present (n forEvery n in [1...5])
|
|
808
|
+
present (n forEvery n in [0..10] by 5)
|
|
809
|
+
present (n forEvery n in [3..1])
|
|
810
|
+
|
|
811
|
+
n = 0
|
|
812
|
+
present 'no by:', (i forEvery i in [1...n])
|
|
813
|
+
present 'by 1:', (i forEvery i in [1...n] by 1)
|
|
814
|
+
present 'wrong sign:', (i forEvery i in [1..5] by -1)
|
|
815
|
+
present 'from the end:', (dish forEvery dish in ['ramen', 'udon', 'soba'] by -1)
|
|
816
|
+
```
|
|
817
|
+
```text
|
|
818
|
+
[ 1, 2, 3, 4, 5 ]
|
|
819
|
+
[ 1, 2, 3, 4 ]
|
|
820
|
+
[ 0, 5, 10 ]
|
|
821
|
+
[ 3, 2, 1 ]
|
|
822
|
+
no by: [ 1 ]
|
|
823
|
+
by 1: []
|
|
824
|
+
wrong sign: []
|
|
825
|
+
from the end: [ 'soba', 'udon', 'ramen' ]
|
|
826
|
+
```
|
|
827
|
+
|
|
828
|
+
### 25. `forEvery` over lists and objects
|
|
829
|
+
|
|
830
|
+
**Explanation.** `forEvery x in list` walks an array (`forEvery x, i in list` adds the index),
|
|
831
|
+
`forEvery key, value of object` walks keys like `for … in`, and `forEvery own key of object` skips
|
|
832
|
+
inherited keys. A `when` clause filters the iterations. `for` is a synonym of `forEvery`. Use `in`
|
|
833
|
+
for arrays and `of` for objects; walking any other iterable is `from` (feature 61).
|
|
834
|
+
|
|
835
|
+
**Demonstration.**
|
|
836
|
+
```mamba
|
|
837
|
+
guild = ['Ana', 'Ben', 'Cy', 'Dee']
|
|
838
|
+
forEvery member, i in guild when i % 2 is 0
|
|
839
|
+
present "#{i}: #{member}"
|
|
840
|
+
|
|
841
|
+
base = {gold: 10}
|
|
842
|
+
loot = Object.create base
|
|
843
|
+
loot.gems = 3
|
|
844
|
+
loot.herbs = 7
|
|
845
|
+
forEvery key, amount of loot
|
|
846
|
+
present 'of:', key, amount
|
|
847
|
+
forEvery own key, amount of loot
|
|
848
|
+
present 'own:', key, amount
|
|
849
|
+
```
|
|
850
|
+
```text
|
|
851
|
+
0: Ana
|
|
852
|
+
2: Cy
|
|
853
|
+
of: gems 3
|
|
854
|
+
of: herbs 7
|
|
855
|
+
of: gold 10
|
|
856
|
+
own: gems 3
|
|
857
|
+
own: herbs 7
|
|
858
|
+
```
|
|
859
|
+
|
|
860
|
+
### 26. `while`, `until`, `loop` and `keepGoing`
|
|
861
|
+
|
|
862
|
+
**Explanation.** `while c` repeats while the test holds, `until c` while it does not, and `loop`
|
|
863
|
+
forever (it compiles to `while (true)`), leaving with `bail`. `keepGoing` (continue) skips to the
|
|
864
|
+
next iteration. Each of them also takes a postfix form (`x *= 2 until x > 100`). `break` and
|
|
865
|
+
`continue` remain available, but the words say what happens.
|
|
866
|
+
|
|
867
|
+
**Demonstration.**
|
|
868
|
+
```mamba
|
|
869
|
+
energy = 3
|
|
870
|
+
while energy > 0
|
|
871
|
+
energy -= 1
|
|
872
|
+
present 'energy left:', energy
|
|
873
|
+
|
|
874
|
+
gold = 1
|
|
875
|
+
gold *= 2 until gold > 100
|
|
876
|
+
present 'gold:', gold
|
|
877
|
+
|
|
878
|
+
turn = 0
|
|
879
|
+
loop
|
|
880
|
+
turn += 1
|
|
881
|
+
keepGoing if turn % 2 is 0
|
|
882
|
+
bail if turn > 5
|
|
883
|
+
present 'odd turn', turn
|
|
884
|
+
```
|
|
885
|
+
```text
|
|
886
|
+
energy left: 0
|
|
887
|
+
gold: 128
|
|
888
|
+
odd turn 1
|
|
889
|
+
odd turn 3
|
|
890
|
+
odd turn 5
|
|
891
|
+
```
|
|
892
|
+
|
|
893
|
+
### 27. `attempt`, `onFail`, `regardless` and `panic 'x'`
|
|
894
|
+
|
|
895
|
+
**Explanation.** `attempt` / `onFail e` / `regardless` are `try` / `catch` / `finally`; `onFail`
|
|
896
|
+
may omit the name. `panic value` throws, and a string (or interpolated string) operand becomes
|
|
897
|
+
`new Error(...)`, so `panic 'out of stock'` gives a real `Error` with a stack. Anything else is
|
|
898
|
+
thrown as it is. `regardless` runs whether or not anything failed, and its last line is not the
|
|
899
|
+
value of the `attempt`.
|
|
900
|
+
|
|
901
|
+
**Demonstration.**
|
|
902
|
+
```mamba
|
|
903
|
+
placeOrder = (dish, stock) ->
|
|
904
|
+
panic "#{dish} is out of stock" if stock[dish] is 0
|
|
905
|
+
panic {code: 404} unless stock[dish]?
|
|
906
|
+
"#{dish} ordered"
|
|
907
|
+
|
|
908
|
+
forEvery dish in ['ramen', 'udon', 'soba']
|
|
909
|
+
attempt
|
|
910
|
+
present placeOrder dish, {ramen: 2, udon: 0}
|
|
911
|
+
onFail problem
|
|
912
|
+
if problem areYouA Error
|
|
913
|
+
present 'Error:', problem.message
|
|
914
|
+
otherwise
|
|
915
|
+
present 'code:', problem.code
|
|
916
|
+
regardless
|
|
917
|
+
present 'closing ticket for', dish
|
|
918
|
+
```
|
|
919
|
+
```text
|
|
920
|
+
ramen ordered
|
|
921
|
+
closing ticket for ramen
|
|
922
|
+
Error: udon is out of stock
|
|
923
|
+
closing ticket for udon
|
|
924
|
+
code: 404
|
|
925
|
+
closing ticket for soba
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
### 28. Word operators and chained comparisons
|
|
929
|
+
|
|
930
|
+
**Explanation.** `is`, `isnt` (or `aint`), `and` (or `also`), `or` and `not` are the comparison and
|
|
931
|
+
logic words; `is` is always strict (`===`) and there is no loose equality. `a < b < c` chains, and
|
|
932
|
+
compiles to `a < b and b < c` with `b` evaluated once. `x in list` tests array membership and
|
|
933
|
+
`object has 'key'` (or `'key' of object`) tests for a key. Compound assignment works with the words
|
|
934
|
+
too: `ready also= checked`.
|
|
935
|
+
Fancy tier (chained comparisons); the plain form is `10 <= level and level < 20`.
|
|
936
|
+
|
|
937
|
+
**Demonstration.**
|
|
938
|
+
```mamba
|
|
939
|
+
level = 12
|
|
940
|
+
present 10 <= level < 20
|
|
941
|
+
present level is 12, level isnt 12, level aint '12'
|
|
942
|
+
present not (level > 50) and (level > 1 or no)
|
|
943
|
+
|
|
944
|
+
role = 'healer'
|
|
945
|
+
present role in ['tank', 'healer', 'mage']
|
|
946
|
+
player = {name: 'Mia', guild: nothing}
|
|
947
|
+
present player has 'guild', 'title' of player
|
|
948
|
+
ready = yes
|
|
949
|
+
ready also= level > 20
|
|
950
|
+
present ready
|
|
951
|
+
```
|
|
952
|
+
```text
|
|
953
|
+
true
|
|
954
|
+
true false true
|
|
955
|
+
true
|
|
956
|
+
true
|
|
957
|
+
true false
|
|
958
|
+
false
|
|
959
|
+
```
|
|
960
|
+
|
|
961
|
+
## Arrays
|
|
962
|
+
|
|
963
|
+
### 29. Comprehensions
|
|
964
|
+
|
|
965
|
+
**Explanation.** A loop in parentheses used as a value collects its body into a new list:
|
|
966
|
+
`(dish.name forEvery dish in menu when dish.vegan)` is a map and a filter in one sentence. It also works over
|
|
967
|
+
ranges and iterables with `from`. For object key/value pairs, use an explicit `forEvery own`
|
|
968
|
+
block; the postfix key/value form is not supported with the native spelling.
|
|
969
|
+
Two `forEvery` loops nest: `([r, c] forEvery c in cols forEvery r in rows)` gives a list of lists. Use a comprehension
|
|
970
|
+
when it reads as one sentence; when the body grows past a line, write a block loop.
|
|
971
|
+
Fancy tier beyond the simple form (nested and object comprehensions); the plain form is a `forEvery` loop that pushes onto a list.
|
|
972
|
+
|
|
973
|
+
**Demonstration.**
|
|
974
|
+
```mamba
|
|
975
|
+
menu = [
|
|
976
|
+
{name: 'ramen', price: 9, vegan: no}
|
|
977
|
+
{name: 'tofu bowl', price: 7, vegan: yes}
|
|
978
|
+
{name: 'salad', price: 5, vegan: yes}
|
|
979
|
+
]
|
|
980
|
+
present (dish.name forEvery dish in menu when dish.vegan)
|
|
981
|
+
present (dish.price * 2 forEvery dish in menu)
|
|
982
|
+
stock = {ramen: 0, tofu: 4, salad: 2}
|
|
983
|
+
available = []
|
|
984
|
+
forEvery own name, count of stock when count > 0
|
|
985
|
+
available.push name
|
|
986
|
+
present available
|
|
987
|
+
present ("#{row}#{seat}" forEvery seat in [1..2] forEvery row in ['A', 'B'])
|
|
988
|
+
```
|
|
989
|
+
```text
|
|
990
|
+
[ 'tofu bowl', 'salad' ]
|
|
991
|
+
[ 18, 14, 10 ]
|
|
992
|
+
[ 'tofu', 'salad' ]
|
|
993
|
+
[ [ 'A1', 'A2' ], [ 'B1', 'B2' ] ]
|
|
994
|
+
```
|
|
995
|
+
|
|
996
|
+
### 30. Slices: `list[1..3]`, `list[-2..]`, `text[0...4]`
|
|
997
|
+
|
|
998
|
+
**Explanation.** Ranges inside brackets slice: `[a..b]` includes `b`, `[a...b]` excludes it,
|
|
999
|
+
`[a..]` runs to the end and negative numbers count from the end. Strings slice the same way. A
|
|
1000
|
+
slice is always a copy (`list[..]` clones), so the original is never touched. Quirk: assigning to
|
|
1001
|
+
a slice (`list[1..2] = x`) is not supported (MS1105); replace a stretch with
|
|
1002
|
+
`list.splice 1, 2, x...`.
|
|
1003
|
+
Fancy tier (ranges as slices); the plain form is `queue.slice 1, 4`.
|
|
1004
|
+
|
|
1005
|
+
**Demonstration.**
|
|
1006
|
+
```mamba
|
|
1007
|
+
queue = ['Ana', 'Ben', 'Cy', 'Dee', 'Eve']
|
|
1008
|
+
present queue[1..3]
|
|
1009
|
+
present queue[1...3]
|
|
1010
|
+
present queue[3..]
|
|
1011
|
+
present queue[-2..]
|
|
1012
|
+
copy = queue[..]
|
|
1013
|
+
copy.push 'Fay'
|
|
1014
|
+
present queue.length, copy.length
|
|
1015
|
+
present 'MambaScript'[0...5]
|
|
1016
|
+
queue.splice 1, 2, 'Bo', 'Cass'
|
|
1017
|
+
present queue
|
|
1018
|
+
```
|
|
1019
|
+
```text
|
|
1020
|
+
[ 'Ben', 'Cy', 'Dee' ]
|
|
1021
|
+
[ 'Ben', 'Cy' ]
|
|
1022
|
+
[ 'Dee', 'Eve' ]
|
|
1023
|
+
[ 'Dee', 'Eve' ]
|
|
1024
|
+
5 6
|
|
1025
|
+
Mamba
|
|
1026
|
+
[ 'Ana', 'Bo', 'Cass', 'Dee', 'Eve' ]
|
|
1027
|
+
```
|
|
1028
|
+
|
|
1029
|
+
### 31. Spread with dots after: `f args...`, `[a..., b...]`
|
|
1030
|
+
|
|
1031
|
+
**Explanation.** Spreading is written with the dots after the value: `f args...` in a call,
|
|
1032
|
+
`[first..., second...]` in a list. A spread value may be any iterable or array-like (an array, a
|
|
1033
|
+
string, a `Set`, a `Map`'s `values()`, a generator, `arguments`), because it compiles to
|
|
1034
|
+
`Array.from(value)`. That makes spreading a `Set` (`[dishes...]`) the shortest way to remove duplicates.
|
|
1035
|
+
|
|
1036
|
+
**Demonstration.**
|
|
1037
|
+
```mamba
|
|
1038
|
+
starters = ['edamame', 'gyoza']
|
|
1039
|
+
mains = ['ramen', 'udon']
|
|
1040
|
+
present [starters..., mains..., 'mochi']
|
|
1041
|
+
|
|
1042
|
+
scores = [12, 40, 7]
|
|
1043
|
+
present Math.max scores...
|
|
1044
|
+
dishes = make Set ['ramen', 'udon', 'ramen']
|
|
1045
|
+
present [dishes...]
|
|
1046
|
+
present ['taco'...]
|
|
1047
|
+
|
|
1048
|
+
prices = make Map [['ramen', 9], ['udon', 8]]
|
|
1049
|
+
present [prices.values()...]
|
|
1050
|
+
countdown = -> yield n forEvery n in [3..1]; return
|
|
1051
|
+
present [countdown()...]
|
|
1052
|
+
```
|
|
1053
|
+
```text
|
|
1054
|
+
[ 'edamame', 'gyoza', 'ramen', 'udon', 'mochi' ]
|
|
1055
|
+
40
|
|
1056
|
+
[ 'ramen', 'udon' ]
|
|
1057
|
+
[ 't', 'a', 'c', 'o' ]
|
|
1058
|
+
[ 9, 8 ]
|
|
1059
|
+
[ 3, 2, 1 ]
|
|
1060
|
+
```
|
|
1061
|
+
|
|
1062
|
+
### 32. Array destructuring with rest, swaps and skipped places
|
|
1063
|
+
|
|
1064
|
+
**Explanation.** `[a, b] = list` takes a list apart, `[first, rest...] = list` collects the rest,
|
|
1065
|
+
and the rest may sit in the middle: `[head, middle..., last]`. `[a, b] = [b, a]` swaps two
|
|
1066
|
+
variables. There are no holes (`[a, , b]` is an error): name the place you skip, for example
|
|
1067
|
+
`unusedItem`. Reserve `_` for the standard library in every program. Binding it in a pattern,
|
|
1068
|
+
parameter or loop can suppress automatic library loading elsewhere in the file.
|
|
1069
|
+
|
|
1070
|
+
**Demonstration.**
|
|
1071
|
+
```mamba
|
|
1072
|
+
podium = ['Ana', 'Ben', 'Cy', 'Dee', 'Eve']
|
|
1073
|
+
[gold, silver, others...] = podium
|
|
1074
|
+
present gold, silver, others
|
|
1075
|
+
[first, middle..., last] = podium
|
|
1076
|
+
present first, middle.length, last
|
|
1077
|
+
[winner, skip, third] = podium
|
|
1078
|
+
present winner, third
|
|
1079
|
+
|
|
1080
|
+
left = 'sword'
|
|
1081
|
+
right = 'shield'
|
|
1082
|
+
[left, right] = [right, left]
|
|
1083
|
+
present left, right
|
|
1084
|
+
```
|
|
1085
|
+
```text
|
|
1086
|
+
Ana Ben [ 'Cy', 'Dee', 'Eve' ]
|
|
1087
|
+
Ana 3 Eve
|
|
1088
|
+
Ana Cy
|
|
1089
|
+
shield sword
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
### 33. Defaults in array patterns and loop variables
|
|
1093
|
+
|
|
1094
|
+
**Explanation.** A pattern member may carry a default: `[name, qty = 1] = order`. The default
|
|
1095
|
+
applies when the value is `nothing` or `missing` (the same rule as parameter defaults), so a `null`
|
|
1096
|
+
in the data is replaced too, unlike JavaScript, where only `undefined` triggers a default.
|
|
1097
|
+
Defaults work in loop variables as well, which makes uneven rows easy to walk.
|
|
1098
|
+
|
|
1099
|
+
**Demonstration.**
|
|
1100
|
+
```mamba
|
|
1101
|
+
orders = [
|
|
1102
|
+
['ramen', 2, 'no egg']
|
|
1103
|
+
['udon']
|
|
1104
|
+
['soba', nothing, nothing]
|
|
1105
|
+
]
|
|
1106
|
+
forEvery [dish, qty = 1, note = 'none'] in orders
|
|
1107
|
+
present "#{qty} x #{dish} (#{note})"
|
|
1108
|
+
|
|
1109
|
+
[size = 'regular', spice = 'mild'] = [nothing]
|
|
1110
|
+
present size, spice
|
|
1111
|
+
```
|
|
1112
|
+
```text
|
|
1113
|
+
2 x ramen (no egg)
|
|
1114
|
+
1 x udon (none)
|
|
1115
|
+
1 x soba (none)
|
|
1116
|
+
regular mild
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
### 34. Leading-dot chains
|
|
1120
|
+
|
|
1121
|
+
**Explanation.** A line that starts with `.` continues the expression above, so a pipeline can be
|
|
1122
|
+
laid out one step per line. Quirk: the dot attaches to the innermost expression, so after a callback
|
|
1123
|
+
written without parentheses (`.map (x) -> x * 2`) the next `.filter` would attach to `x * 2`.
|
|
1124
|
+
Wrap every callback in a chain in parentheses: `.map((x) -> x * 2)`. The fallback parser also
|
|
1125
|
+
needs parentheses for an implicit call on a continuation line (`.join(', ')`).
|
|
1126
|
+
These native array methods demonstrate continuation syntax; ordinary collection transformations
|
|
1127
|
+
prefer the bundled helpers shown in feature 78.
|
|
1128
|
+
|
|
1129
|
+
**Demonstration.**
|
|
1130
|
+
```mamba
|
|
1131
|
+
orders = [
|
|
1132
|
+
{dish: 'ramen', qty: 2, price: 9}
|
|
1133
|
+
{dish: 'udon', qty: 1, price: 8}
|
|
1134
|
+
{dish: 'mochi', qty: 3, price: 2}
|
|
1135
|
+
]
|
|
1136
|
+
receipt = orders
|
|
1137
|
+
.filter((order) -> order.price > 5)
|
|
1138
|
+
.map((order) -> "#{order.qty} x #{order.dish}")
|
|
1139
|
+
.join(', ')
|
|
1140
|
+
present receipt
|
|
1141
|
+
|
|
1142
|
+
total = orders
|
|
1143
|
+
.map((order) -> order.qty * order.price)
|
|
1144
|
+
.reduce(((sum, cost) -> sum + cost), 0)
|
|
1145
|
+
present total
|
|
1146
|
+
```
|
|
1147
|
+
```text
|
|
1148
|
+
2 x ramen, 1 x udon
|
|
1149
|
+
32
|
|
1150
|
+
```
|
|
1151
|
+
|
|
1152
|
+
### 35. A function that ends in a loop returns a list
|
|
1153
|
+
|
|
1154
|
+
**Explanation.** The last expression of a function is its value, and a loop is an expression, so a
|
|
1155
|
+
function whose last statement is a loop returns the list of the loop body's values. That is handy
|
|
1156
|
+
(`squares` below needs no accumulator) and occasionally surprising: a function meant
|
|
1157
|
+
only for its effects quietly builds a list. End such a function with a bare `return` (or a result
|
|
1158
|
+
line) when the collected list is not wanted; it also saves the work of building it.
|
|
1159
|
+
|
|
1160
|
+
**Demonstration.**
|
|
1161
|
+
```mamba
|
|
1162
|
+
squares = (n) ->
|
|
1163
|
+
forEvery i in [1..n]
|
|
1164
|
+
i * i
|
|
1165
|
+
|
|
1166
|
+
announce = (names) ->
|
|
1167
|
+
forEvery name in names
|
|
1168
|
+
present "welcome, #{name}"
|
|
1169
|
+
|
|
1170
|
+
announceQuietly = (names) ->
|
|
1171
|
+
forEvery name in names
|
|
1172
|
+
present "hello, #{name}"
|
|
1173
|
+
return
|
|
1174
|
+
|
|
1175
|
+
present squares 4
|
|
1176
|
+
present announce ['Ana', 'Ben']
|
|
1177
|
+
present announceQuietly ['Cy']
|
|
1178
|
+
```
|
|
1179
|
+
```text
|
|
1180
|
+
[ 1, 4, 9, 16 ]
|
|
1181
|
+
welcome, Ana
|
|
1182
|
+
welcome, Ben
|
|
1183
|
+
[ undefined, undefined ]
|
|
1184
|
+
hello, Cy
|
|
1185
|
+
undefined
|
|
1186
|
+
```
|
|
1187
|
+
|
|
1188
|
+
### 36. Grids: lists of lists
|
|
1189
|
+
|
|
1190
|
+
**Explanation.** Nested lists are written one row per line with no commas between the rows, and
|
|
1191
|
+
nested comprehensions build or transform them: the inner loop of `(f(cell) forEvery cell in row)` sits
|
|
1192
|
+
inside the outer `forEvery row in grid`. Indexing is ordinary (`grid[r][c]`), and `forEvery row, r in
|
|
1193
|
+
grid` gives both the row and its number. This is the shape of every board, map and seating chart in
|
|
1194
|
+
the course.
|
|
1195
|
+
Fancy tier (nested comprehensions); the plain form is two nested `forEvery` loops pushing rows.
|
|
1196
|
+
|
|
1197
|
+
**Demonstration.**
|
|
1198
|
+
```mamba
|
|
1199
|
+
seating = [
|
|
1200
|
+
['Ana', 'Ben', nothing]
|
|
1201
|
+
[nothing, 'Cy', 'Dee']
|
|
1202
|
+
]
|
|
1203
|
+
taken = ((if seat? then 'X' otherwise '.') forEvery seat in row forEvery row in seating)
|
|
1204
|
+
forEvery row in taken
|
|
1205
|
+
present row.join ' '
|
|
1206
|
+
|
|
1207
|
+
transpose = (grid) -> ((row[c] forEvery row in grid) forEvery c in [0...grid[0].length])
|
|
1208
|
+
present transpose [[1, 2, 3], [4, 5, 6]]
|
|
1209
|
+
present seating[1][2]
|
|
1210
|
+
```
|
|
1211
|
+
```text
|
|
1212
|
+
X X .
|
|
1213
|
+
. X X
|
|
1214
|
+
[ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
|
|
1215
|
+
Dee
|
|
1216
|
+
```
|
|
1217
|
+
|
|
1218
|
+
## Objects
|
|
1219
|
+
|
|
1220
|
+
### 37. Implicit objects, shorthand and braceless calls
|
|
1221
|
+
|
|
1222
|
+
**Explanation.** An object can be written without braces, one `key: value` per indented line, like
|
|
1223
|
+
YAML; nested objects simply indent further. `{name, level}` is shorthand for
|
|
1224
|
+
`{name: name, level: level}`. A call whose last argument is an object can drop both the
|
|
1225
|
+
parentheses and the braces (`register name: 'Mia', level: 3`), and an implicit object may continue
|
|
1226
|
+
on the indented lines below a call. Quirk: an implicit object runs to the end of its line, so when
|
|
1227
|
+
the object is not the last argument, give it braces (`f {a: 1}, next`).
|
|
1228
|
+
|
|
1229
|
+
**Demonstration.**
|
|
1230
|
+
```mamba
|
|
1231
|
+
register = (player) -> "#{player.name} joins at level #{player.level}"
|
|
1232
|
+
present register name: 'Mia', level: 3
|
|
1233
|
+
|
|
1234
|
+
name = 'Ben'
|
|
1235
|
+
level = 7
|
|
1236
|
+
present register {name, level}
|
|
1237
|
+
|
|
1238
|
+
guild =
|
|
1239
|
+
name: 'Night Owls'
|
|
1240
|
+
leader:
|
|
1241
|
+
name: 'Cy'
|
|
1242
|
+
class: 'mage'
|
|
1243
|
+
members: 12
|
|
1244
|
+
present guild.leader.class, guild.members
|
|
1245
|
+
```
|
|
1246
|
+
```text
|
|
1247
|
+
Mia joins at level 3
|
|
1248
|
+
Ben joins at level 7
|
|
1249
|
+
mage 12
|
|
1250
|
+
```
|
|
1251
|
+
|
|
1252
|
+
### 38. Object spread: `{defaults..., options..., key: value}`
|
|
1253
|
+
|
|
1254
|
+
**Explanation.** `expression...` inside an object literal copies that object's own enumerable keys
|
|
1255
|
+
in place, in source order, shallowly, with later keys winning; it compiles to `Object.assign({}, …)`.
|
|
1256
|
+
Spreading `nothing` or `missing` adds nothing, so optional overrides need no guard. Objects written
|
|
1257
|
+
in place and parenthesised expressions spread too (`{{a: 1}..., b: 2}`). The dots go after the
|
|
1258
|
+
expression; `{...a}` is MS1128 with a hint.
|
|
1259
|
+
|
|
1260
|
+
**Demonstration.**
|
|
1261
|
+
```mamba
|
|
1262
|
+
defaults = {spice: 'mild', size: 'regular', drink: 'tea'}
|
|
1263
|
+
order = {size: 'large'}
|
|
1264
|
+
noOverrides = nothing
|
|
1265
|
+
|
|
1266
|
+
ticket = {defaults..., order..., noOverrides..., table: 4}
|
|
1267
|
+
present ticket
|
|
1268
|
+
present defaults.size
|
|
1269
|
+
present {{extraEgg: yes}..., ticket...}
|
|
1270
|
+
```
|
|
1271
|
+
```text
|
|
1272
|
+
{ spice: 'mild', size: 'large', drink: 'tea', table: 4 }
|
|
1273
|
+
regular
|
|
1274
|
+
{
|
|
1275
|
+
extraEgg: true,
|
|
1276
|
+
spice: 'mild',
|
|
1277
|
+
size: 'large',
|
|
1278
|
+
drink: 'tea',
|
|
1279
|
+
table: 4
|
|
1280
|
+
}
|
|
1281
|
+
```
|
|
1282
|
+
|
|
1283
|
+
### 39. Object rest: `{id, password, safe...} = user`
|
|
1284
|
+
|
|
1285
|
+
**Explanation.** A `rest...` member inside an object pattern collects every own key the pattern did
|
|
1286
|
+
not name into a new object. The classic use is dropping fields before sending an object somewhere
|
|
1287
|
+
else, without mutating the original. A pattern may have only one rest member (MS1302), and it
|
|
1288
|
+
works in parameter lists too.
|
|
1289
|
+
|
|
1290
|
+
**Demonstration.**
|
|
1291
|
+
```mamba
|
|
1292
|
+
account =
|
|
1293
|
+
id: 42
|
|
1294
|
+
name: 'Mia'
|
|
1295
|
+
password: 'hunter2'
|
|
1296
|
+
gold: 120
|
|
1297
|
+
|
|
1298
|
+
{password, publicView...} = account
|
|
1299
|
+
present publicView
|
|
1300
|
+
present account.password
|
|
1301
|
+
|
|
1302
|
+
describe = ({name, details...}) -> "#{name}: #{Object.keys(details).join ', '}"
|
|
1303
|
+
present describe account
|
|
1304
|
+
```
|
|
1305
|
+
```text
|
|
1306
|
+
{ id: 42, name: 'Mia', gold: 120 }
|
|
1307
|
+
hunter2
|
|
1308
|
+
Mia: id, password, gold
|
|
1309
|
+
```
|
|
1310
|
+
|
|
1311
|
+
### 40. Nested destructuring with renames and defaults
|
|
1312
|
+
|
|
1313
|
+
**Explanation.** Object patterns nest (`{address: {city}} = person`), rename (`{name: who}`), and
|
|
1314
|
+
take defaults (`{level = 1}`), which apply when the value is `nothing` or `missing` and may use
|
|
1315
|
+
names bound earlier in the same pattern. Patterns work everywhere a name is bound: assignments,
|
|
1316
|
+
parameters, loop variables and the `onFail` of an `attempt`. Quirk: a default only belongs where a
|
|
1317
|
+
value is taken apart; `x = {a = 1}` is MS1301.
|
|
1318
|
+
|
|
1319
|
+
**Demonstration.**
|
|
1320
|
+
```mamba
|
|
1321
|
+
player =
|
|
1322
|
+
name: 'Mia'
|
|
1323
|
+
stats: {hp: 30, mp: nothing}
|
|
1324
|
+
home: {city: 'Riverton'}
|
|
1325
|
+
|
|
1326
|
+
{name: hero, stats: {hp, mp = 0}, home: {city, region = city}} = player
|
|
1327
|
+
present hero, hp, mp, city, region
|
|
1328
|
+
|
|
1329
|
+
greet = ({name, greeting = 'Welcome'}) -> "#{greeting}, #{name}"
|
|
1330
|
+
present greet player
|
|
1331
|
+
|
|
1332
|
+
attempt
|
|
1333
|
+
panic {code: 403}
|
|
1334
|
+
onFail {code, reason = 'unknown'}
|
|
1335
|
+
present code, reason
|
|
1336
|
+
```
|
|
1337
|
+
```text
|
|
1338
|
+
Mia 30 0 Riverton Riverton
|
|
1339
|
+
Welcome, Mia
|
|
1340
|
+
403 unknown
|
|
1341
|
+
```
|
|
1342
|
+
|
|
1343
|
+
### 41. Computed keys: `{[expr]: value}`
|
|
1344
|
+
|
|
1345
|
+
**Explanation.** A key in square brackets is computed: `{[key]: 10, ["#{key}Max"]: 100}`. Members
|
|
1346
|
+
keep their source order and each key expression runs once. In a pattern, `{[key]: current} = stats`
|
|
1347
|
+
reads `stats[key]`. Braces are required around an object with a computed key (MS1129 otherwise),
|
|
1348
|
+
because a bare `[key]: value` would read as a list.
|
|
1349
|
+
Fancy tier; the plain form is `player = {name: 'Mia'}` followed by `player[stat] = 12`.
|
|
1350
|
+
|
|
1351
|
+
**Demonstration.**
|
|
1352
|
+
```mamba
|
|
1353
|
+
stat = 'strength'
|
|
1354
|
+
bonus = 5
|
|
1355
|
+
player = {name: 'Mia', [stat]: 12, ["#{stat}Max"]: 20}
|
|
1356
|
+
present player
|
|
1357
|
+
|
|
1358
|
+
{[stat]: current} = player
|
|
1359
|
+
present current + bonus
|
|
1360
|
+
|
|
1361
|
+
tally = (votes) ->
|
|
1362
|
+
result = {}
|
|
1363
|
+
result = {result..., [vote]: (result[vote] ? 0) + 1} forEvery vote in votes
|
|
1364
|
+
result
|
|
1365
|
+
present tally ['ramen', 'udon', 'ramen']
|
|
1366
|
+
```
|
|
1367
|
+
```text
|
|
1368
|
+
{ name: 'Mia', strength: 12, strengthMax: 20 }
|
|
1369
|
+
17
|
|
1370
|
+
{ ramen: 2, udon: 1 }
|
|
1371
|
+
```
|
|
1372
|
+
|
|
1373
|
+
### 42. Soaks: `a?.b`, `a?[i]`, `f?()`
|
|
1374
|
+
|
|
1375
|
+
**Explanation.** A `?` before an access soaks: if the value on its left is `nothing` or `missing`,
|
|
1376
|
+
the whole chain gives `missing` instead of throwing. It works on property access (`a?.b`), index
|
|
1377
|
+
access (`a?[i]`) and calls (`f?()` calls `f` only if it exists). On a name that was never declared
|
|
1378
|
+
it adds a `typeof` guard. Use it at the edges of a program where data may be partial; inside your
|
|
1379
|
+
own code a missing value is usually a bug worth seeing.
|
|
1380
|
+
Fancy tier (soak chains); the plain form is `if player.guild? then player.guild.name`.
|
|
1381
|
+
|
|
1382
|
+
**Demonstration.**
|
|
1383
|
+
```mamba
|
|
1384
|
+
players = [
|
|
1385
|
+
{name: 'Mia', guild: {name: 'Night Owls', banner: ['owl', 'moon']}}
|
|
1386
|
+
{name: 'Ben', guild: nothing, onLogin: -> 'Ben logs in'}
|
|
1387
|
+
]
|
|
1388
|
+
forEvery player in players
|
|
1389
|
+
present player.name, player.guild?.name, player.guild?.banner?[1]
|
|
1390
|
+
present player.onLogin?() ? 'no login hook'
|
|
1391
|
+
present settings?.theme
|
|
1392
|
+
```
|
|
1393
|
+
```text
|
|
1394
|
+
Mia Night Owls moon
|
|
1395
|
+
no login hook
|
|
1396
|
+
Ben undefined undefined
|
|
1397
|
+
Ben logs in
|
|
1398
|
+
undefined
|
|
1399
|
+
```
|
|
1400
|
+
|
|
1401
|
+
### 43. `has`, `of`, `thanos` and own keys
|
|
1402
|
+
|
|
1403
|
+
**Explanation.** `object has 'key'` (or `'key' of object`) is JavaScript's `'key' in object`: it
|
|
1404
|
+
sees inherited keys too. `thanos object.key` deletes a member (it compiles to `delete`) and gives
|
|
1405
|
+
`yes` on success. For a guard that ignores the prototype chain, use `Object.hasOwn object, 'key'`
|
|
1406
|
+
or walk with `forEvery own`. Quirk: `in` is not the key test; `x in list` is array membership.
|
|
1407
|
+
|
|
1408
|
+
**Demonstration.**
|
|
1409
|
+
```mamba
|
|
1410
|
+
base = {currency: 'gold'}
|
|
1411
|
+
wallet = Object.create base
|
|
1412
|
+
wallet.coins = 10
|
|
1413
|
+
wallet.gems = 2
|
|
1414
|
+
|
|
1415
|
+
present wallet has 'coins', wallet has 'currency', 'gems' of wallet
|
|
1416
|
+
present Object.hasOwn wallet, 'currency'
|
|
1417
|
+
present thanos wallet.gems
|
|
1418
|
+
present wallet has 'gems', Object.keys wallet
|
|
1419
|
+
present 'coins' in Object.keys(wallet)
|
|
1420
|
+
```
|
|
1421
|
+
```text
|
|
1422
|
+
true true true
|
|
1423
|
+
false
|
|
1424
|
+
true
|
|
1425
|
+
false [ 'coins' ]
|
|
1426
|
+
true
|
|
1427
|
+
```
|
|
1428
|
+
|
|
1429
|
+
### 44. Grouping with `?=` on members
|
|
1430
|
+
|
|
1431
|
+
**Explanation.** `target[key] ?= value` assigns only when the member is absent, which turns the
|
|
1432
|
+
"create the bucket if needed, then add" step of grouping and counting into one line. Because it
|
|
1433
|
+
tests for `nothing`/`missing` rather than truthiness, a count of `0` or an empty list is kept.
|
|
1434
|
+
`or=` would also work for lists, but it would wipe a stored `0`.
|
|
1435
|
+
|
|
1436
|
+
**Demonstration.**
|
|
1437
|
+
```mamba
|
|
1438
|
+
orders = [
|
|
1439
|
+
{table: 4, dish: 'ramen'}
|
|
1440
|
+
{table: 2, dish: 'udon'}
|
|
1441
|
+
{table: 4, dish: 'mochi'}
|
|
1442
|
+
]
|
|
1443
|
+
byTable = {}
|
|
1444
|
+
forEvery order in orders
|
|
1445
|
+
byTable[order.table] ?= []
|
|
1446
|
+
byTable[order.table].push order.dish
|
|
1447
|
+
present byTable
|
|
1448
|
+
|
|
1449
|
+
counts = {ramen: 0}
|
|
1450
|
+
counts.ramen ?= 99
|
|
1451
|
+
counts.udon ?= 0
|
|
1452
|
+
present counts
|
|
1453
|
+
```
|
|
1454
|
+
```text
|
|
1455
|
+
{ '2': [ 'udon' ], '4': [ 'ramen', 'mochi' ] }
|
|
1456
|
+
{ ramen: 0, udon: 0 }
|
|
1457
|
+
```
|
|
1458
|
+
|
|
1459
|
+
## Blueprints
|
|
1460
|
+
|
|
1461
|
+
### 45. `blueprint` with `@` parameters
|
|
1462
|
+
|
|
1463
|
+
**Explanation.** `blueprint Name` declares a class (`class` is a synonym). Inside it, `@x` means
|
|
1464
|
+
`this.x`, and a constructor parameter written `@name` assigns itself to `this.name`, so most
|
|
1465
|
+
constructors have an empty body. Methods are `name: (args) -> body` lines, and their last
|
|
1466
|
+
expression is returned. A blueprint compiles to an ES5 constructor function with prototype methods,
|
|
1467
|
+
which is why some ES2015 class features are missing (features 52 and 53).
|
|
1468
|
+
|
|
1469
|
+
**Demonstration.**
|
|
1470
|
+
```mamba
|
|
1471
|
+
blueprint Player
|
|
1472
|
+
constructor: (@name, @level = 1) ->
|
|
1473
|
+
@inventory = []
|
|
1474
|
+
|
|
1475
|
+
pickUp: (item) ->
|
|
1476
|
+
@inventory.push item
|
|
1477
|
+
@
|
|
1478
|
+
|
|
1479
|
+
describe: -> "#{@name} (level #{@level}) carries #{@inventory.join(', ') or 'nothing'}"
|
|
1480
|
+
|
|
1481
|
+
mia = make Player 'Mia', 5
|
|
1482
|
+
mia.pickUp('sword').pickUp('potion')
|
|
1483
|
+
present mia.describe()
|
|
1484
|
+
present (make Player 'Ben').describe()
|
|
1485
|
+
```
|
|
1486
|
+
```text
|
|
1487
|
+
Mia (level 5) carries sword, potion
|
|
1488
|
+
Ben (level 1) carries nothing
|
|
1489
|
+
```
|
|
1490
|
+
|
|
1491
|
+
### 46. `inheritsFrom` and `super`
|
|
1492
|
+
|
|
1493
|
+
**Explanation.** `blueprint Hero inheritsFrom Player` extends another blueprint. In the
|
|
1494
|
+
constructor, `super args` calls the parent constructor; in a method, `super()` calls the parent's
|
|
1495
|
+
method of the same name (a bare `super` passes the current arguments along). A child that does not
|
|
1496
|
+
define a constructor gets the parent's. Inherited methods can be overridden and extended, and
|
|
1497
|
+
`@` always refers to the instance.
|
|
1498
|
+
|
|
1499
|
+
**Demonstration.**
|
|
1500
|
+
```mamba
|
|
1501
|
+
blueprint Player
|
|
1502
|
+
constructor: (@name) ->
|
|
1503
|
+
greet: -> "I am #{@name}"
|
|
1504
|
+
power: -> 10
|
|
1505
|
+
|
|
1506
|
+
blueprint Mage inheritsFrom Player
|
|
1507
|
+
constructor: (name, @element) ->
|
|
1508
|
+
super name
|
|
1509
|
+
greet: -> "#{super()}, master of #{@element}"
|
|
1510
|
+
power: -> super * 3
|
|
1511
|
+
|
|
1512
|
+
blueprint Squire inheritsFrom Player
|
|
1513
|
+
|
|
1514
|
+
present (make Mage 'Cy', 'fire').greet()
|
|
1515
|
+
present (make Mage 'Cy', 'fire').power()
|
|
1516
|
+
present (make Squire 'Dee').greet()
|
|
1517
|
+
```
|
|
1518
|
+
```text
|
|
1519
|
+
I am Cy, master of fire
|
|
1520
|
+
30
|
|
1521
|
+
I am Dee
|
|
1522
|
+
```
|
|
1523
|
+
|
|
1524
|
+
### 47. Static members: `@name:` and `@count = 0`
|
|
1525
|
+
|
|
1526
|
+
**Explanation.** Inside a blueprint body, a member written with `@` belongs to the blueprint
|
|
1527
|
+
itself, not to instances: `@create: ->` is a static method and `@count = 0` a static property.
|
|
1528
|
+
Inside a static method `@` is the blueprint, so `make this args` builds an instance of whichever
|
|
1529
|
+
blueprint the method was called on, which subclasses inherit. Quirk: `inheritsFrom` copies the
|
|
1530
|
+
parent's static properties onto the child when it is declared, so each keeps its own count from
|
|
1531
|
+
then on. Use static methods for named constructors and registries.
|
|
1532
|
+
Fancy tier (executable blueprint bodies and `@` statics); the plain form is `Ticket.issued = 0` after the blueprint.
|
|
1533
|
+
|
|
1534
|
+
**Demonstration.**
|
|
1535
|
+
```mamba
|
|
1536
|
+
blueprint Ticket
|
|
1537
|
+
@issued = 0
|
|
1538
|
+
@forTable: (table) ->
|
|
1539
|
+
@issued += 1
|
|
1540
|
+
make @ "T#{@issued}", table
|
|
1541
|
+
constructor: (@id, @table) ->
|
|
1542
|
+
|
|
1543
|
+
blueprint RushTicket inheritsFrom Ticket
|
|
1544
|
+
|
|
1545
|
+
first = Ticket.forTable 4
|
|
1546
|
+
second = RushTicket.forTable 2
|
|
1547
|
+
present first.id, first.table
|
|
1548
|
+
present second.id, second areYouA RushTicket
|
|
1549
|
+
present Ticket.issued, RushTicket.issued
|
|
1550
|
+
```
|
|
1551
|
+
```text
|
|
1552
|
+
T1 4
|
|
1553
|
+
T1 true
|
|
1554
|
+
1 1
|
|
1555
|
+
```
|
|
1556
|
+
|
|
1557
|
+
### 48. Bound methods with `=>`
|
|
1558
|
+
|
|
1559
|
+
**Explanation.** A method written with `=>` instead of `->` is bound to its instance when the
|
|
1560
|
+
instance is made, so it keeps `@` when passed around as a callback (an event handler, a
|
|
1561
|
+
`setTimeout`, `list.map`). A plain `->` method detached from its object loses `this` (the compiled code is not in
|
|
1562
|
+
strict mode, so `this` becomes the global object and `@clicks += 1` quietly gives `NaN`). Bind only the
|
|
1563
|
+
methods you actually hand out, since every instance gets its own copy of each bound method.
|
|
1564
|
+
|
|
1565
|
+
**Demonstration.**
|
|
1566
|
+
```mamba
|
|
1567
|
+
blueprint Counter
|
|
1568
|
+
constructor: (@label) -> @clicks = 0
|
|
1569
|
+
bound: => @clicks += 1
|
|
1570
|
+
plain: -> @clicks += 1
|
|
1571
|
+
|
|
1572
|
+
counter = make Counter 'orders'
|
|
1573
|
+
handlers = [counter.bound, counter.bound]
|
|
1574
|
+
handler() forEvery handler in handlers
|
|
1575
|
+
present counter.clicks
|
|
1576
|
+
|
|
1577
|
+
loose = counter.plain
|
|
1578
|
+
present 'a detached plain method sees no instance:', loose(), counter.clicks
|
|
1579
|
+
```
|
|
1580
|
+
```text
|
|
1581
|
+
2
|
|
1582
|
+
a detached plain method sees no instance: NaN 2
|
|
1583
|
+
```
|
|
1584
|
+
|
|
1585
|
+
### 49. `make` and `areYouA`
|
|
1586
|
+
|
|
1587
|
+
**Explanation.** `make Blueprint args` is `new Blueprint(args)`, with the same implicit-call rules
|
|
1588
|
+
as any call, and `value areYouA Blueprint` is `instanceof`. Write `(make Store).snapshot()` to call
|
|
1589
|
+
a method on a fresh instance. Quirk: `make Store.load()` constructs `Store.load`, and the fast
|
|
1590
|
+
parser reads `make(Store).snapshot()` as CoffeeScript's `new(Store).snapshot()`, but the fallback
|
|
1591
|
+
parser rejects `make(` with parentheses anywhere, so prefer `(make Store)`. `new` still works.
|
|
1592
|
+
|
|
1593
|
+
**Demonstration.**
|
|
1594
|
+
```mamba
|
|
1595
|
+
blueprint Menu
|
|
1596
|
+
constructor: (@dishes = ['ramen']) ->
|
|
1597
|
+
count: -> @dishes.length
|
|
1598
|
+
|
|
1599
|
+
blueprint KidsMenu inheritsFrom Menu
|
|
1600
|
+
|
|
1601
|
+
present (make Menu).count()
|
|
1602
|
+
present (make Menu ['udon', 'soba']).count()
|
|
1603
|
+
kids = make KidsMenu
|
|
1604
|
+
present kids areYouA KidsMenu, kids areYouA Menu, kids areYouA Array
|
|
1605
|
+
present not (kids areYouA Array)
|
|
1606
|
+
present (make Menu).count()
|
|
1607
|
+
```
|
|
1608
|
+
```text
|
|
1609
|
+
1
|
|
1610
|
+
2
|
|
1611
|
+
true true false
|
|
1612
|
+
true
|
|
1613
|
+
1
|
|
1614
|
+
```
|
|
1615
|
+
|
|
1616
|
+
### 50. Custom errors: `inheritsFrom Error`
|
|
1617
|
+
|
|
1618
|
+
**Explanation.** A blueprint can extend `Error`, and `panic make OrderError …` throws an instance
|
|
1619
|
+
that `onFail` can test with `areYouA`. Quirk: because a blueprint compiles to an ES5 constructor,
|
|
1620
|
+
`super message` calls `Error` without letting it fill in `this`, so the message is empty: assign
|
|
1621
|
+
`@message` (and `@name`) yourself. The checker treats a blueprint extending something it cannot see,
|
|
1622
|
+
such as `Error`, as open, so extra members are never flagged.
|
|
1623
|
+
|
|
1624
|
+
**Demonstration.**
|
|
1625
|
+
```mamba
|
|
1626
|
+
blueprint OrderError inheritsFrom Error
|
|
1627
|
+
constructor: (message, @table) ->
|
|
1628
|
+
super message
|
|
1629
|
+
@message = message
|
|
1630
|
+
@name = 'OrderError'
|
|
1631
|
+
|
|
1632
|
+
serve = (table) ->
|
|
1633
|
+
panic make OrderError 'the soup is cold', table if table is 4
|
|
1634
|
+
"served table #{table}"
|
|
1635
|
+
|
|
1636
|
+
forEvery table in [2, 4]
|
|
1637
|
+
attempt
|
|
1638
|
+
present serve table
|
|
1639
|
+
onFail problem
|
|
1640
|
+
present problem areYouA OrderError, problem areYouA Error
|
|
1641
|
+
present "#{problem.name}: #{problem.message} (table #{problem.table})"
|
|
1642
|
+
```
|
|
1643
|
+
```text
|
|
1644
|
+
served table 2
|
|
1645
|
+
true true
|
|
1646
|
+
OrderError: the soup is cold (table 4)
|
|
1647
|
+
```
|
|
1648
|
+
|
|
1649
|
+
### 51. Typed `@` parameters and `implements`
|
|
1650
|
+
|
|
1651
|
+
**Explanation.** Constructor parameters that assign themselves can carry types and defaults at the
|
|
1652
|
+
same time: `constructor: (@name :: String, @level :: Int = 1) ->`. Typed constructor parameters
|
|
1653
|
+
give `make` its argument types, an instance carries the constructor's `@` members for the checker
|
|
1654
|
+
(so `{name, level} = player` type-checks), and `implements` ties the blueprint to a struct. As
|
|
1655
|
+
with all annotations, nothing of this reaches the JavaScript.
|
|
1656
|
+
|
|
1657
|
+
**Demonstration.**
|
|
1658
|
+
```mamba
|
|
1659
|
+
struct Member
|
|
1660
|
+
name :: String
|
|
1661
|
+
level :: Int
|
|
1662
|
+
|
|
1663
|
+
blueprint Recruit implements Member
|
|
1664
|
+
constructor: (@name :: String, @level :: Int = 1) ->
|
|
1665
|
+
promote: :: Int -> @level += 1
|
|
1666
|
+
|
|
1667
|
+
roster :: Member[] = [(make Recruit 'Ana'), (make Recruit 'Ben', 4)]
|
|
1668
|
+
roster[0].promote()
|
|
1669
|
+
forEvery member in roster
|
|
1670
|
+
{name, level} = member
|
|
1671
|
+
present "#{name} is level #{level}"
|
|
1672
|
+
```
|
|
1673
|
+
```text
|
|
1674
|
+
Ana is level 2
|
|
1675
|
+
Ben is level 4
|
|
1676
|
+
```
|
|
1677
|
+
|
|
1678
|
+
### 52. `{@state..., key: value}`: spreading `this`
|
|
1679
|
+
|
|
1680
|
+
**Explanation.** Object spread accepts `@` members, so `{@state..., done: yes}` copies the
|
|
1681
|
+
instance's `state` into a new object with one change. That is the immutable-update idiom of React
|
|
1682
|
+
reducers and stores, written in a blueprint method. The copy is shallow: nested objects are shared
|
|
1683
|
+
until they are spread too.
|
|
1684
|
+
|
|
1685
|
+
**Demonstration.**
|
|
1686
|
+
```mamba
|
|
1687
|
+
blueprint OrderStore
|
|
1688
|
+
constructor: ->
|
|
1689
|
+
@state = {items: [], paid: no, table: 4}
|
|
1690
|
+
@history = []
|
|
1691
|
+
|
|
1692
|
+
update: (changes) ->
|
|
1693
|
+
@history.push @state
|
|
1694
|
+
@state = {@state..., changes...}
|
|
1695
|
+
|
|
1696
|
+
store = make OrderStore
|
|
1697
|
+
store.update items: ['ramen']
|
|
1698
|
+
store.update paid: yes
|
|
1699
|
+
present store.state
|
|
1700
|
+
present store.history.length, store.history[0].paid
|
|
1701
|
+
```
|
|
1702
|
+
```text
|
|
1703
|
+
{ items: [ 'ramen' ], paid: true, table: 4 }
|
|
1704
|
+
2 false
|
|
1705
|
+
```
|
|
1706
|
+
|
|
1707
|
+
### 53. Prototype patching with `::`, and no getters or private fields
|
|
1708
|
+
|
|
1709
|
+
**Explanation.** `Blueprint::name` is `Blueprint.prototype.name`, so `Menu::discount = ->` adds a
|
|
1710
|
+
method after the blueprint is declared (the checker counts it as a member), and `String::shout`
|
|
1711
|
+
extends a built-in. Blueprints have no `get x()` accessors, no `#private` fields and no
|
|
1712
|
+
`static x = 1` class fields: use `_private` properties by convention, a method, `@x = 1` in the
|
|
1713
|
+
body, or `Object.defineProperty` on `Blueprint.prototype` when a getter is truly needed.
|
|
1714
|
+
Fancy tier (`::` prototype patching); the plain form is a method inside the blueprint body.
|
|
1715
|
+
|
|
1716
|
+
**Demonstration.**
|
|
1717
|
+
```mamba
|
|
1718
|
+
blueprint Menu
|
|
1719
|
+
constructor: (@_prices = {ramen: 9, udon: 8}) ->
|
|
1720
|
+
|
|
1721
|
+
Menu::cheapest = -> Math.min Object.values(@_prices)...
|
|
1722
|
+
Object.defineProperty Menu.prototype, 'size', get: -> Object.keys(@_prices).length
|
|
1723
|
+
|
|
1724
|
+
menu = make Menu
|
|
1725
|
+
present menu.cheapest(), menu.size
|
|
1726
|
+
|
|
1727
|
+
String::shout = -> "#{@toUpperCase()}!"
|
|
1728
|
+
present 'order up'.shout()
|
|
1729
|
+
thanos String::shout
|
|
1730
|
+
present typeof 'x'.shout
|
|
1731
|
+
```
|
|
1732
|
+
```text
|
|
1733
|
+
8 2
|
|
1734
|
+
ORDER UP!
|
|
1735
|
+
undefined
|
|
1736
|
+
```
|
|
1737
|
+
|
|
1738
|
+
## Functions
|
|
1739
|
+
|
|
1740
|
+
### 54. `->`, implicit returns and calls without parentheses
|
|
1741
|
+
|
|
1742
|
+
**Explanation.** `(a, b) -> body` is a function and `-> body` one with no parameters; the last
|
|
1743
|
+
expression is returned, so `return` is only needed to leave early. Calls may drop their
|
|
1744
|
+
parentheses (`present 'hi', 42`), and an implicit call runs to the end of the line, so
|
|
1745
|
+
`present double 4` is `present(double(4))`. `present` and `complain` are ordinary values
|
|
1746
|
+
(`console.log` and `console.warn`), so they can be passed as callbacks; remember that `forEach`
|
|
1747
|
+
passes the index and the list as well, and `present` prints them all.
|
|
1748
|
+
|
|
1749
|
+
**Demonstration.**
|
|
1750
|
+
```mamba
|
|
1751
|
+
double = (n) -> n * 2
|
|
1752
|
+
greet = -> 'order up!'
|
|
1753
|
+
priceWithTip = (price, rate) ->
|
|
1754
|
+
return 0 if price <= 0
|
|
1755
|
+
price + price * rate
|
|
1756
|
+
|
|
1757
|
+
present double 4
|
|
1758
|
+
present greet()
|
|
1759
|
+
present priceWithTip(20, 0.15), priceWithTip -5, 0.1
|
|
1760
|
+
['ramen', 'udon'].forEach (dish) -> present "one #{dish}"
|
|
1761
|
+
['mochi'].forEach present
|
|
1762
|
+
```
|
|
1763
|
+
```text
|
|
1764
|
+
8
|
|
1765
|
+
order up!
|
|
1766
|
+
23 0
|
|
1767
|
+
one ramen
|
|
1768
|
+
one udon
|
|
1769
|
+
mochi 0 [ 'mochi' ]
|
|
1770
|
+
```
|
|
1771
|
+
|
|
1772
|
+
### 55. Default parameters and rest parameters
|
|
1773
|
+
|
|
1774
|
+
**Explanation.** `(qty = 1) ->` gives a default that applies when the argument is `nothing` or
|
|
1775
|
+
`missing`, so callers can pass `nothing` to mean "use the default" (in JavaScript only `undefined`
|
|
1776
|
+
does). `(first, rest...) ->` collects the remaining arguments into a list, and the rest may sit in
|
|
1777
|
+
the middle: `(first, middle..., last) ->`. Defaults can use earlier parameters.
|
|
1778
|
+
|
|
1779
|
+
**Demonstration.**
|
|
1780
|
+
```mamba
|
|
1781
|
+
order = (dish, qty = 1, note = "#{qty} x #{dish}") -> note
|
|
1782
|
+
present order 'ramen'
|
|
1783
|
+
present order 'udon', nothing
|
|
1784
|
+
present order 'soba', 3
|
|
1785
|
+
present order 'mochi', 2, 'for the table'
|
|
1786
|
+
|
|
1787
|
+
podium = (gold, others..., last) -> "#{gold} won, #{last} came last, #{others.length} between"
|
|
1788
|
+
present podium 'Ana', 'Ben', 'Cy', 'Dee'
|
|
1789
|
+
total = (prices...) -> prices.reduce ((sum, p) -> sum + p), 0
|
|
1790
|
+
present total(), total 4, 5, 6
|
|
1791
|
+
```
|
|
1792
|
+
```text
|
|
1793
|
+
1 x ramen
|
|
1794
|
+
1 x udon
|
|
1795
|
+
3 x soba
|
|
1796
|
+
for the table
|
|
1797
|
+
Ana won, Dee came last, 2 between
|
|
1798
|
+
0 15
|
|
1799
|
+
```
|
|
1800
|
+
|
|
1801
|
+
### 56. `=>` keeps `this`, and `arguments` inside it
|
|
1802
|
+
|
|
1803
|
+
**Explanation.** `=>` makes a function that keeps the `@` of the place it was written, which is
|
|
1804
|
+
what callbacks inside methods need. Quirk: it compiles to an ordinary function with `this`
|
|
1805
|
+
captured, not to a JavaScript arrow, so `arguments` inside `=>` is the bound function's own
|
|
1806
|
+
arguments, not the enclosing function's. When you want "all the arguments", say so with a rest
|
|
1807
|
+
parameter: `(args...) ->`.
|
|
1808
|
+
|
|
1809
|
+
**Demonstration.**
|
|
1810
|
+
```mamba
|
|
1811
|
+
blueprint Kitchen
|
|
1812
|
+
constructor: (@chef) ->
|
|
1813
|
+
cookAll: (dishes) ->
|
|
1814
|
+
dishes.map (dish) => "#{@chef} cooks #{dish}"
|
|
1815
|
+
countArguments: ->
|
|
1816
|
+
inner = => arguments.length
|
|
1817
|
+
inner 'a', 'b'
|
|
1818
|
+
|
|
1819
|
+
kitchen = make Kitchen 'Mia'
|
|
1820
|
+
present kitchen.cookAll ['ramen', 'udon']
|
|
1821
|
+
present kitchen.countArguments() # 2: inner's own arguments
|
|
1822
|
+
countAll = (args...) -> args.length
|
|
1823
|
+
present countAll 'a', 'b', 'c'
|
|
1824
|
+
```
|
|
1825
|
+
```text
|
|
1826
|
+
[ 'Mia cooks ramen', 'Mia cooks udon' ]
|
|
1827
|
+
2
|
|
1828
|
+
3
|
|
1829
|
+
```
|
|
1830
|
+
|
|
1831
|
+
### 57. `do (x) ->`: one variable per iteration
|
|
1832
|
+
|
|
1833
|
+
**Explanation.** Variables are function scoped, so every closure created in a loop shares the one
|
|
1834
|
+
loop variable and sees its last value. `do (x) -> …` calls a function immediately with `x` as its
|
|
1835
|
+
argument, giving each iteration its own copy. Reach for `do` whenever a loop creates callbacks
|
|
1836
|
+
that run later (timers, event handlers, promises); `forEvery … in list` with `.forEach` or `.map`
|
|
1837
|
+
avoids the problem too.
|
|
1838
|
+
Fancy tier (`do` and IIFE idioms); the plain form is
|
|
1839
|
+
`[1, 2, 3].forEach (table) -> captured.push -> "table #{table}"`.
|
|
1840
|
+
|
|
1841
|
+
**Demonstration.**
|
|
1842
|
+
```mamba
|
|
1843
|
+
shared = []
|
|
1844
|
+
forEvery table in [1, 2, 3]
|
|
1845
|
+
shared.push -> "table #{table}"
|
|
1846
|
+
present (callback() forEvery callback in shared)
|
|
1847
|
+
|
|
1848
|
+
captured = []
|
|
1849
|
+
forEvery table in [1, 2, 3]
|
|
1850
|
+
do (table) ->
|
|
1851
|
+
captured.push -> "table #{table}"
|
|
1852
|
+
present (callback() forEvery callback in captured)
|
|
1853
|
+
|
|
1854
|
+
total = do (base = 10, tip = 2) -> base + tip
|
|
1855
|
+
present total
|
|
1856
|
+
```
|
|
1857
|
+
```text
|
|
1858
|
+
[ 'table 3', 'table 3', 'table 3' ]
|
|
1859
|
+
[ 'table 1', 'table 2', 'table 3' ]
|
|
1860
|
+
12
|
|
1861
|
+
```
|
|
1862
|
+
|
|
1863
|
+
### 58. Tagged templates: `tag"text #{value}"`
|
|
1864
|
+
|
|
1865
|
+
**Explanation.** A string written directly after a value, with no space, is a tagged template: the
|
|
1866
|
+
value is called with the list of string pieces followed by the interpolated values, and `#{…}`
|
|
1867
|
+
becomes `${…}` in the output. Heredocs work too (`sql"""…"""`). With a space, `tag "…"` is an
|
|
1868
|
+
ordinary call with one string. Backticks are embedded JavaScript, so
|
|
1869
|
+
`` tag`…` `` is MS1132. Use tags for escaping, translation and query builders.
|
|
1870
|
+
Fancy tier; the plain form is an ordinary call, `shout ['', ' bowls of ', ', please'], qty, dish`.
|
|
1871
|
+
|
|
1872
|
+
**Demonstration.**
|
|
1873
|
+
```mamba
|
|
1874
|
+
shout = (pieces, values...) ->
|
|
1875
|
+
out = pieces[0]
|
|
1876
|
+
forEvery value, i in values
|
|
1877
|
+
out += String(value).toUpperCase() + pieces[i + 1]
|
|
1878
|
+
out
|
|
1879
|
+
|
|
1880
|
+
dish = 'ramen'
|
|
1881
|
+
qty = 2
|
|
1882
|
+
present shout"#{qty} bowls of #{dish}, please"
|
|
1883
|
+
|
|
1884
|
+
escape = (pieces, values...) ->
|
|
1885
|
+
safe = (String(v).replace(/</g, '<') forEvery v in values)
|
|
1886
|
+
pieces.reduce (html, piece, i) -> html + safe[i - 1] + piece
|
|
1887
|
+
present escape"<p>#{'<b>chef</b>'} says hi to #{dish}</p>"
|
|
1888
|
+
```
|
|
1889
|
+
```text
|
|
1890
|
+
2 bowls of RAMEN, please
|
|
1891
|
+
<p><b>chef</b> says hi to ramen</p>
|
|
1892
|
+
```
|
|
1893
|
+
|
|
1894
|
+
### 59. `waitForIt`: async without the keyword
|
|
1895
|
+
|
|
1896
|
+
**Explanation.** `waitForIt promise` is `await`, and any function whose own body contains
|
|
1897
|
+
`waitForIt` (or `waitForAll`) is emitted as `async` automatically; nested functions are judged on
|
|
1898
|
+
their own. It has the precedence of a unary operator, so `(waitForIt fetchUser()).name` reads the
|
|
1899
|
+
name of the result. A `waitForIt` at the top level wraps the program in an async function (or is a
|
|
1900
|
+
top-level `await` in an ES module). `waitForIt` in a blueprint constructor is an error.
|
|
1901
|
+
|
|
1902
|
+
**Demonstration.**
|
|
1903
|
+
```mamba
|
|
1904
|
+
delay = (ms, value) -> make Promise (resolve) -> setTimeout (-> resolve value), ms
|
|
1905
|
+
|
|
1906
|
+
cook = (dish) ->
|
|
1907
|
+
present "start #{dish}"
|
|
1908
|
+
plate = waitForIt delay 10, "#{dish} plated"
|
|
1909
|
+
present plate
|
|
1910
|
+
plate.length
|
|
1911
|
+
|
|
1912
|
+
present cook('ramen') areYouA Promise
|
|
1913
|
+
size = waitForIt cook 'udon'
|
|
1914
|
+
present 'plate name length:', size
|
|
1915
|
+
present (waitForIt delay(5, {table: 4})).table
|
|
1916
|
+
```
|
|
1917
|
+
```text
|
|
1918
|
+
start ramen
|
|
1919
|
+
true
|
|
1920
|
+
start udon
|
|
1921
|
+
ramen plated
|
|
1922
|
+
udon plated
|
|
1923
|
+
plate name length: 11
|
|
1924
|
+
4
|
|
1925
|
+
```
|
|
1926
|
+
|
|
1927
|
+
### 60. `waitForAll` and async errors
|
|
1928
|
+
|
|
1929
|
+
**Explanation.** `waitForAll list` is `await Promise.all(list)`: start every task first, then wait
|
|
1930
|
+
for all of them, so they run concurrently. A rejected promise throws at the `waitForIt` or
|
|
1931
|
+
`waitForAll` that waits for it, so ordinary `attempt` / `onFail` handles async failures, and a
|
|
1932
|
+
`panic` inside an async function becomes a rejection.
|
|
1933
|
+
|
|
1934
|
+
**Demonstration.**
|
|
1935
|
+
```mamba
|
|
1936
|
+
delay = (ms, value) -> make Promise (resolve) -> setTimeout (-> resolve value), ms
|
|
1937
|
+
|
|
1938
|
+
cook = (dish, ms) ->
|
|
1939
|
+
panic "no #{dish} today" if dish is 'eel'
|
|
1940
|
+
waitForIt delay ms, "#{dish} ready"
|
|
1941
|
+
|
|
1942
|
+
started = Date.now()
|
|
1943
|
+
plates = waitForAll [cook('ramen', 30), cook('udon', 30), cook('soba', 30)]
|
|
1944
|
+
present plates
|
|
1945
|
+
present 'concurrent:', Date.now() - started < 80
|
|
1946
|
+
|
|
1947
|
+
attempt
|
|
1948
|
+
waitForAll [cook('ramen', 5), cook('eel', 5)]
|
|
1949
|
+
onFail problem
|
|
1950
|
+
present 'failed:', problem.message
|
|
1951
|
+
```
|
|
1952
|
+
```text
|
|
1953
|
+
[ 'ramen ready', 'udon ready', 'soba ready' ]
|
|
1954
|
+
concurrent: true
|
|
1955
|
+
failed: no eel today
|
|
1956
|
+
```
|
|
1957
|
+
|
|
1958
|
+
### 61. Generators: `yield`, `yield from` and `forEvery … from`
|
|
1959
|
+
|
|
1960
|
+
**Explanation.** A function that contains `yield` is a generator: calling it returns an iterator
|
|
1961
|
+
that pauses at each `yield`. `yield from other` delegates to another iterable, `received = yield x`
|
|
1962
|
+
takes the value passed to `next`, and `forEvery x from iterable` walks any iterable (generators,
|
|
1963
|
+
strings, `Map`, `Set`). Quirk: a loop at the end of a generator still collects its values, so end
|
|
1964
|
+
the generator with a bare `return` when it should not have a final value.
|
|
1965
|
+
Fancy tier (`yield` as an expression); the plain form keeps the running total in a blueprint with an `add` method.
|
|
1966
|
+
|
|
1967
|
+
**Demonstration.**
|
|
1968
|
+
```mamba
|
|
1969
|
+
courses = ->
|
|
1970
|
+
yield 'soup'
|
|
1971
|
+
yield from ['ramen', 'tempura']
|
|
1972
|
+
yield 'mochi'
|
|
1973
|
+
return
|
|
1974
|
+
|
|
1975
|
+
forEvery course from courses()
|
|
1976
|
+
present 'serve', course
|
|
1977
|
+
present [courses()...].length
|
|
1978
|
+
|
|
1979
|
+
tally = ->
|
|
1980
|
+
total = 0
|
|
1981
|
+
loop
|
|
1982
|
+
total += yield total
|
|
1983
|
+
counter = tally()
|
|
1984
|
+
counter.next()
|
|
1985
|
+
counter.next 5
|
|
1986
|
+
present counter.next(10).value
|
|
1987
|
+
```
|
|
1988
|
+
```text
|
|
1989
|
+
serve soup
|
|
1990
|
+
serve ramen
|
|
1991
|
+
serve tempura
|
|
1992
|
+
serve mochi
|
|
1993
|
+
4
|
|
1994
|
+
15
|
|
1995
|
+
```
|
|
1996
|
+
|
|
1997
|
+
### 62. Async generators and `forEvery waitForIt … from`
|
|
1998
|
+
|
|
1999
|
+
**Explanation.** A function that uses both `waitForIt` and `yield` is an async generator, and
|
|
2000
|
+
`forEvery waitForIt x from source` is JavaScript's `for await`: it waits for each value of an async
|
|
2001
|
+
iterable (a stream, a paginated API, an async generator) in turn. The loop itself makes its
|
|
2002
|
+
function async, so the consumer needs no extra marking.
|
|
2003
|
+
|
|
2004
|
+
**Demonstration.**
|
|
2005
|
+
```mamba
|
|
2006
|
+
delay = (ms, value) -> make Promise (resolve) -> setTimeout (-> resolve value), ms
|
|
2007
|
+
|
|
2008
|
+
ticketsFromKitchen = (count) ->
|
|
2009
|
+
forEvery n in [1..count]
|
|
2010
|
+
yield waitForIt delay 5, "ticket #{n}"
|
|
2011
|
+
return
|
|
2012
|
+
|
|
2013
|
+
serveAll = ->
|
|
2014
|
+
served = []
|
|
2015
|
+
forEvery waitForIt ticket from ticketsFromKitchen 3
|
|
2016
|
+
present 'serving', ticket
|
|
2017
|
+
served.push ticket
|
|
2018
|
+
served.length
|
|
2019
|
+
|
|
2020
|
+
present 'served', waitForIt serveAll()
|
|
2021
|
+
```
|
|
2022
|
+
```text
|
|
2023
|
+
serving ticket 1
|
|
2024
|
+
serving ticket 2
|
|
2025
|
+
serving ticket 3
|
|
2026
|
+
served 3
|
|
2027
|
+
```
|
|
2028
|
+
|
|
2029
|
+
## OOP
|
|
2030
|
+
|
|
2031
|
+
### 63. Polymorphism: one message, many blueprints
|
|
2032
|
+
|
|
2033
|
+
**Explanation.** Different blueprints can answer the same method name in their own way, and code
|
|
2034
|
+
that calls the method does not need to know which blueprint it holds. With `inheritsFrom` the
|
|
2035
|
+
shared behaviour lives in the parent and each child overrides only what differs, calling `super()`
|
|
2036
|
+
to extend rather than replace. Prefer this over a `consider` on a `type` field whenever new kinds
|
|
2037
|
+
are likely to be added.
|
|
2038
|
+
|
|
2039
|
+
**Demonstration.**
|
|
2040
|
+
```mamba
|
|
2041
|
+
blueprint Dish
|
|
2042
|
+
constructor: (@name, @base) ->
|
|
2043
|
+
price: -> @base
|
|
2044
|
+
label: -> "#{@name}: $#{@price().toFixed 2}"
|
|
2045
|
+
|
|
2046
|
+
blueprint Special inheritsFrom Dish
|
|
2047
|
+
price: -> super() * 0.8
|
|
2048
|
+
|
|
2049
|
+
blueprint Combo inheritsFrom Dish
|
|
2050
|
+
constructor: (name, parts...) ->
|
|
2051
|
+
super name, 0
|
|
2052
|
+
@parts = parts
|
|
2053
|
+
price: -> @parts.reduce ((sum, part) -> sum + part.price()), 1
|
|
2054
|
+
|
|
2055
|
+
ramen = make Dish 'ramen', 9
|
|
2056
|
+
order = [ramen, (make Special 'udon', 10), (make Combo 'lunch set', ramen, make Dish 'tea', 2)]
|
|
2057
|
+
present dish.label() forEvery dish in order
|
|
2058
|
+
```
|
|
2059
|
+
```text
|
|
2060
|
+
ramen: $9.00
|
|
2061
|
+
udon: $8.00
|
|
2062
|
+
lunch set: $12.00
|
|
2063
|
+
```
|
|
2064
|
+
|
|
2065
|
+
### 64. Abstract methods with `panic`
|
|
2066
|
+
|
|
2067
|
+
**Explanation.** MambaScript has no `abstract` keyword; a parent blueprint declares the methods its
|
|
2068
|
+
children must supply by giving them a body that panics. `panic 'text'` throws a real `Error`, and
|
|
2069
|
+
an interpolated message can name the blueprint that forgot (`@constructor.name`). The template
|
|
2070
|
+
method pattern follows naturally: the parent's method calls the abstract step, and each child
|
|
2071
|
+
fills it in. For a compile-time guarantee instead, use a `struct` with `implements` (feature 12).
|
|
2072
|
+
|
|
2073
|
+
**Demonstration.**
|
|
2074
|
+
```mamba
|
|
2075
|
+
blueprint Shape
|
|
2076
|
+
area: -> panic "#{@constructor.name} must define area"
|
|
2077
|
+
describe: -> "#{@constructor.name} with area #{@area().toFixed 1}"
|
|
2078
|
+
|
|
2079
|
+
blueprint Circle inheritsFrom Shape
|
|
2080
|
+
constructor: (@r) ->
|
|
2081
|
+
area: -> Math.PI * @r * @r
|
|
2082
|
+
|
|
2083
|
+
blueprint Blob inheritsFrom Shape
|
|
2084
|
+
|
|
2085
|
+
present (make Circle 2).describe()
|
|
2086
|
+
attempt
|
|
2087
|
+
present (make Blob).describe()
|
|
2088
|
+
onFail problem
|
|
2089
|
+
present problem.message
|
|
2090
|
+
```
|
|
2091
|
+
```text
|
|
2092
|
+
Circle with area 12.6
|
|
2093
|
+
Blob must define area
|
|
2094
|
+
```
|
|
2095
|
+
|
|
2096
|
+
### 65. Mixins as blueprint factories
|
|
2097
|
+
|
|
2098
|
+
**Explanation.** A blueprint inherits from one parent, but a function that takes a parent and
|
|
2099
|
+
returns a new blueprint inheriting from it is a mixin: `blueprint Player inheritsFrom Serializable
|
|
2100
|
+
Greets Character` stacks two of them on a base, and `super` still reaches through the chain. This
|
|
2101
|
+
works because the parent of `inheritsFrom` is any expression. It also suits the type checker: a
|
|
2102
|
+
blueprint whose parent the checker cannot see stays open, whereas methods copied in with
|
|
2103
|
+
`_.extend Player.prototype, Greets` are invisible to it, so `--strict` reports each use as
|
|
2104
|
+
MS2009.
|
|
2105
|
+
|
|
2106
|
+
**Demonstration.**
|
|
2107
|
+
```mamba
|
|
2108
|
+
Serializable = (Base) ->
|
|
2109
|
+
blueprint Serialized inheritsFrom Base
|
|
2110
|
+
toJSONString: -> JSON.stringify @
|
|
2111
|
+
|
|
2112
|
+
Greets = (Base) ->
|
|
2113
|
+
blueprint Greeting inheritsFrom Base
|
|
2114
|
+
hello: -> "#{@name} waves"
|
|
2115
|
+
|
|
2116
|
+
blueprint Character
|
|
2117
|
+
constructor: (@name) ->
|
|
2118
|
+
|
|
2119
|
+
blueprint Player inheritsFrom Serializable Greets Character
|
|
2120
|
+
constructor: (name, @level) ->
|
|
2121
|
+
super name
|
|
2122
|
+
|
|
2123
|
+
blueprint Shopkeeper inheritsFrom Greets Character
|
|
2124
|
+
|
|
2125
|
+
mia = make Player 'Mia', 3
|
|
2126
|
+
present mia.toJSONString(), mia.hello()
|
|
2127
|
+
present (make Shopkeeper 'Odo').hello()
|
|
2128
|
+
present (make Shopkeeper 'Odo').toJSONString?() ? 'not serializable'
|
|
2129
|
+
```
|
|
2130
|
+
```text
|
|
2131
|
+
{"level":3,"name":"Mia"} Mia waves
|
|
2132
|
+
Odo waves
|
|
2133
|
+
not serializable
|
|
2134
|
+
```
|
|
2135
|
+
|
|
2136
|
+
### 66. Composition and delegation
|
|
2137
|
+
|
|
2138
|
+
**Explanation.** Instead of inheriting, a blueprint can hold other objects and forward calls to
|
|
2139
|
+
them. Constructor `@` parameters make the parts explicit, defaults supply standard parts, and a
|
|
2140
|
+
caller can pass a different part to change behaviour without a new subclass. A forwarding method
|
|
2141
|
+
is a one-liner, and `@part?.method()` tolerates an optional part.
|
|
2142
|
+
|
|
2143
|
+
**Demonstration.**
|
|
2144
|
+
```mamba
|
|
2145
|
+
blueprint Wallet
|
|
2146
|
+
constructor: (@gold = 0) ->
|
|
2147
|
+
pay: (amount) ->
|
|
2148
|
+
panic "short by #{amount - @gold} gold" if amount > @gold
|
|
2149
|
+
@gold -= amount
|
|
2150
|
+
|
|
2151
|
+
blueprint Player
|
|
2152
|
+
constructor: (@name, @wallet = (make Wallet), @pet = nothing) ->
|
|
2153
|
+
buy: (item, cost) ->
|
|
2154
|
+
@wallet.pay cost
|
|
2155
|
+
"#{@name} bought #{item}, #{@wallet.gold} gold left"
|
|
2156
|
+
petSound: -> @pet?.speak() ? 'silence'
|
|
2157
|
+
|
|
2158
|
+
rich = make Player 'Mia', (make Wallet 50), {speak: -> 'meow'}
|
|
2159
|
+
present rich.buy('sword', 30), rich.petSound()
|
|
2160
|
+
attempt (make Player 'Ben').buy 'shield', 5
|
|
2161
|
+
onFail problem then present problem.message
|
|
2162
|
+
```
|
|
2163
|
+
```text
|
|
2164
|
+
Mia bought sword, 20 gold left meow
|
|
2165
|
+
short by 5 gold
|
|
2166
|
+
```
|
|
2167
|
+
|
|
2168
|
+
### 67. Iterable blueprints with `Symbol.iterator`
|
|
2169
|
+
|
|
2170
|
+
**Explanation.** Giving a blueprint a `Symbol.iterator` method written as a generator makes every
|
|
2171
|
+
instance iterable, so `forEvery x from guild`, `[guild...]` and `Array.from guild` all work. Add it
|
|
2172
|
+
with `Guild::[Symbol.iterator] = -> yield from @members`. Quirk: the type checker does not yet count
|
|
2173
|
+
a splat constructor parameter (`(@members...) ->`) as a member, so assign the list in the body.
|
|
2174
|
+
|
|
2175
|
+
**Demonstration.**
|
|
2176
|
+
```mamba
|
|
2177
|
+
blueprint Guild
|
|
2178
|
+
constructor: (@name, members...) ->
|
|
2179
|
+
@members = members
|
|
2180
|
+
add: (member) -> @members.push member
|
|
2181
|
+
|
|
2182
|
+
Guild::[Symbol.iterator] = ->
|
|
2183
|
+
forEvery member in @members
|
|
2184
|
+
yield "#{member} of #{@name}"
|
|
2185
|
+
return
|
|
2186
|
+
|
|
2187
|
+
owls = make Guild 'Night Owls', 'Ana', 'Ben'
|
|
2188
|
+
owls.add 'Cy'
|
|
2189
|
+
forEvery line from owls
|
|
2190
|
+
present line
|
|
2191
|
+
present [owls...].length
|
|
2192
|
+
```
|
|
2193
|
+
```text
|
|
2194
|
+
Ana of Night Owls
|
|
2195
|
+
Ben of Night Owls
|
|
2196
|
+
Cy of Night Owls
|
|
2197
|
+
3
|
|
2198
|
+
```
|
|
2199
|
+
|
|
2200
|
+
### 68. Encapsulation with closures
|
|
2201
|
+
|
|
2202
|
+
**Explanation.** Blueprints have no `#private` fields, and `_name` properties are private only by
|
|
2203
|
+
convention. When state must be truly hidden, keep it in a local variable of a factory function and
|
|
2204
|
+
return an object of methods that close over it; nothing outside can reach the variable. Each call
|
|
2205
|
+
to the factory makes a fresh, independent copy of the state.
|
|
2206
|
+
|
|
2207
|
+
**Demonstration.**
|
|
2208
|
+
```mamba
|
|
2209
|
+
makeVault = (pin) ->
|
|
2210
|
+
gold = 0
|
|
2211
|
+
attempts = 0
|
|
2212
|
+
check = (entered) ->
|
|
2213
|
+
attempts += 1
|
|
2214
|
+
panic 'vault locked' if attempts > 3
|
|
2215
|
+
panic 'wrong pin' unless entered is pin
|
|
2216
|
+
deposit: (amount) -> gold += amount
|
|
2217
|
+
withdraw: (entered, amount) ->
|
|
2218
|
+
check entered
|
|
2219
|
+
gold -= amount
|
|
2220
|
+
|
|
2221
|
+
vault = makeVault 1234
|
|
2222
|
+
vault.deposit 100
|
|
2223
|
+
present vault.withdraw 1234, 30
|
|
2224
|
+
present vault.gold, Object.keys vault
|
|
2225
|
+
attempt vault.withdraw 1111, 10
|
|
2226
|
+
onFail problem then present problem.message
|
|
2227
|
+
```
|
|
2228
|
+
```text
|
|
2229
|
+
70
|
|
2230
|
+
undefined [ 'deposit', 'withdraw' ]
|
|
2231
|
+
wrong pin
|
|
2232
|
+
```
|
|
2233
|
+
|
|
2234
|
+
### 69. `toString`, `valueOf` and `Symbol.toPrimitive`
|
|
2235
|
+
|
|
2236
|
+
**Explanation.** A blueprint controls how its instances print and compare by defining `toString`
|
|
2237
|
+
(used by `String(x)` and `join`) and `valueOf` (used by `<`, `>` and
|
|
2238
|
+
arithmetic). Quirk: string interpolation compiles to `+` concatenation, not a JavaScript template
|
|
2239
|
+
literal, so when `valueOf` exists `"#{x}"` uses it; write `"#{String x}"` to get `toString`. Note that `is` compares identity, not
|
|
2240
|
+
value, so two equal-looking instances are never `is` each other; compare `+a is +b` or define an
|
|
2241
|
+
`equals` method.
|
|
2242
|
+
|
|
2243
|
+
**Demonstration.**
|
|
2244
|
+
```mamba
|
|
2245
|
+
blueprint Gold
|
|
2246
|
+
constructor: (@amount) ->
|
|
2247
|
+
toString: -> "#{@amount}g"
|
|
2248
|
+
valueOf: -> @amount
|
|
2249
|
+
equals: (other) -> +@ is +other
|
|
2250
|
+
|
|
2251
|
+
purse = make Gold 120
|
|
2252
|
+
price = make Gold 75
|
|
2253
|
+
present "the purse holds #{purse}, or #{String purse}"
|
|
2254
|
+
present purse > price, purse - price
|
|
2255
|
+
present [(make Gold 5), (make Gold 50), (make Gold 1)].sort((a, b) -> a - b).join ' < '
|
|
2256
|
+
present (make Gold 7) is (make Gold 7), (make Gold 7).equals(make Gold 7)
|
|
2257
|
+
```
|
|
2258
|
+
```text
|
|
2259
|
+
the purse holds 120, or 120g
|
|
2260
|
+
true 45
|
|
2261
|
+
1g < 5g < 50g
|
|
2262
|
+
false true
|
|
2263
|
+
```
|
|
2264
|
+
|
|
2265
|
+
## Complex data structures
|
|
2266
|
+
|
|
2267
|
+
### 70. Linked list
|
|
2268
|
+
|
|
2269
|
+
**Explanation.** A node blueprint with `(@val = 0, @next = nothing) ->` is the whole definition,
|
|
2270
|
+
and `reduceRight` builds a list from an array in one line. Reversal is the classic pointer dance,
|
|
2271
|
+
and destructuring assignment does it without a temporary: `[node.next, prev, node] = [prev, node,
|
|
2272
|
+
node.next]` evaluates the right side first. A generator method makes the list walkable with
|
|
2273
|
+
`forEvery … from` and spreadable with `[list...]`.
|
|
2274
|
+
|
|
2275
|
+
**Demonstration.**
|
|
2276
|
+
```mamba
|
|
2277
|
+
blueprint ListNode
|
|
2278
|
+
constructor: (@val = 0, @next = nothing) ->
|
|
2279
|
+
|
|
2280
|
+
fromArray = (items) -> items.reduceRight ((next, val) -> make ListNode val, next), nothing
|
|
2281
|
+
walk = (node) ->
|
|
2282
|
+
while node?
|
|
2283
|
+
yield node.val
|
|
2284
|
+
node = node.next
|
|
2285
|
+
return
|
|
2286
|
+
|
|
2287
|
+
reverse = (head) ->
|
|
2288
|
+
prev = nothing
|
|
2289
|
+
node = head
|
|
2290
|
+
[node.next, prev, node] = [prev, node, node.next] while node?
|
|
2291
|
+
prev
|
|
2292
|
+
|
|
2293
|
+
orders = fromArray ['ramen', 'udon', 'soba']
|
|
2294
|
+
present [walk(orders)...]
|
|
2295
|
+
present [walk(reverse orders)...]
|
|
2296
|
+
present [walk(nothing)...]
|
|
2297
|
+
```
|
|
2298
|
+
```text
|
|
2299
|
+
[ 'ramen', 'udon', 'soba' ]
|
|
2300
|
+
[ 'soba', 'udon', 'ramen' ]
|
|
2301
|
+
[]
|
|
2302
|
+
```
|
|
2303
|
+
|
|
2304
|
+
### 71. Stack
|
|
2305
|
+
|
|
2306
|
+
**Explanation.** An array is a stack: `push` and `pop` work on the end in O(1). The classic stack
|
|
2307
|
+
problem, matching brackets, reads cleanly with a lookup object and a `consider` with no subject
|
|
2308
|
+
deciding what each character does. `stack.at(-1)` peeks at the top without removing it, and an
|
|
2309
|
+
empty stack's `pop()` gives `missing`, which a soak or `?` handles.
|
|
2310
|
+
|
|
2311
|
+
**Demonstration.**
|
|
2312
|
+
```mamba
|
|
2313
|
+
pairs = {')': '(', ']': '[', '}': '{'}
|
|
2314
|
+
|
|
2315
|
+
balanced = (text) ->
|
|
2316
|
+
stack = []
|
|
2317
|
+
forEvery char in text
|
|
2318
|
+
consider
|
|
2319
|
+
when char in ['(', '[', '{'] then stack.push char
|
|
2320
|
+
when pairs[char]?
|
|
2321
|
+
return no unless stack.pop() is pairs[char]
|
|
2322
|
+
stack.length is 0
|
|
2323
|
+
|
|
2324
|
+
present balanced('{order: [1, (2)]}'), balanced('([)]'), balanced('((')
|
|
2325
|
+
undo = ['add ramen', 'add udon']
|
|
2326
|
+
present undo.at(-1), undo.pop(), undo.pop(), undo.pop()
|
|
2327
|
+
```
|
|
2328
|
+
```text
|
|
2329
|
+
true false false
|
|
2330
|
+
add udon add udon add ramen undefined
|
|
2331
|
+
```
|
|
2332
|
+
|
|
2333
|
+
### 72. Queue
|
|
2334
|
+
|
|
2335
|
+
**Explanation.** `shift()` on an array is O(n), so a busy queue keeps a head index instead and
|
|
2336
|
+
compacts only now and then; `push` stays O(1) at the tail. Wrapping that in a blueprint with a
|
|
2337
|
+
`size` method and an iterator gives a queue that reads like the problem: tickets in, tickets out,
|
|
2338
|
+
first come first served.
|
|
2339
|
+
|
|
2340
|
+
**Demonstration.**
|
|
2341
|
+
```mamba
|
|
2342
|
+
blueprint Queue
|
|
2343
|
+
constructor: ->
|
|
2344
|
+
@items = []
|
|
2345
|
+
@head = 0
|
|
2346
|
+
enqueue: (item) -> @items.push item
|
|
2347
|
+
size: -> @items.length - @head
|
|
2348
|
+
dequeue: ->
|
|
2349
|
+
return nothing if @size() is 0
|
|
2350
|
+
item = @items[@head]
|
|
2351
|
+
@head += 1
|
|
2352
|
+
if @head > 32 and @head * 2 > @items.length
|
|
2353
|
+
@items = @items[@head..]
|
|
2354
|
+
@head = 0
|
|
2355
|
+
item
|
|
2356
|
+
|
|
2357
|
+
kitchen = make Queue
|
|
2358
|
+
kitchen.enqueue "ticket #{n}" forEvery n in [1..3]
|
|
2359
|
+
present kitchen.dequeue(), kitchen.size()
|
|
2360
|
+
kitchen.enqueue 'ticket 4'
|
|
2361
|
+
present (kitchen.dequeue() while kitchen.size() > 0)
|
|
2362
|
+
present kitchen.dequeue()
|
|
2363
|
+
```
|
|
2364
|
+
```text
|
|
2365
|
+
ticket 1 2
|
|
2366
|
+
[ 'ticket 2', 'ticket 3', 'ticket 4' ]
|
|
2367
|
+
null
|
|
2368
|
+
```
|
|
2369
|
+
|
|
2370
|
+
### 73. Hash map with separate chaining
|
|
2371
|
+
|
|
2372
|
+
**Explanation.** Writing the hash map yourself shows how `Map` works inside: a hash function picks
|
|
2373
|
+
a bucket, each bucket is a list of `[key, value]` pairs, and lookups scan only one bucket.
|
|
2374
|
+
Destructuring in the loop variable (`forEvery [k, v], i in bucket`) names the pair. In real code use
|
|
2375
|
+
`make Map`, which keeps insertion order and accepts any key.
|
|
2376
|
+
|
|
2377
|
+
**Demonstration.**
|
|
2378
|
+
```mamba
|
|
2379
|
+
blueprint HashMap
|
|
2380
|
+
constructor: (@size = 8) ->
|
|
2381
|
+
@buckets = ([] forEvery i in [0...@size])
|
|
2382
|
+
hash: (key) ->
|
|
2383
|
+
h = 0
|
|
2384
|
+
h = (h * 31 + key.charCodeAt(i)) % @size forEvery i in [0...key.length]
|
|
2385
|
+
h
|
|
2386
|
+
set: (key, value) ->
|
|
2387
|
+
bucket = @buckets[@hash key]
|
|
2388
|
+
forEvery [k], i in bucket when k is key
|
|
2389
|
+
return bucket[i][1] = value
|
|
2390
|
+
bucket.push [key, value]
|
|
2391
|
+
get: (key) ->
|
|
2392
|
+
forEvery [k, v] in @buckets[@hash key] when k is key
|
|
2393
|
+
return v
|
|
2394
|
+
missing
|
|
2395
|
+
|
|
2396
|
+
prices = make HashMap
|
|
2397
|
+
prices.set dish, dish.length forEvery dish in ['ramen', 'udon', 'soba']
|
|
2398
|
+
prices.set 'udon', 8
|
|
2399
|
+
present prices.get('ramen'), prices.get('udon'), prices.get('eel')
|
|
2400
|
+
```
|
|
2401
|
+
```text
|
|
2402
|
+
5 8 undefined
|
|
2403
|
+
```
|
|
2404
|
+
|
|
2405
|
+
### 74. Binary search tree with generator traversals
|
|
2406
|
+
|
|
2407
|
+
**Explanation.** Each traversal of a tree is a recursive generator: `yield from` delegates to the
|
|
2408
|
+
left and right subtrees, so in-order, pre-order and post-order differ only in where the node's own
|
|
2409
|
+
`yield` sits. A guard, `return unless node?`, ends the recursion. In-order traversal of a
|
|
2410
|
+
BST visits the values sorted, which is the quickest correctness check.
|
|
2411
|
+
|
|
2412
|
+
**Demonstration.**
|
|
2413
|
+
```mamba
|
|
2414
|
+
blueprint TreeNode
|
|
2415
|
+
constructor: (@val, @left = nothing, @right = nothing) ->
|
|
2416
|
+
|
|
2417
|
+
insert = (node, val) ->
|
|
2418
|
+
return make TreeNode val unless node?
|
|
2419
|
+
if val < node.val then node.left = insert node.left, val
|
|
2420
|
+
otherwise node.right = insert node.right, val
|
|
2421
|
+
node
|
|
2422
|
+
|
|
2423
|
+
inOrder = (node) ->
|
|
2424
|
+
return unless node?
|
|
2425
|
+
yield from inOrder node.left
|
|
2426
|
+
yield node.val
|
|
2427
|
+
yield from inOrder node.right
|
|
2428
|
+
|
|
2429
|
+
preOrder = (node) ->
|
|
2430
|
+
return unless node?
|
|
2431
|
+
yield node.val
|
|
2432
|
+
yield from preOrder node.left
|
|
2433
|
+
yield from preOrder node.right
|
|
2434
|
+
|
|
2435
|
+
root = [50, 30, 70, 20, 40, 60].reduce ((tree, score) -> insert tree, score), nothing
|
|
2436
|
+
present [inOrder(root)...]
|
|
2437
|
+
present [preOrder(root)...]
|
|
2438
|
+
```
|
|
2439
|
+
```text
|
|
2440
|
+
[ 20, 30, 40, 50, 60, 70 ]
|
|
2441
|
+
[ 50, 30, 20, 40, 70, 60 ]
|
|
2442
|
+
```
|
|
2443
|
+
|
|
2444
|
+
### 75. Graph: BFS and DFS
|
|
2445
|
+
|
|
2446
|
+
**Explanation.** An adjacency list is a `Map` from a node to its neighbours, built from an edge
|
|
2447
|
+
list in one loop. Breadth-first search uses a queue and finds the fewest hops; depth-first search
|
|
2448
|
+
recurses with a `Set` of visited nodes passed as a default parameter. `forEvery [a, b] in edges`
|
|
2449
|
+
destructures each edge, and `?` in `graph.get(a) ? []` treats a missing node as having no
|
|
2450
|
+
neighbours.
|
|
2451
|
+
|
|
2452
|
+
**Demonstration.**
|
|
2453
|
+
```mamba
|
|
2454
|
+
edges = [['inn', 'market'], ['inn', 'gate'], ['market', 'castle'], ['gate', 'castle'], ['castle', 'tower']]
|
|
2455
|
+
graph = make Map
|
|
2456
|
+
forEvery [a, b] in edges
|
|
2457
|
+
graph.set a, [(graph.get(a) ? [])..., b]
|
|
2458
|
+
graph.set b, [(graph.get(b) ? [])..., a]
|
|
2459
|
+
|
|
2460
|
+
bfs = (start, goal) ->
|
|
2461
|
+
queue = [[start]]
|
|
2462
|
+
seen = make Set [start]
|
|
2463
|
+
while queue.length
|
|
2464
|
+
path = queue.shift()
|
|
2465
|
+
return path if path.at(-1) is goal
|
|
2466
|
+
forEvery next in graph.get(path.at(-1)) when not seen.has next
|
|
2467
|
+
seen.add next
|
|
2468
|
+
queue.push [path..., next]
|
|
2469
|
+
nothing
|
|
2470
|
+
|
|
2471
|
+
dfs = (node, seen = make Set) ->
|
|
2472
|
+
seen.add node
|
|
2473
|
+
dfs next, seen forEvery next in graph.get(node) when not seen.has next
|
|
2474
|
+
[seen...]
|
|
2475
|
+
|
|
2476
|
+
present bfs('inn', 'tower').join ' -> '
|
|
2477
|
+
present dfs('inn').join ', '
|
|
2478
|
+
```
|
|
2479
|
+
```text
|
|
2480
|
+
inn -> market -> castle -> tower
|
|
2481
|
+
inn, market, castle, gate, tower
|
|
2482
|
+
```
|
|
2483
|
+
|
|
2484
|
+
### 76. Binary heap (priority queue)
|
|
2485
|
+
|
|
2486
|
+
**Explanation.** JavaScript has no built-in heap, so the course writes one: a complete binary tree
|
|
2487
|
+
stored in an array, with the parent of `i` at `(i - 1) >> 1`. Swapping two elements is one
|
|
2488
|
+
destructuring line, `bail` ends the sift as soon as order is restored, and a comparator parameter
|
|
2489
|
+
with a default turns the same blueprint into a min-heap or a max-heap.
|
|
2490
|
+
|
|
2491
|
+
**Demonstration.**
|
|
2492
|
+
```mamba
|
|
2493
|
+
blueprint Heap
|
|
2494
|
+
constructor: (@cmp = ((a, b) -> a - b)) -> @a = []
|
|
2495
|
+
size: -> @a.length
|
|
2496
|
+
push: (x) ->
|
|
2497
|
+
i = @a.push(x) - 1
|
|
2498
|
+
while i > 0
|
|
2499
|
+
p = (i - 1) >> 1
|
|
2500
|
+
bail if @cmp(@a[i], @a[p]) >= 0
|
|
2501
|
+
[@a[i], @a[p]] = [@a[p], @a[i]]
|
|
2502
|
+
i = p
|
|
2503
|
+
pop: ->
|
|
2504
|
+
[top, last] = [@a[0], @a.pop()]
|
|
2505
|
+
return top unless @a.length
|
|
2506
|
+
[@a[0], i] = [last, 0]
|
|
2507
|
+
loop
|
|
2508
|
+
[l, r, m] = [2 * i + 1, 2 * i + 2, i]
|
|
2509
|
+
m = l if l < @a.length and @cmp(@a[l], @a[m]) < 0
|
|
2510
|
+
m = r if r < @a.length and @cmp(@a[r], @a[m]) < 0
|
|
2511
|
+
bail if m is i
|
|
2512
|
+
[@a[i], @a[m]] = [@a[m], @a[i]]
|
|
2513
|
+
i = m
|
|
2514
|
+
top
|
|
2515
|
+
urgent = make Heap (a, b) -> b.priority - a.priority
|
|
2516
|
+
urgent.push {dish: d, priority: p} forEvery [d, p] in [['tea', 1], ['ramen', 5], ['mochi', 3]]
|
|
2517
|
+
present (urgent.pop().dish while urgent.size())
|
|
2518
|
+
```
|
|
2519
|
+
```text
|
|
2520
|
+
[ 'ramen', 'mochi', 'tea' ]
|
|
2521
|
+
```
|
|
2522
|
+
|
|
2523
|
+
### 77. Trie
|
|
2524
|
+
|
|
2525
|
+
**Explanation.** A trie stores words one character per level, so every word sharing a prefix
|
|
2526
|
+
shares a path. Each node is a plain object of children plus an `end` flag; `node.children[char] ?=
|
|
2527
|
+
{children: {}, end: no}` creates a branch only when needed. Prefix search walks down once and then
|
|
2528
|
+
collects the words below with a recursive generator.
|
|
2529
|
+
|
|
2530
|
+
**Demonstration.**
|
|
2531
|
+
```mamba
|
|
2532
|
+
blueprint Trie
|
|
2533
|
+
constructor: -> @root = {children: {}, end: no}
|
|
2534
|
+
insert: (word) ->
|
|
2535
|
+
node = @root
|
|
2536
|
+
forEvery char in word
|
|
2537
|
+
node = node.children[char] ?= {children: {}, end: no}
|
|
2538
|
+
node.end = yes
|
|
2539
|
+
words: (node, prefix) ->
|
|
2540
|
+
yield prefix if node.end
|
|
2541
|
+
forEvery own char, child of node.children
|
|
2542
|
+
yield from @words child, prefix + char
|
|
2543
|
+
return
|
|
2544
|
+
startsWith: (prefix) ->
|
|
2545
|
+
node = @root
|
|
2546
|
+
forEvery char in prefix
|
|
2547
|
+
node = node.children[char]
|
|
2548
|
+
return [] unless node exists
|
|
2549
|
+
[@words(node, prefix)...]
|
|
2550
|
+
|
|
2551
|
+
menu = make Trie
|
|
2552
|
+
insertDish = (dish :: String) -> menu.insert dish
|
|
2553
|
+
insertDish dish forEvery dish in ['ramen', 'rice', 'risotto', 'udon']
|
|
2554
|
+
present menu.startsWith 'ri'
|
|
2555
|
+
present menu.startsWith 'r'
|
|
2556
|
+
present menu.startsWith 'x'
|
|
2557
|
+
```
|
|
2558
|
+
```text
|
|
2559
|
+
[ 'rice', 'risotto' ]
|
|
2560
|
+
[ 'ramen', 'rice', 'risotto' ]
|
|
2561
|
+
[]
|
|
2562
|
+
```
|
|
2563
|
+
|
|
2564
|
+
## Functional programming
|
|
2565
|
+
|
|
2566
|
+
### 78. map, filter, reduce, or a comprehension
|
|
2567
|
+
|
|
2568
|
+
**Explanation.** Prefer the bundled collection helpers for data transformations. `_.filter`
|
|
2569
|
+
selects orders, `_.pluck` extracts a field, and `_.reduce values, callback, seed` folds them into
|
|
2570
|
+
one value. A comprehension is also useful when teaching loop expressions:
|
|
2571
|
+
`(o.price forEvery o in orders when o.table is 4)` combines filtering and mapping. Here both
|
|
2572
|
+
forms produce the same prices; `_.every` and `_.some` answer collection-wide questions.
|
|
2573
|
+
|
|
2574
|
+
**Demonstration.**
|
|
2575
|
+
```mamba
|
|
2576
|
+
orders = [
|
|
2577
|
+
{dish: 'ramen', table: 4, price: 9}
|
|
2578
|
+
{dish: 'udon', table: 2, price: 8}
|
|
2579
|
+
{dish: 'mochi', table: 4, price: 3}
|
|
2580
|
+
]
|
|
2581
|
+
tableOrders = _.filter orders, (order) -> order.table is 4
|
|
2582
|
+
viaLibrary = _.pluck tableOrders, 'price'
|
|
2583
|
+
viaComprehension = (order.price forEvery order in orders when order.table is 4)
|
|
2584
|
+
present viaLibrary, viaComprehension
|
|
2585
|
+
|
|
2586
|
+
bill = _.reduce viaComprehension, ((sum, price) -> sum + price), 0
|
|
2587
|
+
present "table 4 owes #{bill}"
|
|
2588
|
+
present _.every(orders, (order) -> order.price > 2), _.some(orders, (order) -> order.price > 8)
|
|
2589
|
+
```
|
|
2590
|
+
```text
|
|
2591
|
+
[ 9, 3 ] [ 9, 3 ]
|
|
2592
|
+
table 4 owes 12
|
|
2593
|
+
true true
|
|
2594
|
+
```
|
|
2595
|
+
|
|
2596
|
+
### 79. Compose and pipe
|
|
2597
|
+
|
|
2598
|
+
**Explanation.** `compose` applies functions right to left and `pipe` left to right; both are one
|
|
2599
|
+
line with a rest parameter and `reduce`. Small single-purpose functions (`trim`, `lower`,
|
|
2600
|
+
`slugify`) then combine into a pipeline without temporary variables. The standard library also has
|
|
2601
|
+
`_.compose`.
|
|
2602
|
+
|
|
2603
|
+
**Demonstration.**
|
|
2604
|
+
```mamba
|
|
2605
|
+
compose = (fns...) -> (x) -> fns.reduceRight ((value, fn) -> fn value), x
|
|
2606
|
+
pipe = (fns...) -> (x) -> fns.reduce ((value, fn) -> fn value), x
|
|
2607
|
+
|
|
2608
|
+
trim = (text) -> text.trim()
|
|
2609
|
+
lower = (text) -> text.toLowerCase()
|
|
2610
|
+
dashes = (text) -> text.replace /\s+/g, '-'
|
|
2611
|
+
slugify = pipe trim, lower, dashes
|
|
2612
|
+
present slugify ' Spicy Miso Ramen '
|
|
2613
|
+
|
|
2614
|
+
addTax = (price) -> price * 1.5
|
|
2615
|
+
round = (price) -> Math.round price
|
|
2616
|
+
present compose(round, addTax)(9)
|
|
2617
|
+
present _.compose(round, addTax)(9)
|
|
2618
|
+
```
|
|
2619
|
+
```text
|
|
2620
|
+
spicy-miso-ramen
|
|
2621
|
+
14
|
|
2622
|
+
14
|
|
2623
|
+
```
|
|
2624
|
+
|
|
2625
|
+
### 80. Currying and partial application
|
|
2626
|
+
|
|
2627
|
+
**Explanation.** Chained arrows make curried functions directly: `(rate) -> (price) -> …` takes
|
|
2628
|
+
one argument at a time, and supplying the first gives a specialised function. A general `curry`
|
|
2629
|
+
helper collects arguments until it has `fn.length` of them, using rest and spread. Partial
|
|
2630
|
+
application is the same idea with `bind` or a closure: fix some arguments now, pass the rest later.
|
|
2631
|
+
|
|
2632
|
+
**Demonstration.**
|
|
2633
|
+
```mamba
|
|
2634
|
+
discount = (rate) -> (price) -> price - price * rate
|
|
2635
|
+
happyHour = discount 0.5
|
|
2636
|
+
present [10, 8, 4].map happyHour
|
|
2637
|
+
|
|
2638
|
+
curry = (fn) ->
|
|
2639
|
+
collect = (args...) ->
|
|
2640
|
+
if args.length >= fn.length then fn args... otherwise (more...) -> collect args..., more...
|
|
2641
|
+
|
|
2642
|
+
ticket = curry (table, dish, qty) -> "table #{table}: #{qty} x #{dish}"
|
|
2643
|
+
present ticket(4)('ramen')(2)
|
|
2644
|
+
present ticket(4, 'udon')(1)
|
|
2645
|
+
forTable2 = ticket.bind nothing, 2
|
|
2646
|
+
present forTable2 'mochi', 3
|
|
2647
|
+
```
|
|
2648
|
+
```text
|
|
2649
|
+
[ 5, 4, 2 ]
|
|
2650
|
+
table 4: 2 x ramen
|
|
2651
|
+
table 4: 1 x udon
|
|
2652
|
+
table 2: 3 x mochi
|
|
2653
|
+
```
|
|
2654
|
+
|
|
2655
|
+
### 81. Memoization
|
|
2656
|
+
|
|
2657
|
+
**Explanation.** A memoizing wrapper keeps a `Map` from arguments to results in a closure, so a
|
|
2658
|
+
repeated call returns the stored answer. `cache.get(key) ? compute()` is not enough when a result
|
|
2659
|
+
may be `nothing`, so test `cache.has key`. The standard library's `_.memoize` does the same for
|
|
2660
|
+
one-argument functions. Memoizing a recursive function only helps when the recursion calls the
|
|
2661
|
+
memoized name, as `fib` does here.
|
|
2662
|
+
|
|
2663
|
+
**Demonstration.**
|
|
2664
|
+
```mamba
|
|
2665
|
+
memoize = (fn) ->
|
|
2666
|
+
cache = make Map
|
|
2667
|
+
(args...) ->
|
|
2668
|
+
key = JSON.stringify args
|
|
2669
|
+
cache.set key, fn(args...) unless cache.has key
|
|
2670
|
+
cache.get key
|
|
2671
|
+
|
|
2672
|
+
calls = 0
|
|
2673
|
+
fib = memoize (n) ->
|
|
2674
|
+
calls += 1
|
|
2675
|
+
if n < 2 then n otherwise fib(n - 1) + fib(n - 2)
|
|
2676
|
+
present fib(40), "after #{calls} calls"
|
|
2677
|
+
|
|
2678
|
+
square = _.memoize (n) ->
|
|
2679
|
+
present "computing #{n}"
|
|
2680
|
+
n * n
|
|
2681
|
+
present square(9), square(9)
|
|
2682
|
+
```
|
|
2683
|
+
```text
|
|
2684
|
+
102334155 after 41 calls
|
|
2685
|
+
computing 9
|
|
2686
|
+
81 81
|
|
2687
|
+
```
|
|
2688
|
+
|
|
2689
|
+
### 82. Immutable updates with spread
|
|
2690
|
+
|
|
2691
|
+
**Explanation.** Instead of changing an object, build a new one: `{order..., status: 'paid'}`
|
|
2692
|
+
copies the order and overrides one key, and `[list..., item]` appends without `push`. Nested data
|
|
2693
|
+
needs a spread at each level that changes. The originals stay intact, so earlier versions can be
|
|
2694
|
+
compared, undone or rendered side by side; `Object.freeze` turns an accidental write into a
|
|
2695
|
+
silent no-op (or an error in strict-mode code).
|
|
2696
|
+
|
|
2697
|
+
**Demonstration.**
|
|
2698
|
+
```mamba
|
|
2699
|
+
order = Object.freeze
|
|
2700
|
+
table: 4
|
|
2701
|
+
items: ['ramen']
|
|
2702
|
+
status: 'open'
|
|
2703
|
+
tip: {rate: 0.1}
|
|
2704
|
+
|
|
2705
|
+
paid = {order..., status: 'paid'}
|
|
2706
|
+
more = {order..., items: [order.items..., 'mochi']}
|
|
2707
|
+
generous = {order..., tip: {order.tip..., rate: 0.2}}
|
|
2708
|
+
order.status = 'hacked'
|
|
2709
|
+
|
|
2710
|
+
present order.status, order.items, order.tip.rate
|
|
2711
|
+
present paid.status, more.items, generous.tip.rate
|
|
2712
|
+
present paid.items is order.items
|
|
2713
|
+
```
|
|
2714
|
+
```text
|
|
2715
|
+
open [ 'ramen' ] 0.1
|
|
2716
|
+
paid [ 'ramen', 'mochi' ] 0.2
|
|
2717
|
+
true
|
|
2718
|
+
```
|
|
2719
|
+
|
|
2720
|
+
### 83. The standard library `_`
|
|
2721
|
+
|
|
2722
|
+
**Explanation.** `_` is Underscore ported to MambaScript and shipped inside the compiler, so there
|
|
2723
|
+
is nothing to install: using `_` in a program inserts `var _ = require('mambascript/stdlib')`, and
|
|
2724
|
+
no global is created. It covers collections (`pluck`, `groupBy`, `sortBy`, `max`), arrays (`uniq`,
|
|
2725
|
+
`flatten`, `zip`), functions (`memoize`, `once`, `compose`) and objects (`cloneDeep`, `isEqual`).
|
|
2726
|
+
Chain with `_(list).chain()…value()`; there is no `_.chain`. Keep `_` free for this library,
|
|
2727
|
+
including in parameters and destructuring. In the interactive REPL, `_` instead holds the last
|
|
2728
|
+
result and `stdlib` names the library. `groupBy`, `indexBy` and `countBy` accept field names;
|
|
2729
|
+
`sortBy`, `min` and `max` require functions when selecting by a field. `extend` mutates its
|
|
2730
|
+
target, so pass a fresh `{}` when you want a shallow copy.
|
|
2731
|
+
|
|
2732
|
+
**Demonstration.**
|
|
2733
|
+
```mamba
|
|
2734
|
+
orders = [
|
|
2735
|
+
{dish: 'ramen', table: 4, price: 9}
|
|
2736
|
+
{dish: 'udon', table: 2, price: 8}
|
|
2737
|
+
{dish: 'mochi', table: 4, price: 3}
|
|
2738
|
+
]
|
|
2739
|
+
present _.pluck orders, 'dish'
|
|
2740
|
+
present _.keys _.groupBy orders, (order) -> order.table
|
|
2741
|
+
ranked = _.sortBy orders, (order) -> order.price
|
|
2742
|
+
present _.pluck ranked, 'dish'
|
|
2743
|
+
present _.uniq([4, 2, 4]), _.flatten([[1, [2]], 3]), _.zip(['a', 'b'], [1, 2])
|
|
2744
|
+
present _(orders).chain().pluck('price').max().value()
|
|
2745
|
+
present _.isEqual {a: [1, 2]}, {a: [1, 2]}
|
|
2746
|
+
setup = _.once -> present 'kitchen opened'
|
|
2747
|
+
setup()
|
|
2748
|
+
setup()
|
|
2749
|
+
```
|
|
2750
|
+
```text
|
|
2751
|
+
[ 'ramen', 'udon', 'mochi' ]
|
|
2752
|
+
[ '2', '4' ]
|
|
2753
|
+
[ 'mochi', 'udon', 'ramen' ]
|
|
2754
|
+
[ 4, 2 ] [ 1, 2, 3 ] [ [ 'a', 1 ], [ 'b', 2 ] ]
|
|
2755
|
+
9
|
|
2756
|
+
true
|
|
2757
|
+
kitchen opened
|
|
2758
|
+
```
|
|
2759
|
+
|
|
2760
|
+
### 84. Lazy pipelines with generators
|
|
2761
|
+
|
|
2762
|
+
**Explanation.** Generator helpers (`mapLazy`, `filterLazy`, `take`) pass values along one at a
|
|
2763
|
+
time, so a pipeline over an endless source does only the work its consumer asks for. Each helper is a
|
|
2764
|
+
`forEvery … from` loop that yields, and a `return` so the generator does not collect its loop.
|
|
2765
|
+
Quirk: a `return` inside a loop that ends a generator fails to compile in 2.0, so leave such a loop
|
|
2766
|
+
with `bail` and put the `return` after it. Use this when the source is large, infinite, or expensive per item.
|
|
2767
|
+
|
|
2768
|
+
**Demonstration.**
|
|
2769
|
+
```mamba
|
|
2770
|
+
naturals = ->
|
|
2771
|
+
n = 1
|
|
2772
|
+
loop
|
|
2773
|
+
yield n++
|
|
2774
|
+
|
|
2775
|
+
mapLazy = (source, fn) -> yield fn value forEvery value from source; return
|
|
2776
|
+
filterLazy = (source, test) -> yield value forEvery value from source when test value; return
|
|
2777
|
+
take = (source, count) ->
|
|
2778
|
+
forEvery value from source
|
|
2779
|
+
yield value
|
|
2780
|
+
count -= 1
|
|
2781
|
+
bail if count is 0
|
|
2782
|
+
return
|
|
2783
|
+
|
|
2784
|
+
checked = 0
|
|
2785
|
+
squares = mapLazy naturals(), (n) -> checked += 1; n * n
|
|
2786
|
+
evenSquares = filterLazy squares, (n) -> n % 2 is 0
|
|
2787
|
+
present [take(evenSquares, 4)...]
|
|
2788
|
+
present "checked only #{checked} numbers"
|
|
2789
|
+
```
|
|
2790
|
+
```text
|
|
2791
|
+
[ 4, 16, 36, 64 ]
|
|
2792
|
+
checked only 8 numbers
|
|
2793
|
+
```
|
|
2794
|
+
|
|
2795
|
+
### 85. MambaView: HTML templates as functions
|
|
2796
|
+
|
|
2797
|
+
**Explanation.** MambaView renders HTML from a MambaScript function in which every tag is a
|
|
2798
|
+
function: `div '#menu.card', -> li dish forEvery dish in @dishes`. The data object is `@` inside the
|
|
2799
|
+
template, a leading `'#id.class'` string sets the id and classes, an attribute object comes next,
|
|
2800
|
+
and the content is a string, number or a function body. `MambaView.render template, data` returns
|
|
2801
|
+
the HTML string, and `MambaView.compile` returns a reusable function.
|
|
2802
|
+
|
|
2803
|
+
**Demonstration.**
|
|
2804
|
+
```mamba
|
|
2805
|
+
grab {MambaView} from 'mambascript'
|
|
2806
|
+
|
|
2807
|
+
menuPage = ->
|
|
2808
|
+
div '#menu.card', ->
|
|
2809
|
+
h1 @title
|
|
2810
|
+
ul ->
|
|
2811
|
+
forEvery dish in @dishes
|
|
2812
|
+
li {class: (if dish.vegan then 'vegan' otherwise nothing)}, "#{dish.name} $#{dish.price}"
|
|
2813
|
+
p 'sold out today' if @dishes.length is 0
|
|
2814
|
+
|
|
2815
|
+
data =
|
|
2816
|
+
title: 'Lunch'
|
|
2817
|
+
dishes: [{name: 'ramen', price: 9, vegan: no}, {name: 'tofu', price: 7, vegan: yes}]
|
|
2818
|
+
present MambaView.render menuPage, data
|
|
2819
|
+
|
|
2820
|
+
render = MambaView.compile menuPage
|
|
2821
|
+
present render title: 'Dinner', dishes: []
|
|
2822
|
+
```
|
|
2823
|
+
```text
|
|
2824
|
+
<div id="menu" class="card"><h1>Lunch</h1><ul><li>ramen $9</li><li class="vegan">tofu $7</li></ul></div>
|
|
2825
|
+
<div id="menu" class="card"><h1>Dinner</h1><ul></ul><p>sold out today</p></div>
|
|
2826
|
+
```
|
|
2827
|
+
|
|
2828
|
+
## Design patterns
|
|
2829
|
+
|
|
2830
|
+
### 86. Singleton
|
|
2831
|
+
|
|
2832
|
+
**Explanation.** A module-level value is already a singleton, but when the instance must be made
|
|
2833
|
+
lazily, a static method with `?=` does it in one line: `@instance ?= make this`. `?=` assigns only
|
|
2834
|
+
when the static member is absent, so every later call returns the same object. Keep singletons
|
|
2835
|
+
for things there must be exactly one of (a configuration, a connection pool), not as global
|
|
2836
|
+
variables in disguise.
|
|
2837
|
+
|
|
2838
|
+
**Demonstration.**
|
|
2839
|
+
```mamba
|
|
2840
|
+
blueprint Config
|
|
2841
|
+
@get: -> @instance ?= make Config
|
|
2842
|
+
constructor: ->
|
|
2843
|
+
present 'loading config once'
|
|
2844
|
+
@settings = {currency: 'gold', taxRate: 0.1}
|
|
2845
|
+
|
|
2846
|
+
first = Config.get()
|
|
2847
|
+
second = Config.get()
|
|
2848
|
+
first.settings.taxRate = 0.2
|
|
2849
|
+
present second.settings.taxRate
|
|
2850
|
+
present first is second
|
|
2851
|
+
```
|
|
2852
|
+
```text
|
|
2853
|
+
loading config once
|
|
2854
|
+
0.2
|
|
2855
|
+
true
|
|
2856
|
+
```
|
|
2857
|
+
|
|
2858
|
+
### 87. Factory
|
|
2859
|
+
|
|
2860
|
+
**Explanation.** A factory decides which blueprint to build from data, so callers never name the
|
|
2861
|
+
concrete blueprint. A lookup object from a kind to a blueprint replaces a growing `if` ladder, and
|
|
2862
|
+
`make registry[kind] args...` builds whatever was registered. An unknown kind is a clear `panic`
|
|
2863
|
+
rather than an `undefined is not a constructor` error later.
|
|
2864
|
+
|
|
2865
|
+
**Demonstration.**
|
|
2866
|
+
```mamba
|
|
2867
|
+
blueprint Warrior
|
|
2868
|
+
constructor: (@name) -> @hp = 120
|
|
2869
|
+
blueprint Mage
|
|
2870
|
+
constructor: (@name) -> @hp = 70
|
|
2871
|
+
blueprint Rogue
|
|
2872
|
+
constructor: (@name) -> @hp = 90
|
|
2873
|
+
|
|
2874
|
+
classes = {warrior: Warrior, mage: Mage, rogue: Rogue}
|
|
2875
|
+
createHero = (kind, name) ->
|
|
2876
|
+
Hero = classes[kind]
|
|
2877
|
+
panic "no hero class called #{kind}" unless Hero?
|
|
2878
|
+
make Hero name
|
|
2879
|
+
|
|
2880
|
+
party = (createHero kind, name forEvery [kind, name] in [['mage', 'Cy'], ['warrior', 'Ana']])
|
|
2881
|
+
present ("#{hero.name} the #{hero.constructor.name} (#{hero.hp} hp)" forEvery hero in party)
|
|
2882
|
+
attempt createHero 'bard', 'Lu'
|
|
2883
|
+
onFail problem then present problem.message
|
|
2884
|
+
```
|
|
2885
|
+
```text
|
|
2886
|
+
[ 'Cy the Mage (70 hp)', 'Ana the Warrior (120 hp)' ]
|
|
2887
|
+
no hero class called bard
|
|
2888
|
+
```
|
|
2889
|
+
|
|
2890
|
+
### 88. Observer
|
|
2891
|
+
|
|
2892
|
+
**Explanation.** An emitter keeps a list of listeners per event name and calls them when the event
|
|
2893
|
+
fires. `@listeners[event] ?= []` creates each list on first use, `on` returns an unsubscribe
|
|
2894
|
+
function (a closure over the listener), and the soak in `@listeners[event]?.slice()` makes an
|
|
2895
|
+
event nobody listens to a no-op. Node's `EventEmitter` is the same idea; this is the whole pattern.
|
|
2896
|
+
|
|
2897
|
+
**Demonstration.**
|
|
2898
|
+
```mamba
|
|
2899
|
+
blueprint Emitter
|
|
2900
|
+
constructor: -> @listeners = {}
|
|
2901
|
+
on: (event, listener) ->
|
|
2902
|
+
(@listeners[event] ?= []).push listener
|
|
2903
|
+
=> @listeners[event] = (l forEvery l in @listeners[event] when l isnt listener)
|
|
2904
|
+
emit: (event, data...) ->
|
|
2905
|
+
listener data... forEvery listener in @listeners[event]?.slice() ? []
|
|
2906
|
+
return
|
|
2907
|
+
|
|
2908
|
+
kitchen = make Emitter
|
|
2909
|
+
stopWaiter = kitchen.on 'ready', (dish, table) -> present "waiter: #{dish} to table #{table}"
|
|
2910
|
+
kitchen.on 'ready', (dish) -> present "board: #{dish} is up"
|
|
2911
|
+
kitchen.emit 'ready', 'ramen', 4
|
|
2912
|
+
stopWaiter()
|
|
2913
|
+
kitchen.emit 'ready', 'udon', 2
|
|
2914
|
+
kitchen.emit 'closed'
|
|
2915
|
+
```
|
|
2916
|
+
```text
|
|
2917
|
+
waiter: ramen to table 4
|
|
2918
|
+
board: ramen is up
|
|
2919
|
+
board: udon is up
|
|
2920
|
+
```
|
|
2921
|
+
|
|
2922
|
+
### 89. Strategy
|
|
2923
|
+
|
|
2924
|
+
**Explanation.** A strategy is a function chosen at run time, so in MambaScript it is just a value
|
|
2925
|
+
in an object: `pricing[customer.tier] ? pricing.standard` picks one, with `?` supplying the
|
|
2926
|
+
default. Swapping behaviour then needs no subclass and no `consider`. Pass strategies as
|
|
2927
|
+
parameters with defaults so the common case needs no argument.
|
|
2928
|
+
|
|
2929
|
+
**Demonstration.**
|
|
2930
|
+
```mamba
|
|
2931
|
+
pricing =
|
|
2932
|
+
standard: (total) -> total
|
|
2933
|
+
member: (total) -> total * 0.9
|
|
2934
|
+
happyHour: (total) -> Math.max total - 5, 0
|
|
2935
|
+
|
|
2936
|
+
checkout = (items, strategy = pricing.standard) ->
|
|
2937
|
+
total = items.reduce ((sum, item) -> sum + item.price), 0
|
|
2938
|
+
strategy(total).toFixed 2
|
|
2939
|
+
|
|
2940
|
+
cart = [{price: 9}, {price: 8}]
|
|
2941
|
+
present checkout cart
|
|
2942
|
+
present checkout cart, pricing.member
|
|
2943
|
+
forEvery tier in ['happyHour', 'vip']
|
|
2944
|
+
present tier, checkout cart, pricing[tier] ? pricing.standard
|
|
2945
|
+
```
|
|
2946
|
+
```text
|
|
2947
|
+
17.00
|
|
2948
|
+
15.30
|
|
2949
|
+
happyHour 12.00
|
|
2950
|
+
vip 17.00
|
|
2951
|
+
```
|
|
2952
|
+
|
|
2953
|
+
### 90. Decorator
|
|
2954
|
+
|
|
2955
|
+
**Explanation.** A decorator wraps a function in another with the same signature, adding behaviour
|
|
2956
|
+
before or after: logging, timing, retries, caching. Rest parameters and spread pass the arguments
|
|
2957
|
+
through untouched (`(args...) -> fn args...`), and decorators stack because each returns an
|
|
2958
|
+
ordinary function. Inside a blueprint, wrap methods with `Blueprint::name = decorate Blueprint::name`.
|
|
2959
|
+
|
|
2960
|
+
**Demonstration.**
|
|
2961
|
+
```mamba
|
|
2962
|
+
logged = (name, fn) -> (args...) ->
|
|
2963
|
+
result = fn args...
|
|
2964
|
+
present "#{name}(#{args.join ', '}) -> #{result}"
|
|
2965
|
+
result
|
|
2966
|
+
|
|
2967
|
+
retried = (times, fn) -> (args...) ->
|
|
2968
|
+
forEvery round in [1..times]
|
|
2969
|
+
attempt
|
|
2970
|
+
return fn args...
|
|
2971
|
+
onFail problem
|
|
2972
|
+
present "attempt #{round} failed: #{problem.message}"
|
|
2973
|
+
panic "gave up after #{times} attempts"
|
|
2974
|
+
|
|
2975
|
+
flaky = 0
|
|
2976
|
+
fetchPrice = (dish) ->
|
|
2977
|
+
flaky += 1
|
|
2978
|
+
panic 'kitchen busy' if flaky < 3
|
|
2979
|
+
dish.length * 2
|
|
2980
|
+
safeFetch = logged 'fetchPrice', retried(3, fetchPrice)
|
|
2981
|
+
safeFetch 'ramen'
|
|
2982
|
+
```
|
|
2983
|
+
```text
|
|
2984
|
+
attempt 1 failed: kitchen busy
|
|
2985
|
+
attempt 2 failed: kitchen busy
|
|
2986
|
+
fetchPrice(ramen) -> 10
|
|
2987
|
+
```
|
|
2988
|
+
|
|
2989
|
+
### 91. Command (with undo)
|
|
2990
|
+
|
|
2991
|
+
**Explanation.** Each command is an object with `run` and `undo`, built by a small factory that
|
|
2992
|
+
closes over its arguments. An invoker keeps a history stack, so undo is `history.pop()?.undo()`:
|
|
2993
|
+
the soak makes undo on an empty history a no-op. Commands can be queued, logged and replayed,
|
|
2994
|
+
which is how editors and game turn systems work.
|
|
2995
|
+
|
|
2996
|
+
**Demonstration.**
|
|
2997
|
+
```mamba
|
|
2998
|
+
order = []
|
|
2999
|
+
addDish = (dish) ->
|
|
3000
|
+
run: -> order.push dish
|
|
3001
|
+
undo: -> order.splice order.lastIndexOf(dish), 1
|
|
3002
|
+
|
|
3003
|
+
blueprint Waiter
|
|
3004
|
+
constructor: -> @history = []
|
|
3005
|
+
execute: (command) ->
|
|
3006
|
+
command.run()
|
|
3007
|
+
@history.push command
|
|
3008
|
+
undo: -> @history.pop()?.undo()
|
|
3009
|
+
|
|
3010
|
+
waiter = make Waiter
|
|
3011
|
+
waiter.execute addDish dish forEvery dish in ['ramen', 'gyoza', 'mochi']
|
|
3012
|
+
present order
|
|
3013
|
+
waiter.undo()
|
|
3014
|
+
present order
|
|
3015
|
+
waiter.undo() forEvery i in [1..5]
|
|
3016
|
+
present order
|
|
3017
|
+
```
|
|
3018
|
+
```text
|
|
3019
|
+
[ 'ramen', 'gyoza', 'mochi' ]
|
|
3020
|
+
[ 'ramen', 'gyoza' ]
|
|
3021
|
+
[]
|
|
3022
|
+
```
|
|
3023
|
+
|
|
3024
|
+
### 92. Builder with Decision
|
|
3025
|
+
|
|
3026
|
+
**Explanation.** A builder assembles a complex object step by step. Decision, shipped with the
|
|
3027
|
+
compiler (`grab Decision from 'mambascript/decision'`), is a builder for UI trees: `Decision(Pragma)` returns
|
|
3028
|
+
tag functions (`div`, `li`, `$`) that call `Pragma.createElement`, so it drives React, Preact or any
|
|
3029
|
+
object with `createElement` and `isValidElement`. A `'#id.class'` selector sets the id and class
|
|
3030
|
+
name, and a function argument's body collects the children. Here the pragma is a few lines that
|
|
3031
|
+
print escaped text and attribute values for these fixed tags and attribute names. It is a teaching
|
|
3032
|
+
renderer, not a replacement for React or MambaView: it does not implement event handlers, void
|
|
3033
|
+
elements, arbitrary attribute validation or a complete HTML serialization contract.
|
|
3034
|
+
Fancy tier (Decision); the plain form is calling `Html.createElement 'div', {id: 'lunch'}, …` directly.
|
|
3035
|
+
|
|
3036
|
+
**Demonstration.**
|
|
3037
|
+
```mamba
|
|
3038
|
+
grab Decision from 'mambascript/decision'
|
|
3039
|
+
escapeHtml = (value) -> String(value).replace /[&<>"]/g, (char) ->
|
|
3040
|
+
{'&': '&', '<': '<', '>': '>', '"': '"'}[char]
|
|
3041
|
+
attrsOf = (props) :: String ->
|
|
3042
|
+
attrs = []
|
|
3043
|
+
forEvery own key, value of props
|
|
3044
|
+
name = if key is 'className' then 'class' otherwise key
|
|
3045
|
+
attrs.push "#{name}=\"#{escapeHtml value}\""
|
|
3046
|
+
attrs.join ' '
|
|
3047
|
+
Html =
|
|
3048
|
+
createElement: (type, props, children...) -> {type, props: props orElse {}, children}
|
|
3049
|
+
isValidElement: (node) -> node?.type?
|
|
3050
|
+
render = (node) ->
|
|
3051
|
+
return escapeHtml(node) unless Html.isValidElement node
|
|
3052
|
+
open = _.compact([node.type, attrsOf node.props]).join ' '
|
|
3053
|
+
children = _.map node.children, render
|
|
3054
|
+
"<#{open}>#{children.join ''}</#{node.type}>"
|
|
3055
|
+
|
|
3056
|
+
{div, h2, ul, li} = Decision Html
|
|
3057
|
+
menu = div '#lunch.card', ->
|
|
3058
|
+
h2 'Lunch'
|
|
3059
|
+
ul ->
|
|
3060
|
+
li {data: {price: 9}}, 'ramen'
|
|
3061
|
+
li 'udon'
|
|
3062
|
+
present render menu
|
|
3063
|
+
```
|
|
3064
|
+
```text
|
|
3065
|
+
<div id="lunch" class="card"><h2>Lunch</h2><ul><li data-price="9">ramen</li><li>udon</li></ul></div>
|
|
3066
|
+
```
|
|
3067
|
+
|
|
3068
|
+
### 93. Module: `grab`, `share` and ES modules
|
|
3069
|
+
|
|
3070
|
+
**Explanation.** `grab x from 'm'` and `share {a, b}` are the module syntax. They compile to
|
|
3071
|
+
`require` and `module.exports` by default, and to `import` and `export` with `mamba -c --esm`,
|
|
3072
|
+
`modules: 'esm'` in the API, or `"type": "module"` in `package.json`; in ES-module output a
|
|
3073
|
+
top-level `waitForIt` is a top-level `await`. `grab` and `share` sit at the top level (MS3002),
|
|
3074
|
+
`grab` destructures one level (MS3001), and a file has one default `share` (MS3003).
|
|
3075
|
+
|
|
3076
|
+
**Demonstration.**
|
|
3077
|
+
```mamba
|
|
3078
|
+
grab MambaScript from 'mambascript'
|
|
3079
|
+
grab {join, basename: nameOf} from 'path'
|
|
3080
|
+
|
|
3081
|
+
present join('menus', 'lunch.json'), nameOf '/menus/dinner.json'
|
|
3082
|
+
share {tax: 0.1, menuFile: join 'menus', 'lunch.json'}
|
|
3083
|
+
present module.exports
|
|
3084
|
+
|
|
3085
|
+
present MambaScript.cs2js """
|
|
3086
|
+
grab {readFile} from 'fs/promises'
|
|
3087
|
+
grab * as path from 'path'
|
|
3088
|
+
loadMenu = (file) -> JSON.parse waitForIt readFile path.join('menus', file), 'utf8'
|
|
3089
|
+
share {loadMenu}
|
|
3090
|
+
""", modules: 'esm', bare: yes
|
|
3091
|
+
```
|
|
3092
|
+
```text
|
|
3093
|
+
menus/lunch.json dinner.json
|
|
3094
|
+
{ tax: 0.1, menuFile: 'menus/lunch.json' }
|
|
3095
|
+
// Generated by MambaScript 2.0.0
|
|
3096
|
+
import { readFile } from 'fs/promises';
|
|
3097
|
+
import * as path from 'path';
|
|
3098
|
+
var loadMenu;
|
|
3099
|
+
loadMenu = async function (file) {
|
|
3100
|
+
return JSON.parse(await readFile(path.join('menus', file), 'utf8'));
|
|
3101
|
+
};
|
|
3102
|
+
export { loadMenu };
|
|
3103
|
+
```
|
|
3104
|
+
|
|
3105
|
+
## Algorithms
|
|
3106
|
+
|
|
3107
|
+
### 94. Binary search
|
|
3108
|
+
|
|
3109
|
+
**Explanation.** Binary search halves a sorted range until it finds the target or the range is
|
|
3110
|
+
empty: O(log n). `(lo + hi) >> 1` is the midpoint without floating point, `consider` with no subject
|
|
3111
|
+
reads as the three cases, and a multiple assignment like `[lo, hi] = [0, items.length - 1]` sets up
|
|
3112
|
+
the window. The same loop, returning `lo` instead of `-1`, gives the insertion point.
|
|
3113
|
+
|
|
3114
|
+
**Demonstration.**
|
|
3115
|
+
```mamba
|
|
3116
|
+
search = (items, target) ->
|
|
3117
|
+
[lo, hi] = [0, items.length - 1]
|
|
3118
|
+
while lo <= hi
|
|
3119
|
+
mid = (lo + hi) >> 1
|
|
3120
|
+
consider
|
|
3121
|
+
when items[mid] is target then return mid
|
|
3122
|
+
when items[mid] < target then lo = mid + 1
|
|
3123
|
+
otherwise hi = mid - 1
|
|
3124
|
+
-1
|
|
3125
|
+
|
|
3126
|
+
insertionPoint = (items, target) ->
|
|
3127
|
+
[lo, hi] = [0, items.length]
|
|
3128
|
+
while lo < hi
|
|
3129
|
+
mid = (lo + hi) >> 1
|
|
3130
|
+
if items[mid] < target then lo = mid + 1 otherwise hi = mid
|
|
3131
|
+
lo
|
|
3132
|
+
|
|
3133
|
+
levels = [1, 4, 9, 16, 25, 36]
|
|
3134
|
+
present search(levels, 16), search(levels, 5), search([], 1)
|
|
3135
|
+
present insertionPoint levels, 10
|
|
3136
|
+
```
|
|
3137
|
+
```text
|
|
3138
|
+
3 -1 -1
|
|
3139
|
+
3
|
|
3140
|
+
```
|
|
3141
|
+
|
|
3142
|
+
### 95. Sorting: merge sort and comparators
|
|
3143
|
+
|
|
3144
|
+
**Explanation.** Merge sort splits the list with slices (`items[...mid]`, `items[mid..]`), sorts
|
|
3145
|
+
each half recursively and merges them: O(n log n) and stable. The built-in `sort` takes a
|
|
3146
|
+
comparator, and a quirk from JavaScript: without one it compares as strings, so
|
|
3147
|
+
`[10, 9, 1].sort()` puts 10 before 9. Chain comparators with `or` to sort by several keys, since `0` (a tie) is falsy.
|
|
3148
|
+
|
|
3149
|
+
**Demonstration.**
|
|
3150
|
+
```mamba
|
|
3151
|
+
mergeSort = (items) ->
|
|
3152
|
+
return items if items.length <= 1
|
|
3153
|
+
mid = items.length >> 1
|
|
3154
|
+
[left, right] = [mergeSort(items[...mid]), mergeSort(items[mid..])]
|
|
3155
|
+
merged = []
|
|
3156
|
+
while left.length and right.length
|
|
3157
|
+
merged.push (if left[0] <= right[0] then left.shift() otherwise right.shift())
|
|
3158
|
+
[merged..., left..., right...]
|
|
3159
|
+
|
|
3160
|
+
present mergeSort([38, 27, 43, 3, 9, 82, 10]).join ' '
|
|
3161
|
+
present [10, 9, 1].sort(), [10, 9, 1].sort (a, b) -> a - b
|
|
3162
|
+
|
|
3163
|
+
players = [{name: 'Cy', level: 5}, {name: 'Ana', level: 9}, {name: 'Ben', level: 5}]
|
|
3164
|
+
byLevelThenName = (a, b) -> (b.level - a.level) or a.name.localeCompare b.name
|
|
3165
|
+
present (p.name forEvery p in players.sort byLevelThenName)
|
|
3166
|
+
```
|
|
3167
|
+
```text
|
|
3168
|
+
3 9 10 27 38 43 82
|
|
3169
|
+
[ 1, 10, 9 ] [ 1, 9, 10 ]
|
|
3170
|
+
[ 'Ana', 'Ben', 'Cy' ]
|
|
3171
|
+
```
|
|
3172
|
+
|
|
3173
|
+
### 96. Two pointers
|
|
3174
|
+
|
|
3175
|
+
**Explanation.** Two indices walking toward each other over a sorted list find a pair with a given
|
|
3176
|
+
sum in O(n) and O(1) space: move the left one up when the sum is too small and the right one down
|
|
3177
|
+
when it is too large. Destructuring assignment keeps both pointers on one line, and the same shape
|
|
3178
|
+
checks palindromes and reverses in place.
|
|
3179
|
+
|
|
3180
|
+
**Demonstration.**
|
|
3181
|
+
```mamba
|
|
3182
|
+
pairWithSum = (prices, budget) ->
|
|
3183
|
+
[i, j] = [0, prices.length - 1]
|
|
3184
|
+
while i < j
|
|
3185
|
+
sum = prices[i] + prices[j]
|
|
3186
|
+
return [prices[i], prices[j]] if sum is budget
|
|
3187
|
+
if sum < budget then i += 1 otherwise j -= 1
|
|
3188
|
+
nothing
|
|
3189
|
+
|
|
3190
|
+
isPalindrome = (text) ->
|
|
3191
|
+
letters = text.toLowerCase().replace /[^a-z]/g, ''
|
|
3192
|
+
[i, j] = [0, letters.length - 1]
|
|
3193
|
+
while i < j
|
|
3194
|
+
return no if letters[i] isnt letters[j]
|
|
3195
|
+
[i, j] = [i + 1, j - 1]
|
|
3196
|
+
yes
|
|
3197
|
+
|
|
3198
|
+
present pairWithSum [2, 3, 5, 8, 13], 16
|
|
3199
|
+
present pairWithSum [2, 3], 100
|
|
3200
|
+
present isPalindrome('Taco cat'), isPalindrome('ramen')
|
|
3201
|
+
```
|
|
3202
|
+
```text
|
|
3203
|
+
[ 3, 13 ]
|
|
3204
|
+
null
|
|
3205
|
+
true false
|
|
3206
|
+
```
|
|
3207
|
+
|
|
3208
|
+
### 97. Sliding window
|
|
3209
|
+
|
|
3210
|
+
**Explanation.** A window over a list or string grows on the right and shrinks on the left, each
|
|
3211
|
+
index moving at most n times, so problems like "longest stretch without repeats" run in O(n).
|
|
3212
|
+
A `Map` remembers where each item was last seen, and `Math.max` jumps the left edge past a
|
|
3213
|
+
repeat. Fixed-size windows update a running sum by adding the new item and subtracting the old.
|
|
3214
|
+
|
|
3215
|
+
**Demonstration.**
|
|
3216
|
+
```mamba
|
|
3217
|
+
longestUnique = (text) ->
|
|
3218
|
+
lastSeen = make Map
|
|
3219
|
+
[left, best] = [0, '']
|
|
3220
|
+
forEvery char, right in text
|
|
3221
|
+
left = Math.max left, lastSeen.get(char) + 1 if lastSeen.has char
|
|
3222
|
+
lastSeen.set char, right
|
|
3223
|
+
best = text[left..right] if right - left + 1 > best.length
|
|
3224
|
+
best
|
|
3225
|
+
|
|
3226
|
+
bestStreak = (scores, size) ->
|
|
3227
|
+
sum = _.reduce scores[...size], ((a, b) -> a + b), 0
|
|
3228
|
+
best = sum
|
|
3229
|
+
forEvery i in [size...scores.length] by 1
|
|
3230
|
+
sum += scores[i] - scores[i - size]
|
|
3231
|
+
best = Math.max best, sum
|
|
3232
|
+
best
|
|
3233
|
+
|
|
3234
|
+
present longestUnique 'abcabcbb'
|
|
3235
|
+
present longestUnique 'ramenmenu'
|
|
3236
|
+
present bestStreak [3, 1, 4, 1, 5, 9, 2, 6], 3
|
|
3237
|
+
```
|
|
3238
|
+
```text
|
|
3239
|
+
abc
|
|
3240
|
+
ramen
|
|
3241
|
+
17
|
|
3242
|
+
```
|
|
3243
|
+
|
|
3244
|
+
### 98. Recursion and backtracking
|
|
3245
|
+
|
|
3246
|
+
**Explanation.** Backtracking builds a candidate one choice at a time, recurses, then undoes the
|
|
3247
|
+
choice: `path.push`, recurse, `path.pop()`. A nested helper closes over the result list and the
|
|
3248
|
+
input, so only the changing state travels as arguments. Spreading `[path...]` snapshots the path
|
|
3249
|
+
when it is complete; pushing `path` itself would store the same list over and over.
|
|
3250
|
+
|
|
3251
|
+
**Demonstration.**
|
|
3252
|
+
```mamba
|
|
3253
|
+
combos = (menu, budget) ->
|
|
3254
|
+
results = []
|
|
3255
|
+
pick = (start, path, left) ->
|
|
3256
|
+
results.push [path...] if left is 0
|
|
3257
|
+
forEvery i in [start...menu.length] by 1 when menu[i].price <= left
|
|
3258
|
+
path.push menu[i].name
|
|
3259
|
+
pick i + 1, path, left - menu[i].price
|
|
3260
|
+
path.pop()
|
|
3261
|
+
return
|
|
3262
|
+
pick 0, [], budget
|
|
3263
|
+
results
|
|
3264
|
+
|
|
3265
|
+
menu = [
|
|
3266
|
+
{name: 'ramen', price: 9}
|
|
3267
|
+
{name: 'gyoza', price: 4}
|
|
3268
|
+
{name: 'tea', price: 2}
|
|
3269
|
+
{name: 'mochi', price: 3}
|
|
3270
|
+
]
|
|
3271
|
+
present _.map combos(menu, 9), (combo) -> combo.join ' + '
|
|
3272
|
+
```
|
|
3273
|
+
```text
|
|
3274
|
+
[ 'ramen', 'gyoza + tea + mochi' ]
|
|
3275
|
+
```
|
|
3276
|
+
|
|
3277
|
+
### 99. Dynamic programming
|
|
3278
|
+
|
|
3279
|
+
**Explanation.** Dynamic programming stores the answers to smaller problems so each is solved once.
|
|
3280
|
+
Bottom-up, a table filled in order replaces recursion: for the fewest coins, `ways[amount]` is one
|
|
3281
|
+
more than the best `ways[amount - coin]`. `Array(n).fill(Infinity)` makes the table and `by 1`
|
|
3282
|
+
keeps the range from counting backwards when a bound is small. The same table holds the number of
|
|
3283
|
+
ways to reach each amount.
|
|
3284
|
+
|
|
3285
|
+
**Demonstration.**
|
|
3286
|
+
```mamba
|
|
3287
|
+
fewestCoins = (coins, amount) ->
|
|
3288
|
+
best = Array(amount + 1).fill Infinity
|
|
3289
|
+
best[0] = 0
|
|
3290
|
+
forEvery total in [1..amount] by 1
|
|
3291
|
+
forEvery coin in coins when coin <= total
|
|
3292
|
+
best[total] = Math.min best[total], best[total - coin] + 1
|
|
3293
|
+
if best[amount] is Infinity then -1 otherwise best[amount]
|
|
3294
|
+
|
|
3295
|
+
countWays = (coins, amount) ->
|
|
3296
|
+
ways = Array(amount + 1).fill 0
|
|
3297
|
+
ways[0] = 1
|
|
3298
|
+
forEvery coin in coins
|
|
3299
|
+
ways[total] += ways[total - coin] forEvery total in [coin..amount] by 1
|
|
3300
|
+
ways[amount]
|
|
3301
|
+
|
|
3302
|
+
present fewestCoins([1, 5, 10, 25], 63), fewestCoins([5], 3)
|
|
3303
|
+
present countWays [1, 2, 5], 5
|
|
3304
|
+
present countWays [2], 0
|
|
3305
|
+
```
|
|
3306
|
+
```text
|
|
3307
|
+
6 -1
|
|
3308
|
+
4
|
|
3309
|
+
1
|
|
3310
|
+
```
|
|
3311
|
+
|
|
3312
|
+
### 100. Union-find
|
|
3313
|
+
|
|
3314
|
+
**Explanation.** Union-find (a disjoint-set forest) tracks which items are connected: `find` walks
|
|
3315
|
+
to a root and compresses the path on the way back, `union` hangs the smaller tree under the larger,
|
|
3316
|
+
and both run in nearly constant time. It answers "are these two in the same group" and counts
|
|
3317
|
+
groups (here, guild alliances) faster than a graph search per query. Comprehensions build the
|
|
3318
|
+
`parent` and `size` tables in one line each.
|
|
3319
|
+
|
|
3320
|
+
**Demonstration.**
|
|
3321
|
+
```mamba
|
|
3322
|
+
blueprint UnionFind
|
|
3323
|
+
constructor: (n) ->
|
|
3324
|
+
@parent = (i forEvery i in [0...n] by 1)
|
|
3325
|
+
@size = (1 forEvery i in [0...n] by 1)
|
|
3326
|
+
@groups = n
|
|
3327
|
+
find: (x) ->
|
|
3328
|
+
@parent[x] = @find @parent[x] unless @parent[x] is x
|
|
3329
|
+
@parent[x]
|
|
3330
|
+
union: (a, b) ->
|
|
3331
|
+
[ra, rb] = [@find(a), @find(b)]
|
|
3332
|
+
return no if ra is rb
|
|
3333
|
+
[ra, rb] = [rb, ra] if @size[ra] < @size[rb]
|
|
3334
|
+
@parent[rb] = ra
|
|
3335
|
+
@size[ra] += @size[rb]
|
|
3336
|
+
@groups -= 1
|
|
3337
|
+
yes
|
|
3338
|
+
|
|
3339
|
+
guilds = ['Owls', 'Wolves', 'Hawks', 'Bears', 'Foxes']
|
|
3340
|
+
alliances = make UnionFind guilds.length
|
|
3341
|
+
alliances.union a, b forEvery [a, b] in [[0, 1], [2, 3], [1, 0], [3, 4]]
|
|
3342
|
+
present alliances.groups
|
|
3343
|
+
present alliances.find(4) is alliances.find(2), alliances.find(0) is alliances.find(2)
|
|
3344
|
+
```
|
|
3345
|
+
```text
|
|
3346
|
+
2
|
|
3347
|
+
true false
|
|
3348
|
+
```
|