ブラックフライデー、2日延長ブラックフライデー延長中ブラックフライデー:Proの全部が$19(通常$49)、1年でいちばん安い価格です。。 · $19 通常$49終了まで延長 · 終了まで終了まで Proにする · $19Proにする
学ぶ 練習 デイリーゴルフ リファレンス
11ステップ中1
縦の移動·レッスン 2/6·8分·練習問題 0/8Pro

絶対ジャンプ

行番号はページ番号。ggとGで表紙と裏表紙、42Gか:42↵で言われた行へ。最後はスタックトレースをたどって、指された所を直します。

手に入るキーggG42G:42
とても長いコードの本が横になっていて、表紙にgg、裏表紙にG。忍者は42Gの札の付いた42ページへしおりを引き、机の付せんには:42とある。
場面

木曜日、午後3時40分。チャットにスタックトレースが届きます。配達料の計算中に注文が落ちました。

  • TypeError: Cannot read properties of undefined (reading 'lat')
  • at distanceKm (legacy.js:84)
  • at placeOrder (legacy.js:194)
  • at reorder (legacy.js:290)

行番号が3つ、どれも画面からはるか先。定規で測れるのは、今のページだけです。

11ステップ中2
思い出す練習

これまでのチャプターで準備運動

前のチャプターから2つ。新しい話の前に、思い出して答えましょう。2回間違えると答えが出ます。

どのキー?
行きたい行は上で、欄には7とある。そこへ。
2キー押す…
2問中1問目
行きたい行は上で、欄には7とある。そこへ。
11ステップ中3
パート1:表紙

ggとG:表紙と裏表紙

余白にページ番号。トレースは84、194、290と言っています。
表紙
トレース

本は何百年も前にこれを解決しました。ページ番号を印刷すればいい。ファイルにも余白に番号があり、Vimはどのページでもまっすぐ開けます。

まずは表紙から。ggはファイルの最初の行、表紙へ。Gは最後の行、裏表紙へ。どこからでも1つか2つのキーで、知らないファイルで自分の居場所をつかむいちばんの近道です。

11ステップ中4
パート2:ページ

ページを開く:84G

やってみよう

引き算をする

トレースの1番目は、ページの外の行です。自分の行からの距離を計算して、jでジャンプしましょう。

