generated from bloominstituteoftechnology/W_S2_Challenge
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
434 lines (394 loc) · 19 KB
/
index.html
File metadata and controls
434 lines (394 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<!DOCTYPE html>
<html lang="en">
<head>
<title>Web Sprint 2 Challenge</title>
<style>
.widget {
padding: 0 0 0.5rem 0.65rem;
margin-bottom: 0.5rem;
border: 1px solid black;
border-radius: 0.5rem;
}
.widget p {
font-size: 0.75rem;
font-style: italic;
}
.row>div {
display: inline-block;
background-color: lightgrey;
border: 1px solid grey;
width: 2rem;
height: 2rem;
cursor: pointer;
}
#outcome {
font-size: 3rem;
}
</style>
</head>
<body>
<h1>Web Sprint 2 Challenge </h1>
<p>❗ See the last script tag for instructions on completing your Challenge</p>
<!-- widgets start -->
<section class="widget">
<p>Click on a square! (this widget uses the mineSweeper function)</p>
<div class="row" id="row1">
<div></div>
<div></div>
<div></div>
</div>
<div class="row" id="row2">
<div></div>
<div></div>
<div></div>
</div>
<div class="row" id="row3">
<div></div>
<div></div>
<div></div>
</div>
<span id="outcome"></span>
</section>
<form class="widget">
<p>Type a ten-digit number! (this widget uses the normalizePhoneNumber function)</p>
<input type="text" id="phoneNumInput" maxlength="10" />
<span id="normalized"></span>
</form>
<!-- widgets end -->
<!-- The first script tag loads a library called lodash that helps with testing -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script id="challenge">
// In CHALLENGES 1-6 you will write JavaScript functions
function prefixer(prefix, ...args) {
let returnArray = [];
for (let i = 0; i < args.length; i++) {
returnArray.push(prefix + args[i]);
}
return returnArray;
}
// Now call the function and log the output to see the output in console.
console.log(prefixer('un-', 'opposed', 'ashamed'));
// ❗ Functions are scaffolded for you, but are missing their parameters and bodies
// ❗ Do not rename the functions provided, and do not create any other script tags
// ❗ Do not modify the location of the two script tags in this document
// ❗ Debug properly using the Console
// 👉 CHALLENGE 1
// 🧠 profileActivation takes two arguments, profile and reason, which are an object and a string respectively
// The reason arg is only used -and therefore required- to deactivate profiles, not to activate them
// The profile arg has an `active` property holding a Boolean value
// * If profile is active, profileActivation deactivates it and writes a `reason` prop holding the reason
// * If profile is inactive, profileActivation activates it and deletes the `reason` prop from the object
// * In both cases the updated profile object is returned
// 🧠 Edge cases:
// * If the profile is inactive but its `reason` prop is **missing**, return the string "confirm status manually"
// * If the profile is active but it has a `reason` prop, return the string "confirm status manually"
// * If the profile is **missing** an `active` prop, return the string "impossible to ascertain status"
// 🌟 HINT: to confirm the existence of a prop, check that its value is not undefined
function profileActivation(profile, reason) {
if (profile.active === undefined) {
return "impossible to ascertain status";
}
if ((!profile.active && profile.reason === undefined) ||
(profile.active && profile.reason !== undefined)) {
return "confirm status manually";
}
let updatedProfile = { ...profile};
if (updatedProfile.active) {
updatedProfile.active = false;
updatedProfile.reason = reason;
} else {
updatedProfile.active = true;
delete updatedProfile.reason;
}
return updatedProfile;
}
// If this property is not defined,
//it means the function cannot determine whether the profile is active or not.
//If the profile is not active and no reason for its inactive status is provided.
//Or If the profile is active but there is a reason provided when there shouldn't be one.
//the function ends by returning the profile object.
//Instead of writing it twice David, you can place Or's || for one return.remember.
// 👉 CHALLENGE 2
// 🧠 mineSweeper takes a grid as its first argument, and coordinates x and y as the second and third args
// The grid is an array of arrays in the following format: [["🟥","🟦","🟥"],["🟦","🟥","🟥"],["🟥","🟦","🟦"]]
// Each subarray is a row of the grid, the first subarray being the top row:
// [
// ["🟥", "🟦", "🟥"],
// ["🟦", "🟥", "🟥"],
// ["🟥", "🟦", "🟦"]
// ]
// The subarrays can contain any mix of red and blue squares
// The coordinates x and y are numbers: either 1 or 2 or 3
// * An x = 1 and y = 1 means the top-left square
// * An x = 3 and y = 1 means the top-right square
// * An x = 3 and y = 3 means the bottom-right square
// Red squares are mines and blue squares are safe
// * If mineSweeper is called with such coordinates that the player lands on red, return the string "🟥 💀"
// * If the player lands on blue, return the string "🟦 🥳"
// 🧠 Edge cases:
// * If the x or y coordinates are under 1 or over 3, return the string "invalid coordinates"
function mineSweeper(grid, leftToRight, upDown) {
if (leftToRight < 1 || leftToRight > 3 || upDown < 1 || upDown > 3) {
return "invalid coordinates";
}
const column = leftToRight - 1;
const row = upDown - 1;
const square = grid[row][column];
if (square === "🟥") {
return "🟥 💀";
} else if (square === "🟦") {
return "🟦 🥳";
}
}
// 👉 CHALLENGE 3
// 🧠 booleanize takes an object as its single argument, which can have any number of properties
// Loop over the properties and then return the object, after applying the following transformations:
// * If a value is the number zero, it must be transformed into the Boolean false
// * If a value is the number one, it must be transformed into the Boolean true
// * If a value is null, the whole key-value pair must be deleted from the object
// 🧠 Edge cases:
// * If a property name exceeds 9 characters, return the string "shorten all prop names to 9 chars or less"
// 🌟 HINT: careful not to perform any unintended changes on the object
function booleanize(pager) {
for (const key in pager) {
if(key.length > 9)
return "shorten all prop names to 9 chars or less";
}
let result = {};
for (const key in pager) {
if (pager[key] !== null) {
if (typeof pager[key] === 'number') {
result[key] = Boolean(pager[key]);
} else if (typeof pager[key] === 'string') {
result[key] = pager[key];
}
}
}
return result;
}
// function booleanize(pager) {
// let result = {};
// for (const key in pager) {
// // Check the length of the key
// if (key.length > 9) {
// // Shorten the key to 9 characters
// const shortenedKey = key.substring(0, 9);
// result[shortenedKey] = convertValue(pager[key]);
// } else {
// // Key length is 9 characters or less; use it as is
// result[key] = convertValue(pager[key]);
// }
// }
// return result;
// }
// function convertValue(value) {
// if (value !== null) {
// if (typeof value === 'number') {
// // Convert non-null numbers to their boolean equivalent
// return Boolean(value);
// } else if (typeof value === 'string') {
// // Keep strings as is
// return value;
// }
// }
// // Return null if value is null, or if value is of a type that isn't handled
// return null;
// }
// The function starts a loop using a for...in statement,
// which iterates over all properties (or keys) of the pager object.
// Inside the loop, the first if statement checks if any property name
//is longer than 9 characters.
// The pageCount property's value has been changed to true since its original value was 1
//The hasItems property's value has been changed to false since its original value was 0.
//The descriptionText property was removed since its value was null.
//The itemCount property remains unchanged since its value was neither 0, 1, nor null.
// 👉 CHALLENGE 4
// 🧠 scrub takes a string "text" as its first argument, and an array of forbidden words "forbidden" as its second
// Any word in the text included in the array of forbidden words is replaced with a word of equal length but made of lowcase "x"
// The scrubbed text is then returned from the function, as seen in the examples below
// No punctuation is used in the text
// 🧠 Examples of usage:
// scrub("out of the silent planet", ["of", "silent"]) // returns "out xx the xxxxxx planet"
// scrub("the ghost of the navigator", ["the"]) // returns "xxx ghost of xxx navigator"
// scrub("lost somewhere in time", []) // returns "lost somewhere in time"
// scrub("aces high", ["high", "aces", "hearts"]) // returns "xxxx xxxx"
// scrub("", ["high", "aces""]) // returns ""
// 🌟 HINT: useful array methods to use are `push`, `indexOf`, `split`, `join`
function scrub(text, forbidden) {
let words = text.split(' ');
for (let index = 0; index < words.length; index++) {
if(forbidden.includes(words[index])) {
words[index] = 'x' .repeat(words[index].length);
}
}
return words.join(' ');
}
// 👉 CHALLENGE 5
// 🧠 normalizePhoneNumber takes a string as its only argument, representing a ten-digit number
// The function returns a string formatted as seen below
// 🧠 Examples of usage:
// normalizePhoneNumber("9876543210") // returns "(987) 654-3210"
// normalizePhoneNumber("1111111111") // returns "(111) 111-1111"
// 🧠 Edge cases:
// * If the argument is of an incorrect length, return the string "type a 10-digit number"
// * If the argument is of the correct length but any character is not an integer between 0 and 9, return "invalid phone number"
// 🌟 HINT: instead of looping over the number's digits, loop backwards over a template "(XXX) XXX-XXXX"
// 🌟 HINT: at each iteration, if the current character is an "X", replace it with the result of popping a digit from the number
// 🌟 HINT: if you'd rather loop forwards, use `shift` instead of `pop`
function normalizePhoneNumber(number) {
if (number.length !== 10) {
return "type a 10-digit number";
}
if (!Array.from(number).every(char => char >= '0' && char <= '9')) {
return "invalid phone number";
}
const formattedNumber = `(${number.substring(0, 3)}) ${number.substring(3, 6)}-${number.substring(6)}`;
return formattedNumber;
}
console.log(scrub("out of the silent planet", ["of", "silent"])); // returns "out xx the xxxxxx planet"
console.log(scrub("the ghost of the navigator", ["the"])); // returns "xxx ghost of xxx navigator"
console.log(scrub("lost somewhere in time", [])); // returns "lost somewhere in time"
console.log(scrub("aces high", ["high", "aces", "hearts"])); // returns "xxxx xxxx"
console.log(scrub("", ["high", "aces"])); // returns ""
// 👉 CHALLENGE 6 (bonus, NOT graded)
// 🧠 diceRolls takes no arguments and returns a number
// The function throws a six-sided dice until 3 sixes in a row are obtained
// The number of throws it took to obtain that third-in-a-row six is then returned from the function
// 🌟 HINT: research using `Math.random` to obtain a number from 1 to 6
// 🌟 HINT: use `while(true)` to throw the dice indefinitely, but avoid an infinite loop by making sure to break out eventually
// 🌟 HINT: you need to keep track of the total number of throws, as well as how many sixes in a row
function countNums() {
let throws = 0;
let counter = 0;
while (true) {
throws++;
const num = Math.floor(Math.random() *6) +1;
console.log(num);
if (num === 6) {
counter++;
if (counter === 3) {
return throws;
}
} else {
counter = 0;
}
}
}
// function min() {
// let mins = arguments[0];
// for (let index = 1; index < arguments.length; index++) {
// if (arguments[index] < mins) {
// mins = arguments[index];
// }
// }
// return mins; // Changed from 'return min;' to 'return mins;'
// }
// console.log(min(3, 2, 7));
// 🧪 TESTS, do not make any changes below this line ===================
// 🧪 TESTS, do not make any changes below this line ===================
// 🧪 TESTS, do not make any changes below this line ===================
globalThis.challengeVersion = 1
globalThis.profileActivation = profileActivation
globalThis.mineSweeper = mineSweeper
globalThis.booleanize = booleanize
globalThis.scrub = scrub
globalThis.normalizePhoneNumber = normalizePhoneNumber
try {
runTests('CHALLENGE 1 - profileActivation', profileActivation, [
[[{}], 'impossible to ascertain status'],
[[{ active: true, reason: '' }], 'confirm status manually'],
[[{ active: true, reason: 'because' }], 'confirm status manually'],
[[{ active: false }], 'confirm status manually'],
[[{ active: true }, 'because'], { active: false, reason: 'because' }],
[[{ active: false, reason: 'because' }], { active: true }],
])
runTests('CHALLENGE 2 - mineSweeper', mineSweeper, [
[[[["🟥", "🟦", "🟥"], ["🟦", "🟥", "🟥"], ["🟥", "🟦", "🟦"]], 0, 4], "invalid coordinates"],
[[[["🟥", "🟦", "🟥"], ["🟦", "🟥", "🟥"], ["🟥", "🟦", "🟦"]], 0, 1], "invalid coordinates"],
[[[["🟥", "🟦", "🟥"], ["🟦", "🟥", "🟥"], ["🟥", "🟦", "🟦"]], 1, 4], "invalid coordinates"],
[[[["🟦", "🟦", "🟥"], ["🟦", "🟦", "🟦"], ["🟦", "🟦", "🟥"]], 1, 1], "🟦 🥳"],
[[[["🟦", "🟥", "🟦"], ["🟦", "🟦", "🟦"], ["🟥", "🟦", "🟥"]], 2, 1], "🟥 💀"],
[[[["🟥", "🟦", "🟥"], ["🟥", "🟥", "🟦"], ["🟥", "🟥", "🟦"]], 3, 1], "🟥 💀"],
[[[["🟥", "🟦", "🟦"], ["🟥", "🟦", "🟥"], ["🟦", "🟦", "🟦"]], 1, 2], "🟥 💀"],
[[[["🟥", "🟥", "🟥"], ["🟥", "🟦", "🟥"], ["🟦", "🟥", "🟦"]], 2, 2], "🟦 🥳"],
[[[["🟥", "🟦", "🟦"], ["🟦", "🟥", "🟥"], ["🟥", "🟥", "🟦"]], 3, 2], "🟥 💀"],
[[[["🟥", "🟥", "🟥"], ["🟦", "🟦", "🟥"], ["🟥", "🟥", "🟦"]], 1, 3], "🟥 💀"],
[[[["🟥", "🟦", "🟥"], ["🟥", "🟥", "🟥"], ["🟥", "🟦", "🟥"]], 2, 3], "🟦 🥳"],
[[[["🟥", "🟥", "🟥"], ["🟦", "🟥", "🟥"], ["🟥", "🟥", "🟦"]], 3, 3], "🟦 🥳"],
[[[["🟥", "🟦", "🟦"], ["🟥", "🟥", "🟦"], ["🟥", "🟥", "🟥"]], 1, 1], "🟥 💀"],
[[[["🟥", "🟦", "🟦"], ["🟥", "🟥", "🟦"], ["🟥", "🟥", "🟥"]], 2, 2], "🟥 💀"],
[[[["🟥", "🟦", "🟦"], ["🟥", "🟥", "🟦"], ["🟥", "🟥", "🟥"]], 3, 3], "🟥 💀"],
])
runTests('CHALLENGE 3 - booleanize', booleanize, [
[[{ bad1: null }], {}],
[[{ bad1: null, bad2: null }], {}],
[[{ '0123456789': 1 }], 'shorten all prop names to 9 chars or less'],
[[{ a: 1, b: 1 }], { a: true, b: true }],
[[{ a: 0, b: 0 }], { a: false, b: false }],
[[{ a: 1, b: 0, c: null, d: 'Lady Gaga' }], { a: true, b: false, d: 'Lady Gaga' }],
])
runTests('CHALLENGE 4 - scrub', scrub, [
[["out of the silent planet", ["of", "silent"]], "out xx the xxxxxx planet"],
[["out of the silent planet", ["of", "planet"]], "out xx the silent xxxxxx"],
[["the ghost of the navigator", ["the"]], "xxx ghost of xxx navigator"],
[["lost somewhere in time", []], "lost somewhere in time"],
[["aces high", ["high", "aces", "hearts"]], "xxxx xxxx"],
[["", ["high", "aces"]], ""],
])
runTests('CHALLENGE 5 - normalizePhoneNumber', normalizePhoneNumber, [
[["1234567890"], "(123) 456-7890"],
[["1111111111"], "(111) 111-1111"],
[["9876543210"], "(987) 654-3210"],
[[""], "type a 10-digit number"],
[["x"], "type a 10-digit number"],
[["987654321"], "type a 10-digit number"],
[["98765432100"], "type a 10-digit number"],
[["987654321x"], "invalid phone number"],
[["x876543210"], "invalid phone number"],
[["98765x3210"], "invalid phone number"],
])
console.log('\nCHALLENGE 6 does not have auto tests')
function runTests(testName, func, tests) {
let results = []
tests.forEach(test => {
const originalArgsList = _.cloneDeep(test[0])
const argsList = test[0]
const expected = test[1]
const actual = func.apply(null, argsList)
results.push([argsList, expected, actual, originalArgsList])
})
console.log('\n' + testName)
if (results.every(result => _.isEqual(result[1], result[2]))) console.log('\t✅ All tests pass')
else if (results.every(result => !_.isEqual(result[1], result[2]))) console.log('\t❌ All tests fail')
else results.forEach((result, idx) => {
if (_.isEqual(result[1], result[2])) console.log(`\t✅ Test ${idx + 1} passes`)
else console.log(`\t❌ Test ${idx + 1} fails:
${func.name}(${result[3].map(JSON.stringify)})
👉 should return ${JSON.stringify(result[1])}
👉 but returns ${JSON.stringify(result[2])}`)
})
}
const gridElems = [Array.from(row1.children), Array.from(row2.children), Array.from(row3.children)]
const squares = ["🟥", "🟦"]
let grid = [[], [], []]
gridElems.forEach((row, idxRow) => {
row.forEach((square, idxSquare) => {
const emoji = squares[Math.floor(Math.random() * 2)]
grid[idxRow].push(emoji)
if (emoji === squares[0]) square.style.backgroundColor = '#ffecec'
else square.style.backgroundColor = '#f2f2ff'
square.onclick = () => {
const x = idxSquare + 1
const y = idxRow + 1
console.log(`\nYou clicked coordinates [${x}, ${y}]`)
outcome.textContent = mineSweeper(grid, x, y)
}
})
})
phoneNumInput.oninput = evt => {
normalized.textContent = normalizePhoneNumber(evt.target.value)
}
} catch (err) { console.error(err.stack) }
</script>
</body>
</html>