-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
288 lines (267 loc) Β· 11 KB
/
Copy pathindex.html
File metadata and controls
288 lines (267 loc) Β· 11 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
<!DOCTYPE html>
<html lang="en">
<head>
<title>Manipulating Arrays Solution</title>
</head>
<body>
<h1>Manipulating Arrays Solution</h1>
<p>Please load this file in VSCode and Chrome, and open the Console in Chrome Dev Tools.</p>
<p>Work through the challenges found inside the script tag in this document,
until the Console reports all tests passing.</p>
<script>
// In CHALLENGES 1-9 you will flesh out some functions.
// To do this, translate each π§ set of instructions into a working function.
// β Functions are scaffolded for you, but some of them might be missing their parameters.
// β Watch the Guided Project to learn proper debugging technique.
// β The first challenge is _partially_ done for you:
// π CHALLENGE 1
// π§ The function sumNumsFor takes an array of supposed numbers and adds them up, returning the total sum.
// π§ If the function receives an empty array, the returned value ought to be 0.
// π§ If an element in the array happens to not be a number, it is ignored.
// π§ However, if the number 13 is encountered, sumNumsFor returns the string "I'm too superstitious!"
// π§ Examples of usage:
// sumNumsFor([1, 2, 3]) // should return 6
// sumNumsFor([1, 2, 13]) // should return "I'm too superstitious!"
// β Notes:
// π§ There are many ways to solve this, but practice using a for loop to iterate over the array.
// π§ As you have done in the past, declare a variable before you start looping, to accumulate the result.
function sumNumsFor(nums) {
let result = 0
for (let idx = 0; idx < nums.length; idx++) {
let element = nums[idx]
if (typeof element === 'number') {
if (element === 13) {
return "I'm too superstitious!"
}
result += element
}
}
return result
}
// π CHALLENGE 2
// π§ The function stripVowels takes a string, strips all lowcase vowel letters (a,e,i,o,u) from it and returns it.
// π§ Example of usage:
// stripVowels('Lady Gaga') // should return 'Ldy Gg'
// β Notes:
// π§ There are many ways to solve this, but practice using a for loop to iterate over the characters of the string.
function stripVowels(str) {
const split = str.split('')
const result = []
for (let idx = 0; idx < split.length; idx++) {
const char = split[idx]
if (char !== 'a' && char !== 'e' && char!== 'i' && char !=='o' && char !== 'u') {
result.push(char)
}
}
return result.join('')
}
// π CHALLENGE 3
// π§ Reimplement sumNumsFor using a while loop instead of a for loop.
// π§ Examples of usage:
// sumNumsWhile([1, 2, 3]) // should return 6
// sumNumsWhile([1, 2, 13]) // should return "I'm too superstitious!"
function sumNumsWhile(nums) {
let result = 0
let idx = 0
while (idx < nums.length) {
let element = nums[idx]
if (typeof element === 'number') {
if (element === 13) {
return "I'm too superstitious!"
}
result += element
}
idx++
}
return result
}
// π CHALLENGE 4
// π§ The function fightMonsters takes an integer (lifePoints) as its argument, and returns a string.
// π§ Inside the function there will be several rounds of monster-fighting.
// π§ We are alive to fight as long as lifePoints is bigger than zero.
// π§ In the first round, 1 point will be substracted from the initial lifePoints.
// π§ In the second round, 2 points will be substracted from the remaining lifePoints, and so on.
// π§ Eventually a string is returned from the function, in the format "You died in round 5".
// π§ That would be the round when you lost all lifePoints.
// π§ Examples of usage:
// fightMonsters(1) // should return "You died in round 1"
// fightMonsters(2) // should return "You died in round 2"
// fightMonsters(3) // should return "You died in round 2"
// fightMonsters(10) // should return "You died in round 4"
// β Notes:
// π§ There are many ways to solve this, but practice using a while loop.
// π§ Work out using pen and paper how the round number and the lifePoints change after each round.
// π§ As long as there are lifePoints, decrease lifePoints by round number, and increase round number by one.
function fightMonsters(lifePoints) {
let round = 1
while (lifePoints > 0) {
lifePoints -= round
if (lifePoints <= 0) {
return `You died in round ${round}`
}
round++
}
}
// π CHALLENGE 5
// π§ The function findEvenNums takes an array of integers as its argument.
// π§ It returns a new array containing the even numbers found in the original array, in the same order.
// π§ Examples of usage:
// findEvenNums([0, 1, 2, 3, 4]) // should return [0, 2, 4]
// β Notes:
// π§ Use any kind of loop you'd like and the push method to populate the array of even numbers.
function findEvenNums(ints) {
let evens = []
for (let idx in ints) {
let num = ints[idx]
if (num % 2 === 0) {
evens.push(num)
}
}
return evens
}
// π CHALLENGE 6
// π§ The function separateAges takes an array of integers (ages) as its argument.
// π§ It returns a new array containing two elements, which happen to also be arrays.
// π§ The first subarray contains the ages under 21, and the second subarray the ages equal or older than 21.
// π§ Ages in the subarrays should appear in the same order they appeared in the original array.
// π§ Examples of usage:
// separateAges([31, 12, 25, 65, 84, 20]) // should return [[12, 20], [31, 25, 65, 84]]
function separateAges(ages) {
let under21 = []
let others = []
for (let idx = 0; idx < ages.length; idx++) {
let age = ages [idx]
if (age < 21) {
under21.push(age)
} else {
others.push(age)
}
}
return [under21, others]
}
// π CHALLENGE 7
// π§ The function headAndTail takes an array as its argument.
// π§ It returns an object with two properties: "head" and "tail".
// π§ The "head" prop contains the first element of the array.
// π§ The "tail" prop contains an array holding the elements of the array after the first one.
// π§ Examples of usage:
// headAndTail([1, 2, 3]) // should return { head: 1, tail: [2, 3] }
function headAndTail(arr) {
let head = arr[0]
let tail = arr.slice(1)
return { head, tail}
}
// π CHALLENGE 8
// π§ The function nestedLoops takes an array of strings as its argument.
// π§ It returns a new array of strings which are the same as the original ones except that the vowels are capitalized.
// π§ Examples of usage:
// nestedLoops(['hello', 'goodbye']) // should return ['hEllO', 'gOOdbyE']
// β Notes:
// π§ To capitalize a string you can use its toUpperCase method: "a".toUpperCase() returns "A"
function nestedLoops(strings) {
let result = []
for (let idx in strings) {
let word = strings[idx]
let modifiedWord = ''
for (let idx in word) {
let char = word[idx]
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
let upperCased = char.toUpperCase()
modifiedWord += upperCased
} else {
modifiedWord += char
}
}
result.push(modifiedWord)
}
return result
}
// π CHALLENGE 9
// π§ The function crazyTrimmer takes an array as its argument.
// π§ If the array has an even number of elements, the function returns it minus its last element.
// π§ If the number of elements is odd, the function returns the array minus its first and last elements.
// π§ Examples of usage:
// crazyTrimmer(['a', 'b', 'c']) // should return ['b']
// crazyTrimmer(['a', 'b', 'c', 'd']) // should return ['a', 'b', 'c']
// β Notes:
// π§ Practice using pop and slice.
// π§ Note that pop modifies the original array in place and returns the "popped" element, whereas slice gives us a brand new array.
function crazyTrimmer(arr) {
if (arr.length % 2 === 0) {
arr.pop()
return arr
} else {
return arr.slice(1, arr.length - 1)
}
}
// π§ͺ TESTS, do not work below this line
// π§ͺ TESTS, do not work below this line
// π§ͺ TESTS, do not work below this line
runTests('CHALLENGE 1 - sumNumsFor', sumNumsFor, [
[[[1, 2, 3]], 6],
[[[]], 0],
[[[1, 2, "x", 4]], 7],
[[[1, 2, 13, 3]], "I'm too superstitious!"],
])
runTests('CHALLENGE 2 - stripVowels', stripVowels, [
[['aeiou'], ''],
[['xyz'], 'xyz'],
[['aeiouAEIOU'], 'AEIOU'],
[['precaution'], 'prctn'],
])
runTests('CHALLENGE 3 - sumNumsWhile', sumNumsWhile, [
[[[1, 2, 3]], 6],
[[[]], 0],
[[[1, 2, "x", 4]], 7],
[[[1, 2, 13, 3]], "I'm too superstitious!"],
])
runTests('CHALLENGE 4 - fightMonsters', fightMonsters, [
[[1], 'You died in round 1'],
[[2], 'You died in round 2'],
[[3], 'You died in round 2'],
[[10], 'You died in round 4'],
[[100], 'You died in round 14'],
])
runTests('CHALLENGE 5 - findEvenNums', findEvenNums, [
[[[]], []],
[[[0]], [0]],
[[[1, 0, 5, 2, 4]], [0, 2, 4]],
])
runTests('CHALLENGE 6 - separateAges', separateAges, [
[[[31, 12, 25, 65, 84, 20]], [[12, 20], [31, 25, 65, 84]]],
[[[1, 2, 3]], [[1, 2, 3], []]],
[[[21, 22, 23]], [[], [21, 22, 23]]],
])
runTests('CHALLENGE 7 - headAndTail', headAndTail, [
[[[1, 2, 3]], { head: 1, tail: [2, 3] }],
[[["a", "b", "c"]], { head: "a", tail: ["b", "c"] }],
])
runTests('CHALLENGE 8 - nestedLoops', nestedLoops, [
[[['aeiou', 'xyz']], ['AEIOU', 'xyz']],
[[['foo', 'bar', 'baz']], ['fOO', 'bAr', 'bAz']],
])
runTests('CHALLENGE 9 - crazyTrimmer', crazyTrimmer, [
[[[1, 2, 3]], [2]],
[[[1, 2]], [1]],
[[[1, 2, 3, 4]], [1, 2, 3]],
[[[1, 2, 3, 4, 5]], [2, 3, 4]],
])
function runTests(testName, func, tests) {
let results = []
tests.forEach(test => {
const argsList = test[0]
const expected = JSON.stringify(test[1])
const actual = JSON.stringify(func.apply(null, JSON.parse(JSON.stringify(argsList))))
results.push([argsList, expected, actual])
})
console.log('\n' + testName)
if (results.every(result => result[1] === result[2])) console.log('\tβ
All tests pass')
else results.forEach((result, idx) => {
if (result[1] === result[2]) console.log(`\tβ
Test ${idx + 1} passes`)
else console.log(`\tβ Test ${idx + 1} fails: ${func.name}(${result[0]
.map(JSON.stringify)}) should return ${result[1]} but returns ${result[2]}`)
})
}
</script>
</body>
</html>