トレースは84行目。今は54行目にいます。legacy.js
53// legacy.js — Byte Burrito, 2019–present. Please don't add anything here.
52// (Everyone has added something here.)
51
50const TAX_RATE = 0.0875;
49const MAX_DISTANCE_KM = 8;
48const OPEN_HOUR = 11;
47const CLOSE_HOUR = 23;
46const RUSH_START = 12;
45const RUSH_END = 14;
44
43function isOpen(now) {
42 const hour = now.getHours();
41 return hour >= OPEN_HOUR && hour < CLOSE_HOUR;
40}
39
38function isLunchRush(now) {
37 const hour = now.getHours();
36 return hour >= RUSH_START && hour < RUSH_END;
35}
34
33function formatPrice(cents) {
32 const dollars = Math.floor(cents / 100);
31 const rest = String(cents % 100).padStart(2, "0");
30 return "$" + dollars + "." + rest;
29}
28
27function subtotal(items) {
26 let sum = 0;
25 for (const item of items) {
24 sum += item.price * item.qty;
23 }
22 return sum;
21}
20
19function taxFor(amount) {
18 return Math.round(amount * TAX_RATE);
17}
16
15function totalFor(order) {
14 const base = subtotal(order.items);
13 const tax = taxFor(base);
12 const tip = order.tip || 0;
11 return base + tax + tip;
10}
9
8// DEAD CODE: the fax ordering line was switched off in 2020
7function faxOrder(order) {
6 const sheet = renderFaxSheet(order);
5 faxMachine.send(sheet, "+1-555-0100");
4 log("fax sent", order.id);
3 return true;
2}
1
54function validateOrder(order) {
1 if (!order.items || order.items.length === 0) return "empty";
2 if (order.items.some((i) => i.qty <= 0)) return "bad quantity";
3 if (!order.address) return "no address";
4 if (!isOpen(new Date())) return "closed";
5 return null;
6}
7
8function applyCoupon(order, code) {
9 const coupon = COUPONS[code];
10 if (!coupon) return order;
11 if (coupon.expires < Date.now()) return order;
12 const off = Math.round(subtotal(order.items) * coupon.percent);
13 return { ...order, discount: off };
14}
15
16function studentDiscount(order, user) {
17 if (!user.isStudent) return 0;
18 return Math.round(subtotal(order.items) * 0.1);
19}
20
21// DEAD CODE: loyalty points were replaced by the app in 2021
22function addLoyaltyPoints(user, order) {
23 const points = Math.floor(totalFor(order) / 100);
24 user.points = (user.points || 0) + points;
25 saveUser(user);
26 return points;
27}
28
29function distanceKm(a, b) {
30 const dLat = (b.lat - a.lat) * 111;
31 const dLng = (b.lng - a.lng) * 111 * Math.cos((a.lat * Math.PI) / 180);
32 return Math.sqrt(dLat * dLat + dLng * dLng);
33}
34
35function nearestRider(riders, address) {
36 let best = null;
37 for (const rider of riders) {
38 if (!rider.online) continue;
39 const d = distanceKm(rider.position, address.position);
40 if (d > MAX_DISTANCE_KM) continue;
41 if (!best || d < best.distance) best = { rider, distance: d };
42 }
43 return best;
44}
45
46function assignRider(order, riders) {
47 const match = nearestRider(riders, order.address);
48 if (!match) return refund(order, "No rider nearby, sorry!");
49 order.riderId = match.rider.id;
50 order.eta = Math.ceil(match.distance * 4) + 10;
51 notify(match.rider.phone, "New order: " + order.id);
52 return order;
53}
54
55function etaMinutes(order, now) {
56 const rush = isLunchRush(now) ? 10 : 0;
57 return order.eta + rush;
58}
59
60// DEAD CODE: the pager integration, before the riders had phones
61function pageRider(rider, order) {
62 const message = "ORDER " + order.id + " " + order.address.street;
63 pager.send(rider.pagerId, message.slice(0, 80));
64 return true;
65}
66
67function refund(order, reason) {
68 order.status = "refunded";
69 order.refundReason = reason;
70 payments.refund(order.paymentId, totalFor(order));
71 notify(order.customerPhone, "Refunded: " + reason);
72 return order;
73}
74
75function markDelivered(order, now) {
76 order.status = "delivered";
77 order.deliveredAt = now.toISOString();
78 const late = now - new Date(order.placedAt) > order.eta * 60000;
79 if (late) order.lateBy = Math.round((now - new Date(order.placedAt)) / 60000 - order.eta);
80 return order;
81}
82
83function kitchenTicket(order) {
84 const lines = order.items.map((i) => i.qty + " x " + i.name);
85 lines.unshift("ORDER " + order.id);
86 if (order.notes) lines.push("NOTE: " + order.notes);
87 return lines.join("\n");
88}
89
90function printTicket(order) {
91 const ticket = kitchenTicket(order);
92 printer.print(ticket);
93 log("printed", order.id);
94}
95
96// DEAD CODE: the old receipt printer, replaced by email receipts
97function printReceipt(order) {
98 const lines = order.items.map((i) => i.name + " " + formatPrice(i.price * i.qty));
99 lines.push("TOTAL " + formatPrice(totalFor(order)));
100 receiptPrinter.print(lines.join("\n"));
101}
102
103function emailReceipt(order, user) {
104 const body = renderReceipt(order);
105 mailer.send(user.email, "Your Byte Burrito receipt", body);
106}
107
108function menuItem(id) {
109 const item = MENU.find((m) => m.id === id);
110 if (!item) throw new Error("not on the menu: " + id);
111 return item;
112}
113
114function isSpicy(id) {
115 return menuItem(id).spicy === true;
116}
117
118function happyHourPrice(item, now) {
119 const hour = now.getHours();
120 if (hour >= 17 && hour < 19) return Math.round(item.price * 0.8);
121 return item.price;
122}
123
124function priceList(now) {
125 return MENU.map((item) => ({
126 id: item.id,
127 name: item.name,
128 price: formatPrice(happyHourPrice(item, now)),
129 }));
130}
131
132// DEAD CODE: the 2019 "burrito of the month", never shipped
133function burritoOfTheMonth(month) {
134 const picks = ["al-pastor", "veggie", "carnitas", "birria"];
135 return menuItem(picks[month % picks.length]);
136}
137
138function placeOrder(cart, user, now) {
139 const order = { id: newId(), items: cart.items, address: user.address, placedAt: now.toISOString() };
140 const fee = deliveryFee(order, distanceKm(KITCHEN, order.address));
141 const problem = validateOrder(order);
142 if (problem) throw new Error(problem);
143 order.discount = studentDiscount(order, user);
144 order.total = totalFor(order) - order.discount + fee;
145 return order;
146}
147
148function deliveryFee(order, km) {
149 const base = km <= 2 ? 0 : 1.5;
150 const perKm = km > 2 ? (km - 2) * 0.4 : 0;
151 const rush = isLunchRush(new Date()) ? 1 : 0;
152 return Math.round((base + perKm + rush) * 100) / 100;
153}
154
155function newId() {
156 return "BB-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 6);
157}
158
159function log(event, ...details) {
160 console.log("[" + new Date().toISOString() + "] " + event, ...details);
161}
162
163function notify(phone, text) {
164 if (!phone) return;
165 sms.send(phone, text.slice(0, 160));
166}
167
168function saveUser(user) {
169 db.users.put(user.id, user);
170}
171
172function loadUser(id) {
173 return db.users.get(id);
174}
175
176function saveOrder(order) {
177 db.orders.put(order.id, order);
178 log("saved", order.id);
179}
180
181function loadOrder(id) {
182 return db.orders.get(id);
183}
184
185function ordersToday(now) {
186 const day = now.toISOString().slice(0, 10);
187 return db.orders.all().filter((o) => o.placedAt.startsWith(day));
188}
189
190function revenueToday(now) {
191 return ordersToday(now).reduce((sum, o) => sum + o.total, 0);
192}
193
194function busiestHour(now) {
195 const counts = new Array(24).fill(0);
196 for (const o of ordersToday(now)) counts[new Date(o.placedAt).getHours()]++;
197 return counts.indexOf(Math.max(...counts));
198}
199
200// DEAD CODE: the CSV export the accountant asked for, then never used
201function exportCsv(orders) {
202 const rows = orders.map((o) => [o.id, o.total, o.status].join(","));
203 rows.unshift("id,total,status");
204 return rows.join("\n");
205}
206
207function ridersOnline(riders) {
208 return riders.filter((r) => r.online).length;
209}
210
211function riderReport(riders, now) {
212 const online = ridersOnline(riders);
213 const rush = isLunchRush(now);
214 return { online, rush, short: rush && online < 6 };
215}
216
217function weatherDelay(weather) {
218 if (weather === "rain") return 8;
219 if (weather === "snow") return 20;
220 return 0;
221}
222
223function adjustEta(order, weather) {
224 order.eta = order.eta + weatherDelay(weather);
225 return order;
226}
227
228function cancelOrder(order, reason) {
229 if (order.status === "delivered") return order;
230 order.status = "cancelled";
231 return refund(order, reason);
232}
233
234function reorder(previous, user, now) {
235 const cart = { items: previous.items.map((i) => ({ ...i })) };
236 return placeOrder(cart, user, now);
237}
238
239function favourite(user) {
240 const counts = {};
241 for (const o of db.orders.byUser(user.id)) {
242 for (const i of o.items) counts[i.id] = (counts[i.id] || 0) + i.qty;
243 }
244 return Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
245}
246
247module.exports = {
248 isOpen,
249 placeOrder,
250 assignRider,
251 markDelivered,
252 printTicket,
253 emailReceipt,
254 priceList,
255 revenueToday,
256 riderReport,
257 cancelOrder,
258 reorder,
259};
NORMALエディタを読み込み中…0.0s行54、列:1

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。

