-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchallenges-05.test.js
365 lines (301 loc) · 11.7 KB
/
challenges-05.test.js
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
'use strict';
/* ------------------------------------------------------------------------------------------------
CHALLENGE 1 - Review
Write a function that iterates over an array of people objects
and creates a new list of each person's full name using the array method 'map'.
Each object will have the shape {firstName:string, lastName:string}
E.g. [ { firstName:"Jane", lastName:"Doe" }, { firstName:"James", lastName:"Bond"}]
should convert to ["Jane Doe", "James Bond"]
Note the space in between first and last names.
You can assume that neither firstName nor lastName will be blank
------------------------------------------------------------------------------------------------ */
const toLastNames = people => people.map(person => `${person.firstName} ${person.lastName}`);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 2
Write a function named addValues that, given an array of numbers as input, uses reduce to add the values in the array.
------------------------------------------------------------------------------------------------ */
const addValues = (arr) => arr.reduce((a, b) => a + b, 0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 3
Write a function named addPurchases that, given an array of objects as input, uses reduce to find the total amount purchased. Each object contains the keys `item` and `purchasePrice` like the example.
{
item: 'switch'
purchasePrice: 399
}
------------------------------------------------------------------------------------------------ */
// Helpful example: https://stackoverflow.com/a/6300596/7967484
const addPurchases = (arr) => arr.reduce((a,b) => a + b.purchasePrice, 0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 4
Write a function named countNumberOfElements that, given an array as input, uses reduce to count the number of elements in the array.
Note: You may not use the array's built-in length property.
------------------------------------------------------------------------------------------------ */
const countNumberOfElements = (arr) => arr.reduce(a => a + 1, 0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 5
Write a function named returnNames that, given the Star Wars data, below, uses reduce to return an array containing the names of the characters.
------------------------------------------------------------------------------------------------ */
let starWarsData = [{
name: 'Luke Skywalker',
height: '172',
mass: '77',
hair_color: 'blond',
skin_color: 'fair',
eye_color: 'blue',
birth_year: '19BBY',
gender: 'male',
},
{
name: 'C-3PO',
height: '167',
mass: '75',
hair_color: 'n/a',
skin_color: 'gold',
eye_color: 'yellow',
birth_year: '112BBY',
gender: 'n/a'},
{
name: 'R2-D2',
height: '96',
mass: '32',
hair_color: 'n/a',
skin_color: 'white, blue',
eye_color: 'red',
birth_year: '33BBY',
gender: 'n/a'
},
{
name: 'Darth Vader',
height: '202',
mass: '136',
hair_color: 'none',
skin_color: 'white',
eye_color: 'yellow',
birth_year: '41.9BBY',
gender: 'male'
},
{
name: 'Leia Organa',
height: '150',
mass: '49',
hair_color: 'brown',
skin_color: 'light',
eye_color: 'brown',
birth_year: '19BBY',
gender: 'female'
}];
// Help on return: https://stackoverflow.com/a/44875537/7967484
const returnNames = (arr) => arr.reduce((a,b) => a.push(b.name) && a, []);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 6
Write a function named reversedString that takes in a string and returns a string with the letters in reverse order.
Note: You must use reduce for this challenge. You may not use the built-in .reverse() string method.
------------------------------------------------------------------------------------------------ */
// https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/
const reversedString = (str) => (str === '') ? '' : reversedString(str.substr(1)) + str.charAt(0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 7 - Stretch Goal
Write a function named countNumberOfChildren that, given the array of characters, below, uses reduce to return the total number of children in the data set.
------------------------------------------------------------------------------------------------ */
const characters = [
{
name: 'Eddard',
spouse: 'Catelyn',
children: ['Robb', 'Sansa', 'Arya', 'Bran', 'Rickon'],
house: 'Stark',
},
{
name: 'Jon',
spouse: 'Lysa',
children: ['Robin'],
house: 'Arryn',
},
{
name: 'Cersei',
spouse: 'Robert',
children: ['Joffrey', 'Myrcella', 'Tommen'],
house: 'Lannister',
},
{
name: 'Daenarys',
spouse: 'Khal Drogo',
children: ['Drogon', 'Rhaegal', 'Viserion'],
house: 'Targaryen',
},
{
name: 'Mace',
spouse: 'Alerie',
children: ['Margaery', 'Loras'],
house: 'Tyrell',
},
{
name: 'Sansa',
spouse: 'Tyrion',
house: 'Stark',
},
{
name: 'Jon',
spouse: null,
house: 'Snow',
},
];
const countNumberOfChildren = (arr) => arr.reduce((a,b) => b.children === undefined ? a + 0 : a + b.children.length, 0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 8 - Stretch Goal
Write a function that, given an array of numbers as input, uses reduce to calculate the array's average value.
Hint: The accumulator should begin as { count: 0, sum: 0 }
------------------------------------------------------------------------------------------------ */
const calculateAverage = (arr) => arr.reduce((a,b) => {
a.count++;
a.sum += b;
if (a.count !== arr.length) {
return a;
} else {
return a.sum / a.count;
}
}, {count: 0, sum: 0});
/* ------------------------------------------------------------------------------------------------
CHALLENGE 9 - Stretch Goal
Write a function named countPrimeNumbers that, given an array elements as input, uses reduce to count the number of elements that are prime numbers.
You are welcome to use the provided isPrime function.
------------------------------------------------------------------------------------------------ */
const isPrime = (value) => {
for (let i = 2; i < value; i++) {
if (value % i === 0) {
return false;
}
}
return value > 1;
};
const countPrimeNumbers = (arr) => arr.reduce((a, b) => {
if(isPrime(b)) {
a++;
}
return a;
}, 0);
/* ------------------------------------------------------------------------------------------------
CHALLENGE 10 - Stretch Goal
Write a function named extractState that, given the snorlaxData, below, uses reduce to return the object whose 'name' property matches the given string.
If the input array does not have a stat with that specific name, the function should return null.
------------------------------------------------------------------------------------------------ */
const snorlaxData = {
stats: [
{
stat: {
url: 'https://pokeapi.co/api/v2/stat/6/',
name: 'speed',
},
effort: 5,
baseStat: 30,
},
{
stat: {
url: 'https://pokeapi.co/api/v2/stat/5/',
name: 'special-defense',
},
effort: 2,
baseStat: 110,
},
{
stat: {
url: 'https://pokeapi.co/api/v2/stat/4/',
name: 'special-attack',
},
effort: 9,
baseStat: 65,
},
],
name: 'snorlax',
weight: 4600,
};
// TODO: Fix to work with multiple matches
const extractStat = (statName, arr) => arr.reduce((a, b) => {
if(b.stat.name.includes(statName)) {
a = b;
}
return a;
}, {});
/* ------------------------------------------------------------------------------------------------
CHALLENGE 11 - Stretch Goal
Write a function named extractChildren that, given the array of characters from challenge 4, accomplishes the following:
1) Uses filter to return an array of the characters that contain the letter 'a' in their name
2) Then, uses reduce to return an array of all the children's names in the filtered array
------------------------------------------------------------------------------------------------ */
// TODO: This could be a lot better with a better use of reduce
const extractChildren = arr => {
let children = [];
let withA = arr.filter(item => item.name.indexOf('a') !== -1);
withA.reduce((a, b) => {
if(b.children !== undefined) {
b.children.forEach(child => children.push(child));
}
}, []);
return children;
};
/* ------------------------------------------------------------------------------------------------
TESTS
All the code below will verify that your functions are working to solve the challenges.
DO NOT CHANGE any of the below code.
Run your tests from the console: jest challenges-09.test.js
------------------------------------------------------------------------------------------------ */
describe('Testing challenge 1', () => {
test('It should convert object to full name string', () => {
const people = [{ firstName: "Jane", lastName: "Doe" }, { firstName: "James", lastName: "Bond" }];
expect(toLastNames(people)).toStrictEqual(["Jane Doe", "James Bond"]);
});
});
describe('Testing challenge 2', () => {
test('It should add the values of an array', () => {
expect(addValues([1, 2, 3, 4, 5])).toStrictEqual(15);
expect(addValues([])).toStrictEqual(0);
expect(addValues([1, 2, 3, 4, -5])).toStrictEqual(5);
});
});
describe('Testing challenge 3', () => {
test('It should add the purchase price', () => {
expect(addPurchases([{item: 'switch', purchasePrice: 399}, {item: 'toothpaste', purchasePrice: 2}])).toStrictEqual(401);
expect(addPurchases([])).toStrictEqual(0);
});
});
describe('Testing challenge 4', () => {
test('It should return the length of the array', () => {
expect(countNumberOfElements([1, 2, 3, 4, 5])).toStrictEqual(5);
});
});
describe('Testing challenge 5', () => {
test('It should return an array continaing the names of the characters', () => {
expect(returnNames(starWarsData)).toStrictEqual([ 'Luke Skywalker', 'C-3PO', 'R2-D2', 'Darth Vader', 'Leia Organa' ]);
expect(returnNames(starWarsData).length).toStrictEqual(5);
});
});
describe('Testing challenge 6', () => {
test('It should return the string with the characters in reverse order', () => {
expect(reversedString('Code 301')).toStrictEqual('103 edoC');
});
});
describe('Testing challenge 7', () => {
test('It should return the total number of children', () => {
expect(countNumberOfChildren(characters)).toStrictEqual(14);
});
});
describe('Testing challenge 8', () => {
test('It should return the average of the numbers in the array', () => {
expect(calculateAverage([18, 290, 37, 4, 55, 16, 7, 85 ])).toStrictEqual(64);
});
});
describe('Testing challenge 9', () => {
test('It should return a count of the prime numbers in the array', () => {
expect(countPrimeNumbers([1, 2, 13, 64, 45, 56, 17, 8])).toStrictEqual(3);
});
});
describe('Testing challenge 10', () => {
test('It should return any stats that match the input', () => {
expect(extractStat('speed', snorlaxData.stats)).toStrictEqual({ stat: { url: 'https://pokeapi.co/api/v2/stat/6/', name: 'speed' }, effort: 5, baseStat: 30 });
});
});
describe('Testing challenge 11', () => {
test('It should return an array containing the names of the children', () => {
expect(extractChildren(characters)).toStrictEqual([ 'Robb', 'Sansa', 'Arya', 'Bran', 'Rickon', 'Drogon', 'Rhaegal', 'Viserion', 'Margaery', 'Loras' ]);
expect(extractChildren(characters).length).toStrictEqual(10);
});
});