11ステップ中5

動く前に、引き算をしました。Gの前に行番号を置けば要りません。84Gは、どこにいてもまっすぐ84行目へ。

:194と↵でも、コマンドとして同じことができます。指の好きなほうを使いましょう。

1// legacy.js — Byte Burrito, 2019–present. Please don't add anything here.
1// (Everyone has added something here.)
2
3const TAX_RATE = 0.0875;
4const MAX_DISTANCE_KM = 8;
5const OPEN_HOUR = 11;
6const CLOSE_HOUR = 23;
7const RUSH_START = 12;
8const RUSH_END = 14;
9
10function isOpen(now) {
11 const hour = now.getHours();
12 return hour >= OPEN_HOUR && hour < CLOSE_HOUR;
13}
14
15function isLunchRush(now) {
16 const hour = now.getHours();
17 return hour >= RUSH_START && hour < RUSH_END;
18}
19
20function formatPrice(cents) {
21 const dollars = Math.floor(cents / 100);
22 const rest = String(cents % 100).padStart(2, "0");
23 return "$" + dollars + "." + rest;
24}
25
26function subtotal(items) {
27 let sum = 0;
28 for (const item of items) {
29 sum += item.price * item.qty;
30 }
31 return sum;
32}
33
34function taxFor(amount) {
35 return Math.round(amount * TAX_RATE);
36}
37
38function totalFor(order) {
39 const base = subtotal(order.items);
40 const tax = taxFor(base);
41 const tip = order.tip || 0;
42 return base + tax + tip;
43}
44
45// DEAD CODE: the fax ordering line was switched off in 2020
46function faxOrder(order) {
47 const sheet = renderFaxSheet(order);
48 faxMachine.send(sheet, "+1-555-0100");
49 log("fax sent", order.id);
50 return true;
51}
52
53function validateOrder(order) {
54 if (!order.items || order.items.length === 0) return "empty";
55 if (order.items.some((i) => i.qty <= 0)) return "bad quantity";
56 if (!order.address) return "no address";
57 if (!isOpen(new Date())) return "closed";
58 return null;
59}
60
61function applyCoupon(order, code) {
62 const coupon = COUPONS[code];
63 if (!coupon) return order;
64 if (coupon.expires < Date.now()) return order;
65 const off = Math.round(subtotal(order.items) * coupon.percent);
66 return { ...order, discount: off };
67}
68
69function studentDiscount(order, user) {
70 if (!user.isStudent) return 0;
71 return Math.round(subtotal(order.items) * 0.1);
72}
73
74// DEAD CODE: loyalty points were replaced by the app in 2021
75function addLoyaltyPoints(user, order) {
76 const points = Math.floor(totalFor(order) / 100);
77 user.points = (user.points || 0) + points;
78 saveUser(user);
79 return points;
80}
81
82function distanceKm(a, b) {
83 const dLat = (b.lat - a.lat) * 111;
84 const dLng = (b.lng - a.lng) * 111 * Math.cos((a.lat * Math.PI) / 180);
85 return Math.sqrt(dLat * dLat + dLng * dLng);
86}
87
88function nearestRider(riders, address) {
89 let best = null;
90 for (const rider of riders) {
91 if (!rider.online) continue;
92 const d = distanceKm(rider.position, address.position);
93 if (d > MAX_DISTANCE_KM) continue;
94 if (!best || d < best.distance) best = { rider, distance: d };
95 }
96 return best;
97}
98
99function assignRider(order, riders) {
100 const match = nearestRider(riders, order.address);
101 if (!match) return refund(order, "No rider nearby, sorry!");
102 order.riderId = match.rider.id;
103 order.eta = Math.ceil(match.distance * 4) + 10;
104 notify(match.rider.phone, "New order: " + order.id);
105 return order;
106}
107
108function etaMinutes(order, now) {
109 const rush = isLunchRush(now) ? 10 : 0;
110 return order.eta + rush;
111}
112
113// DEAD CODE: the pager integration, before the riders had phones
114function pageRider(rider, order) {
115 const message = "ORDER " + order.id + " " + order.address.street;
116 pager.send(rider.pagerId, message.slice(0, 80));
117 return true;
118}
119
120function refund(order, reason) {
121 order.status = "refunded";
122 order.refundReason = reason;
123 payments.refund(order.paymentId, totalFor(order));
124 notify(order.customerPhone, "Refunded: " + reason);
125 return order;
126}
127
128function markDelivered(order, now) {
129 order.status = "delivered";
130 order.deliveredAt = now.toISOString();
131 const late = now - new Date(order.placedAt) > order.eta * 60000;
132 if (late) order.lateBy = Math.round((now - new Date(order.placedAt)) / 60000 - order.eta);
133 return order;
134}
135
136function kitchenTicket(order) {
137 const lines = order.items.map((i) => i.qty + " x " + i.name);
138 lines.unshift("ORDER " + order.id);
139 if (order.notes) lines.push("NOTE: " + order.notes);
140 return lines.join("\n");
141}
142
143function printTicket(order) {
144 const ticket = kitchenTicket(order);
145 printer.print(ticket);
146 log("printed", order.id);
147}
148
149// DEAD CODE: the old receipt printer, replaced by email receipts
150function printReceipt(order) {
151 const lines = order.items.map((i) => i.name + " " + formatPrice(i.price * i.qty));
152 lines.push("TOTAL " + formatPrice(totalFor(order)));
153 receiptPrinter.print(lines.join("\n"));
154}
155
156function emailReceipt(order, user) {
157 const body = renderReceipt(order);
158 mailer.send(user.email, "Your Byte Burrito receipt", body);
159}
160
161function menuItem(id) {
162 const item = MENU.find((m) => m.id === id);
163 if (!item) throw new Error("not on the menu: " + id);
164 return item;
165}
166
167function isSpicy(id) {
168 return menuItem(id).spicy === true;
169}
170
171function happyHourPrice(item, now) {
172 const hour = now.getHours();
173 if (hour >= 17 && hour < 19) return Math.round(item.price * 0.8);
174 return item.price;
175}
176
177function priceList(now) {
178 return MENU.map((item) => ({
179 id: item.id,
180 name: item.name,
181 price: formatPrice(happyHourPrice(item, now)),
182 }));
183}
184
185// DEAD CODE: the 2019 "burrito of the month", never shipped
186function burritoOfTheMonth(month) {
187 const picks = ["al-pastor", "veggie", "carnitas", "birria"];
188 return menuItem(picks[month % picks.length]);
189}
190
191function placeOrder(cart, user, now) {
192 const order = { id: newId(), items: cart.items, address: user.address, placedAt: now.toISOString() };
193 const fee = deliveryFee(order, distanceKm(KITCHEN, order.address));
194 const problem = validateOrder(order);
195 if (problem) throw new Error(problem);
196 order.discount = studentDiscount(order, user);
197 order.total = totalFor(order) - order.discount + fee;
198 return order;
199}
200
201function deliveryFee(order, km) {
202 const base = km <= 2 ? 0 : 1.5;
203 const perKm = km > 2 ? (km - 2) * 0.4 : 0;
204 const rush = isLunchRush(new Date()) ? 1 : 0;
205 return Math.round((base + perKm + rush) * 100) / 100;
206}
207
208function newId() {
209 return "BB-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 6);
210}
211
212function log(event, ...details) {
213 console.log("[" + new Date().toISOString() + "] " + event, ...details);
214}
215
216function notify(phone, text) {
217 if (!phone) return;
218 sms.send(phone, text.slice(0, 160));
219}
220
221function saveUser(user) {
222 db.users.put(user.id, user);
223}
224
225function loadUser(id) {
226 return db.users.get(id);
227}
228
229function saveOrder(order) {
230 db.orders.put(order.id, order);
231 log("saved", order.id);
232}
233
234function loadOrder(id) {
235 return db.orders.get(id);
236}
237
238function ordersToday(now) {
239 const day = now.toISOString().slice(0, 10);
240 return db.orders.all().filter((o) => o.placedAt.startsWith(day));
241}
242
243function revenueToday(now) {
244 return ordersToday(now).reduce((sum, o) => sum + o.total, 0);
245}
246
247function busiestHour(now) {
248 const counts = new Array(24).fill(0);
249 for (const o of ordersToday(now)) counts[new Date(o.placedAt).getHours()]++;
250 return counts.indexOf(Math.max(...counts));
251}
252
253// DEAD CODE: the CSV export the accountant asked for, then never used
254function exportCsv(orders) {
255 const rows = orders.map((o) => [o.id, o.total, o.status].join(","));
256 rows.unshift("id,total,status");
257 return rows.join("\n");
258}
259
260function ridersOnline(riders) {
261 return riders.filter((r) => r.online).length;
262}
263
264function riderReport(riders, now) {
265 const online = ridersOnline(riders);
266 const rush = isLunchRush(now);
267 return { online, rush, short: rush && online < 6 };
268}
269
270function weatherDelay(weather) {
271 if (weather === "rain") return 8;
272 if (weather === "snow") return 20;
273 return 0;
274}
275
276function adjustEta(order, weather) {
277 order.eta = order.eta + weatherDelay(weather);
278 return order;
279}
280
281function cancelOrder(order, reason) {
282 if (order.status === "delivered") return order;
283 order.status = "cancelled";
284 return refund(order, reason);
285}
286
287function reorder(previous, user, now) {
288 const cart = { items: previous.items.map((i) => ({ ...i })) };
289 return placeOrder(cart, user, now);
290}
291
292function favourite(user) {
293 const counts = {};
294 for (const o of db.orders.byUser(user.id)) {
295 for (const i of o.items) counts[i.id] = (counts[i.id] || 0) + i.qty;
296 }
297 return Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
298}
299
300module.exports = {
301 isOpen,
302 placeOrder,
303 assignRider,
304 markDelivered,
305 printTicket,
306 emailReceipt,
307 priceList,
308 revenueToday,
309 riderReport,
310 cancelOrder,
311 reorder,
312};
NORMALエディタを読み込み中…行1、列:1
やってみよう

ページをめくる

ファイルのどこにでも目標が出ます。画面の外なら、問題の欄に行番号が、右の帯に印が出ます。番号を付けてG。

へ移動(78行目、画面の下)legacy.js
1// legacy.js — Byte Burrito, 2019–present. Please don't add anything here.
1// (Everyone has added something here.)
2
3const TAX_RATE = 0.0875;
4const MAX_DISTANCE_KM = 8;
5const OPEN_HOUR = 11;
6const CLOSE_HOUR = 23;
7const RUSH_START = 12;
8const RUSH_END = 14;
9
10function isOpen(now) {
11 const hour = now.getHours();
12 return hour >= OPEN_HOUR && hour < CLOSE_HOUR;
13}
14
15function isLunchRush(now) {
16 const hour = now.getHours();
17 return hour >= RUSH_START && hour < RUSH_END;
18}
19
20function formatPrice(cents) {
21 const dollars = Math.floor(cents / 100);
22 const rest = String(cents % 100).padStart(2, "0");
23 return "$" + dollars + "." + rest;
24}
25
26function subtotal(items) {
27 let sum = 0;
28 for (const item of items) {
29 sum += item.price * item.qty;
30 }
31 return sum;
32}
33
34function taxFor(amount) {
35 return Math.round(amount * TAX_RATE);
36}
37
38function totalFor(order) {
39 const base = subtotal(order.items);
40 const tax = taxFor(base);
41 const tip = order.tip || 0;
42 return base + tax + tip;
43}
44
45// DEAD CODE: the fax ordering line was switched off in 2020
46function faxOrder(order) {
47 const sheet = renderFaxSheet(order);
48 faxMachine.send(sheet, "+1-555-0100");
49 log("fax sent", order.id);
50 return true;
51}
52
53function validateOrder(order) {
54 if (!order.items || order.items.length === 0) return "empty";
55 if (order.items.some((i) => i.qty <= 0)) return "bad quantity";
56 if (!order.address) return "no address";
57 if (!isOpen(new Date())) return "closed";
58 return null;
59}
60
61function applyCoupon(order, code) {
62 const coupon = COUPONS[code];
63 if (!coupon) return order;
64 if (coupon.expires < Date.now()) return order;
65 const off = Math.round(subtotal(order.items) * coupon.percent);
66 return { ...order, discount: off };
67}
68
69function studentDiscount(order, user) {
70 if (!user.isStudent) return 0;
71 return Math.round(subtotal(order.items) * 0.1);
72}
73
74// DEAD CODE: loyalty points were replaced by the app in 2021
75function addLoyaltyPoints(user, order) {
76 const points = Math.floor(totalFor(order) / 100);
77 user.points = (user.points || 0) + points;
78 saveUser(user);
79 return points;
80}
81
82function distanceKm(a, b) {
83 const dLat = (b.lat - a.lat) * 111;
84 const dLng = (b.lng - a.lng) * 111 * Math.cos((a.lat * Math.PI) / 180);
85 return Math.sqrt(dLat * dLat + dLng * dLng);
86}
87
88function nearestRider(riders, address) {
89 let best = null;
90 for (const rider of riders) {
91 if (!rider.online) continue;
92 const d = distanceKm(rider.position, address.position);
93 if (d > MAX_DISTANCE_KM) continue;
94 if (!best || d < best.distance) best = { rider, distance: d };
95 }
96 return best;
97}
98
99function assignRider(order, riders) {
100 const match = nearestRider(riders, order.address);
101 if (!match) return refund(order, "No rider nearby, sorry!");
102 order.riderId = match.rider.id;
103 order.eta = Math.ceil(match.distance * 4) + 10;
104 notify(match.rider.phone, "New order: " + order.id);
105 return order;
106}
107
108function etaMinutes(order, now) {
109 const rush = isLunchRush(now) ? 10 : 0;
110 return order.eta + rush;
111}
112
113// DEAD CODE: the pager integration, before the riders had phones
114function pageRider(rider, order) {
115 const message = "ORDER " + order.id + " " + order.address.street;
116 pager.send(rider.pagerId, message.slice(0, 80));
117 return true;
118}
119
120function refund(order, reason) {
121 order.status = "refunded";
122 order.refundReason = reason;
123 payments.refund(order.paymentId, totalFor(order));
124 notify(order.customerPhone, "Refunded: " + reason);
125 return order;
126}
127
128function markDelivered(order, now) {
129 order.status = "delivered";
130 order.deliveredAt = now.toISOString();
131 const late = now - new Date(order.placedAt) > order.eta * 60000;
132 if (late) order.lateBy = Math.round((now - new Date(order.placedAt)) / 60000 - order.eta);
133 return order;
134}
135
136function kitchenTicket(order) {
137 const lines = order.items.map((i) => i.qty + " x " + i.name);
138 lines.unshift("ORDER " + order.id);
139 if (order.notes) lines.push("NOTE: " + order.notes);
140 return lines.join("\n");
141}
142
143function printTicket(order) {
144 const ticket = kitchenTicket(order);
145 printer.print(ticket);
146 log("printed", order.id);
147}
148
149// DEAD CODE: the old receipt printer, replaced by email receipts
150function printReceipt(order) {
151 const lines = order.items.map((i) => i.name + " " + formatPrice(i.price * i.qty));
152 lines.push("TOTAL " + formatPrice(totalFor(order)));
153 receiptPrinter.print(lines.join("\n"));
154}
155
156function emailReceipt(order, user) {
157 const body = renderReceipt(order);
158 mailer.send(user.email, "Your Byte Burrito receipt", body);
159}
160
161function menuItem(id) {
162 const item = MENU.find((m) => m.id === id);
163 if (!item) throw new Error("not on the menu: " + id);
164 return item;
165}
166
167function isSpicy(id) {
168 return menuItem(id).spicy === true;
169}
170
171function happyHourPrice(item, now) {
172 const hour = now.getHours();
173 if (hour >= 17 && hour < 19) return Math.round(item.price * 0.8);
174 return item.price;
175}
176
177function priceList(now) {
178 return MENU.map((item) => ({
179 id: item.id,
180 name: item.name,
181 price: formatPrice(happyHourPrice(item, now)),
182 }));
183}
184
185// DEAD CODE: the 2019 "burrito of the month", never shipped
186function burritoOfTheMonth(month) {
187 const picks = ["al-pastor", "veggie", "carnitas", "birria"];
188 return menuItem(picks[month % picks.length]);
189}
190
191function placeOrder(cart, user, now) {
192 const order = { id: newId(), items: cart.items, address: user.address, placedAt: now.toISOString() };
193 const fee = deliveryFee(order, distanceKm(KITCHEN, order.address));
194 const problem = validateOrder(order);
195 if (problem) throw new Error(problem);
196 order.discount = studentDiscount(order, user);
197 order.total = totalFor(order) - order.discount + fee;
198 return order;
199}
200
201function deliveryFee(order, km) {
202 const base = km <= 2 ? 0 : 1.5;
203 const perKm = km > 2 ? (km - 2) * 0.4 : 0;
204 const rush = isLunchRush(new Date()) ? 1 : 0;
205 return Math.round((base + perKm + rush) * 100) / 100;
206}
207
208function newId() {
209 return "BB-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 6);
210}
211
212function log(event, ...details) {
213 console.log("[" + new Date().toISOString() + "] " + event, ...details);
214}
215
216function notify(phone, text) {
217 if (!phone) return;
218 sms.send(phone, text.slice(0, 160));
219}
220
221function saveUser(user) {
222 db.users.put(user.id, user);
223}
224
225function loadUser(id) {
226 return db.users.get(id);
227}
228
229function saveOrder(order) {
230 db.orders.put(order.id, order);
231 log("saved", order.id);
232}
233
234function loadOrder(id) {
235 return db.orders.get(id);
236}
237
238function ordersToday(now) {
239 const day = now.toISOString().slice(0, 10);
240 return db.orders.all().filter((o) => o.placedAt.startsWith(day));
241}
242
243function revenueToday(now) {
244 return ordersToday(now).reduce((sum, o) => sum + o.total, 0);
245}
246
247function busiestHour(now) {
248 const counts = new Array(24).fill(0);
249 for (const o of ordersToday(now)) counts[new Date(o.placedAt).getHours()]++;
250 return counts.indexOf(Math.max(...counts));
251}
252
253// DEAD CODE: the CSV export the accountant asked for, then never used
254function exportCsv(orders) {
255 const rows = orders.map((o) => [o.id, o.total, o.status].join(","));
256 rows.unshift("id,total,status");
257 return rows.join("\n");
258}
259
260function ridersOnline(riders) {
261 return riders.filter((r) => r.online).length;
262}
263
264function riderReport(riders, now) {
265 const online = ridersOnline(riders);
266 const rush = isLunchRush(now);
267 return { online, rush, short: rush && online < 6 };
268}
269
270function weatherDelay(weather) {
271 if (weather === "rain") return 8;
272 if (weather === "snow") return 20;
273 return 0;
274}
275
276function adjustEta(order, weather) {
277 order.eta = order.eta + weatherDelay(weather);
278 return order;
279}
280
281function cancelOrder(order, reason) {
282 if (order.status === "delivered") return order;
283 order.status = "cancelled";
284 return refund(order, reason);
285}
286
287function reorder(previous, user, now) {
288 const cart = { items: previous.items.map((i) => ({ ...i })) };
289 return placeOrder(cart, user, now);
290}
291
292function favourite(user) {
293 const counts = {};
294 for (const o of db.orders.byUser(user.id)) {
295 for (const i of o.items) counts[i.id] = (counts[i.id] || 0) + i.qty;
296 }
297 return Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
298}
299
300module.exports = {
301 isOpen,
302 placeOrder,
303 assignRider,
304 markDelivered,
305 printTicket,
306 emailReceipt,
307 priceList,
308 revenueToday,
309 riderReport,
310 cancelOrder,
311 reorder,
312};
NORMALエディタを読み込み中…0.0s行1、列:1

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。

11ステップ中6
パート3:選ぶ

定規?ページ番号?

どちらでも着けます。わかっていることで選びましょう。

行が見える?定規を読みます:13j。スタックトレースやエラー、誰かに行番号を言われた?そのページを開きます:194G。

自分の行の欄にはいつもページ番号が出ているので、今どこにいるかもわかります。

確かめよう

12ページ?12行先?

ノーマルモードで、カーソルは5行目のconst MAX_DISTANCE_KM = 8;。12Gを押すと、どの行に着きますか?

前これは図です。答えは下から選んでください(1、2、3、4)
4// legacy.js — Byte Burrito, 2019–present. Please don't add anything here.
3// (Everyone has added something here.)
2
1const TAX_RATE = 0.0875;
5const MAX_DISTANCE_KM = 8;
1const OPEN_HOUR = 11;
2const CLOSE_HOUR = 23;
3const RUSH_START = 12;
4const RUSH_END = 14;
5
6function isOpen(now) {
7 const hour = now.getHours();
8 return hour >= OPEN_HOUR && hour < CLOSE_HOUR;
9}
10
11function isLunchRush(now) {
12 const hour = now.getHours();
13 return hour >= RUSH_START && hour < RUSH_END;
NORMAL
答えを選ぶ(クリックか番号キー)と、エンジンが実際にキーを打って答え合わせをします。
11ステップ中7
思い出す練習

どのページ?

どのキー?
知らないファイルを開いた。最初の行へ。
ここまでスクロールして、キーを押す
4問中1問目
知らないファイルを開いた。最初の行へ。
11ステップ中8
チャレンジ

バグ探し

legacy.jsのあちこちに12か所。見えるものは定規、見えないものはページ番号。

練習問題を開いています…
Pro
このレッスンの続きはProで

どのレッスンも最初の練習問題は無料。Proなら残りも全トラックも、ずっと使えます。

Proを見る

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。

11ステップ中9
ボス戦

スタックトレース

トレースを1つずつたどりましょう。問題の欄に、行番号と何が見つかるかが出ます。番号でまっすぐ跳びます。3番目だけは、コマンドとして打ちましょう。それからあと2ページ。防げたはずの住所の確認と、それが実行される所です。

練習問題を開いています…
Pro
このレッスンの続きはProで

どのレッスンも最初の練習問題は無料。Proなら残りも全トラックも、ずっと使えます。

Proを見る

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。

11ステップ中10
ボス戦

場所の違う1行

直し方は書き直しではなく、移動です。194行目のconst fee = deliveryFee(…)が、住所の確認より前に実行されています。if (problem) throw …の下に来るように、行を下げましょう。行全体を切り、1行下がって、下に置きます。

答えを全部見る
練習問題を開いています…
Pro
このレッスンの続きはProで

どのレッスンも最初の練習問題は無料。Proなら残りも全トラックも、ずっと使えます。

Proを見る

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。

注文のやり直し配車係は、落ちた注文をまだ抱えています。上の練習問題をクリアすると見られます。
11ステップ中11
おまけの練習

おまけの練習やらなくてもOK

このチャプターはクリアです。ここからは好きなだけ続けられます。飽きたらそこでおしまい。

エンドレス

ページめくり

ファイルのどこにでも目標が、終わりなく。定規かページ番号か、自分で決めましょう。

練習問題を開いています…
Pro
このレッスンの続きはProで

どのレッスンも最初の練習問題は無料。Proなら残りも全トラックも、ずっと使えます。

Proを見る

この練習問題にはキーボードが必要です。 このまま読み進めて、パソコンで試してください。