forked from SEIR-725-Batch/daily-js-code-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solutions.js
1280 lines (976 loc) · 42.3 KB
/
solutions.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-----------------------------------------------------------------
Challenge: 00-sayHello (example)
Difficulty: Basic
Prompt:
Write a function called sayHello that returns the string "Hello!".
Examples:
sayHello() //=> Hello!
-----------------------------------------------------------------*/
// Your solution for 00-sayHello (example) here:
function sayHello() {
return 'Hello!'
}
/*-----------------------------------------------------------------
Challenge: 01-addOne
Difficulty: Basic
Prompt:
Write a function called addOne that takes a single number as an argument and returns that number plus 1.
Examples:
addOne(1) //=> 2
addOne(-5) //=> -4
-----------------------------------------------------------------*/
// Your solution for 01-addOne here:
function addOne(n) {
return n + 1;
}
/*-----------------------------------------------------------------
Challenge: 02-addTwoNumbers
Difficulty: Basic
Prompt:
Write a function called addTwoNumbers that accepts two numeric arguments and returns the sum of those two numbers.
If either argument is not a Number, return the value of NaN.
Examples:
addTwoNumbers(5, 10) //=> 15
addTwoNumbers(10, -2) //=> 8
addTwoNumbers(0, 0) //=> 0
addTwoNumbers('Hello', 5) //=> NaN
-----------------------------------------------------------------*/
// Your solution for 02-addTwoNumbers here:
function addTwoNumbers(a, b) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else {
return NaN;
}
}
/*-----------------------------------------------------------------
Challenge: 03-sumNumbers
Difficulty: Basic
Prompt:
- Write a function called sumNumbers that accepts a single array of numbers and returns the sum of the numbers in the array.
- If the array is empty, return 0 (zero).
Examples:
sumNumbers([10]) //=> 10
sumNumbers([5, 10]) //=> 15
sumNumbers([2, 10, -5]) //=> 7
sumNumbers([]) //=> 0
-----------------------------------------------------------------*/
// Your solution for 03-sumNumbers here:
/*--- okay solution ---*/
function sumNumbers(nums) {
var sum = 0;
for(var i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}
/*--- better solution (use forEach unless you have to exit loop early) ---*/
// function sumNumbers(nums) {
// var sum = 0;
// nums.forEach(function(num) {
// sum += num;
// });
// return sum;
// }
/*--- best solution (don't worry, this will make sense soon enough) ---*/
// function sumNumbers(nums) {
// return nums.reduce((sum, num) => sum += num, 0);
// }
/*-----------------------------------------------------------------
Challenge: 04-addList
Difficulty: Basic
Prompt:
- Write a function called addList that accepts any quantity of numbers as arguments, adds them together and returns the resulting sum.
- Assume all parameters will be numbers.
- If called with no arguments, return 0 (zero).
Examples:
add(1) //=> 1
add(1,50,1.23) //=> 52.23
add(7,-12) //=> -5
-----------------------------------------------------------------*/
// Your solution for 04-addList here:
/*--- using the arguments keyword (array-like object) and a for loop ---*/
function addList() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
/*--- make arguments a true array then forEach ---*/
// function addList() {
// var nums = Array.from(arguments);
// var sum = 0;
// nums.forEach(function(num) {
// sum += num;
// });
// return sum;
// }
/*--- use rest paramater syntax (ES2015) then reduce ---*/
// function addList(...nums) {
// // nums will be an array containing all arguments
// return nums.reduce((sum, num) => sum + num, 0);
// }
/*-----------------------------------------------------------------
Challenge: 05-computeRemainder
Difficulty: Basic
Prompt:
- Write a function named computeRemainder that accepts two numeric arguments and returns the remainder of the division of those two numbers.
- The first argument should be the dividend and the second argument should be the divisor.
- If a 0 is passed in as the second argument you should return JavaScript's special numeric value: Infinity.
- For extra fun, complete this challenge without using the modulus (%) operator.
Examples:
computeRemainder(10,2) //=> 0
computeRemainder(4,0) //=> Infinity
computeRemainder(10.5, 3) //=> 1.5
-----------------------------------------------------------------*/
// Your solution for 05-computeRemainder:
/*--- Not using the modulus operator ---*/
function computeRemainder(dividend, divisor) {
if (divisor === 0) return Infinity;
return dividend - (Math.floor(dividend / divisor) * divisor);
}
/*--- Using the modulus operator ---*/
// function computeRemainder(dividend, divisor) {
// if (divisor === 0) return Infinity;
// return dividend % divisor;
// }
/*-----------------------------------------------------------------
Challenge: 06-range
Difficulty: basic
Prompt:
- Write a function called range that accepts two integers as arguments and returns an array of integers starting with the first argument up to one less than the second argument.
- The range function must be called with the first argument less than or equal to the second argument, otherwise return the string "First argument must be less than second".
Examples:
range(1,4) //=> [1,2,3]
range(-2, 3) //=> [-2,-1,0,1,2]
range(1,1) //=> []
range(5,2) //=> "First argument must be less than second"
-----------------------------------------------------------------*/
// Your solution for 06-range here:
function range(start, finish) {
if (start > finish) return 'First argument must be less than second';
var range = [];
for (var n = start; n < finish; n++) {
range.push(n);
}
return range;
}
/*-----------------------------------------------------------------
Challenge: 07-reverseUpcaseString
Difficulty: Basic
Prompt:
- Write a function called reverseUpcaseString that accepts a single string argument, then returns the string with its characters in reverse orderand converts all characters to uppercase.
Examples:
reverseUpcaseString("SEI Rocks!"); //=> "!SKCOR IES"
-----------------------------------------------------------------*/
// Your solution for 07-reverseUpcaseString here:
function reverseUpcaseString(str) {
var results = '';
for (var i = 0; i < str.length; i++) {
// can use square brackets to access chars in a string
// but using the charAt() method is preferred
results = str.charAt(i).toUpperCase() + results;
}
return results;
}
// function reverseUpcaseString(str) {
// // convert string to array, reverse, map and finally join it
// return str.split('').reverse().map(function(char) {
// return char.toUpperCase();
// }).join('');
// }
// function reverseUpcaseString(str) {
// // above version using an arrow function
// return str.split('').reverse().map(c => c.toUpperCase()).join('');
// }
/*-----------------------------------------------------------------
Challenge: 08-removeEnds
Difficulty: Basic
Prompt:
- Write a function called removeEnds that accepts a single string argument, then returns the a string with the first and last characters removed.
- If the length of the string argument is less than 3, return an empty string.
Examples:
removeEnds('SEI Rocks!'); //=> "EI Rocks"
removeEnds('a'); //=> "" (empty string)
-----------------------------------------------------------------*/
// Your solution for 08-removeEnds here:
/*--- Using for loop ---*/
function removeEnds(str) {
if (str.length < 3) return '';
var result= '';
for (var i = 1; i < str.length - 1; i++) {
result += str.charAt(i);
}
return result;
}
/*--- Using substr String method ---*/
// function removeEnds(str) {
// if (str.length < 3) return '';
// return str.substr(1, str.length - 2);
// }
/*-----------------------------------------------------------------
Challenge: 09-charCount
Difficulty: Basic
Prompt:
- Write a function named charCount that accepts a single string argument and returns an object that represents the count of each character in the string.
- The returned object should have keys that represent the character with its value set to the how many times the character appears in the string argument.
- Upper and lower case characters should be counted separately.
- Space characters should be count too.
Examples:
charCount('hello') //=> { h: 1, e: 1, l: 2, o: 1 }
charCount('Today is fantastic!') //=> { T: 1, o: 1, d: 1, a: 3, y: 1, ' ': 2, i: 2, s: 2, f: 1, n: 1, t: 2, c: 1, '!': 1 }
-----------------------------------------------------------------*/
// Your solution for 09-charCount here:
/*--- using a for loop ---*/
function charCount(str) {
var result = {};
for (var i = 0; i < str.length; i++) {
var char = str.charAt(i);
// already seen this char?
if (result[char]) {
result[char]++;
} else {
result[char] = 1;
}
}
return result;
}
/*--- convert str to array and use reduce with a ternary ---*/
// function charCount(str) {
// return str.split('').reduce(function(countObj, char) {
// countObj[char] = countObj[char] ? ++countObj[char] : 1;
// return countObj;
// }, {});
// }
/*-----------------------------------------------------------------
Challenge: 10-formatWithPadding
Difficulty: Basic
Prompt:
- Write a function called formatWithPadding that accepts three arguments:
- A numeric argument (an integer) representing the number to format.
- A string argument (a single character) representing the character used to "pad" the returned string to a minimum length.
- Another numeric argument (an integer) representing the length to "pad" the returned string to.
- The function should return the integer as a string, "left padded" to the length of the 3rd arg using the character provided in the 2nd arg.
- If the length of the integer converted to a string is equal or greater than the 3rd argument, no padding is needed - just return the integer as a string.
Examples:
formatWithPadding(123, '0', 5); //=> "00123"
formatWithPadding(42, '*', 10); //=> "********42"
formatWithPadding(1234, '*', 3); //=> "1234"
-----------------------------------------------------------------*/
// Your solution for 10-formatWithPadding here:
/*--- Using for while loop ---*/
function formatWithPadding(int, char, length) {
var result = int.toFixed(0);
while (result.length < length) {
result = char + result;
}
return result;
}
/*--- Using the padStart String method ---*/
// function formatWithPadding(int, char, length) {
// return int.toFixed(0).padStart(length, char);
// }
/*-----------------------------------------------------------------
Challenge: 11-isPalindrome
Difficulty: Intermediate
Prompt:
- Write a function called isPalindrome that accepts a single string argument, then returns true or false depending upon whether or not the string is a palindrome.
- A palindrome is a word or phrase that are the same forward or backward.
- Casing and spaces are not included when considering whether or not a string is a palindrome.
- If the length of the string is 0 or 1, return true.
Examples:
isPalindrome('SEI Rocks'); //=> false
isPalindrome('rotor'); //=> true
isPalindrome('A nut for a jar of tuna'); //=> true
isPalindrome(''); //=> true
-----------------------------------------------------------------*/
// Your solution for 11-isPalindrome here:
/*--- Using a for loop ---*/
function isPalindrome(str) {
str = str.toLowerCase();
// loop to replace spaces
while (str.includes(' ')) str = str.replace(' ', '');
for (var i = 0; i < Math.floor(str.length / 2); i++) {
if (str.charAt(i) !== str.charAt(str.length - i - 1)) return false;
}
return true;
}
/*--- Using regular expression to replace spaces ---*/
// function isPalindrome(str) {
// // regular expression to replace all spaces
// str = str.toLowerCase().replace(/ /g, '');
// for (var i = 0; i < Math.floor(str.length / 2); i++) {
// if (str.charAt(i) !== str.charAt(str.length - i - 1)) return false;
// }
// return true;
// }
/*-----------------------------------------------------------------
Challenge: 12-hammingDistance
Difficulty: Intermediate
Prompt:
In information theory, the hamming distance refers to the count of the differences between two strings of equal length. It is used in computer science for such things as implementing "fuzzy search" capability.
- Write a function named hammingDistance that accepts two arguments which are both strings of equal length.
- The function should return the count of the symbols (characters, numbers, etc.) at the same position within each string that are different.
- If the strings are not of the same length, the function should return NaN.
Examples:
hammingDistance('abc', 'abc'); //=> 0
hammingDistance('a1c', 'a2c'); //=> 1
hammingDistance('!!!!', '****'); //=> 4
hammingDistance('abc', 'ab'); //=> NaN
-----------------------------------------------------------------*/
// Your solution for 12-hammingDistance here:
function hammingDistance(s1, s2) {
if (s1.length !== s2.length) return NaN;
var count = 0;
for (var i = 0; i < s1.length; i++) {
if (s1.charAt(i) !== s2.charAt(i)) count++;
}
return count;
}
/*--- convert one string to array and reduce ---*/
// function hammingDistance(s1, s2) {
// if (s1.length !== s2.length) return NaN;
// s1.split('').reduce(function(count, char, idx) {
// return char !== s2.charAt(idx) ? count + 1 : count;
// }, 0);
// }
/*-----------------------------------------------------------------
Challenge: 13-mumble
Difficulty: Intermediate
Prompt:
- Write a function called mumble that accepts a single string argument.
- The function should return a string that has each character repeated the number of times according to its position within the string arg. In addition, each repeated section of characters should be separated by a hyphen (-).
- Examples describe it best..
Examples:
mumble('X'); //=> 'X'
mumble('abc'); //=> 'a-bb-ccc'
mumble('121'); //=> '1-22-111'
mumble('!A 2'); //=> '!-AA- -2222'
-----------------------------------------------------------------*/
// Your solution for 13-mumble here:
function mumble(str) {
var result = '';
for (var i = 0; i < str.length; i++) {
// the ((i || '') && '-') only adds a dash if it's not the first iteration
result += ((i || '') && '-') + str.charAt(i).repeat(i + 1);
}
return result;
}
/*--- convert to array and use reduce (break that one-liner down!) ---*/
// function mumble(str) {
// return str.split('').reduce((result, c, i) => result + ((i || '') && '-') + c.repeat(i + 1), '');
// }
/*-----------------------------------------------------------------
Challenge: 14-fromPairs
Difficulty: Intermediate
Prompt:
- Write a function named fromPairs that creates an object from an array containing nested arrays.
- Each nested array will have two elements representing key/value pairs used to create key/value pairs in an object to be returned by the function.
- If a key appears in multiple pairs, the rightmost pair should overwrite previous the previous entry in the object.
Examples:
fromPairs([ ['a', 1], ['b', 2], ['c', 3] ]) //=> { a: 1, b: 2, c: 3 }
fromPairs([ ['name', 'Sam"], ['age', 24], ['name', 'Sally'] ]) //=> { name: "Sally", age: 24 }
-----------------------------------------------------------------*/
// Your solution for 14-fromPairs here:
/*--- using forEach ---*/
function fromPairs(arr) {
var obj = {};
arr.forEach(function(kvArr) {
obj[kvArr[0]] = kvArr[1];
});
return obj;
}
/*--- using reduce & arrow function ---*/
// function fromPairs(arr) {
// return arr.reduce((obj, kvArr) => {
// obj[kvArr[0]] = kvArr[1];
// return obj;
// }, {});
// }
/*-----------------------------------------------------------------
Challenge: 15-mergeObjects
Difficulty: Intermediate
Prompt:
- Write a function named mergeObjects that accepts at least two objects as arguments, merges the properties of the second through n objects into the first object, then finally returns the first object.
- If any objects have the same property key, values from the object(s) later in the arguments list should overwrite earlier values.
Examples:
mergeObjects({}, {a: 1}); //=> {a: 1} (same object as first arg)
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}); //=> {a: 1, b: 2, c: 3, d: 4}
mergeObjects({a: 1, b: 2, c: 3}, {d: 4}, {b: 22, d: 44}); //=> {a: 1, b: 22, c: 3, d: 44}
-----------------------------------------------------------------*/
// Your solution for 15-mergeObjects here:
/*--- Using ES2015's rest parameter syntax ---*/
function mergeObjects(target, ...objects) {
objects.forEach(function(obj) {
// using ES2015's 'for in' loop
for(var key in obj) {
target[key] = obj[key];
}
});
return target;
}
/*--- Using ES2015's Object.assign & spread operator ---*/
// function mergeObjects(target, ...objects) {
// return Object.assign(target, ...objects);
// }
/*-----------------------------------------------------------------
Challenge: 16-findHighestPriced
Difficulty: Intermediate
Prompt:
- Write a function named findHighestPriced that accepts a single array of objects.
- The objects contained in the array are guaranteed to have a price property holding a numeric value.
- The function should return the object in the array that has the largest value held in the price property.
- If there's a tie between two or more objects, return the first of those objects in the array.
- Return the original object, not a copy.
Examples:
findHighestPriced([
{ sku: 'a1', price: 25 },
{ sku: 'b2', price: 5 },
{ sku: 'c3', price: 50 },
{ sku: 'd4', price: 10 }
]);
//=> { sku: 'c3', price: 50 }
findHighestPriced([
{ sku: 'a1', price: 25 },
{ sku: 'b2', price: 50 },
{ sku: 'c3', price: 50 },
{ sku: 'd4', price: 10 }
]);
//=> { sku: 'b2', price: 50 }
-----------------------------------------------------------------*/
// Your solution for 16-findHighestPriced here:
function findHighestPriced(arr) {
var highestPrice = 0;
var resultObj;
arr.forEach(function(item) {
if (item.price > highestPrice) {
highestPrice = item.price;
resultObj = item;
}
});
return resultObj;
}
/*--- using the reduce Array method ---*/
// function findHighestPriced(arr) {
// return arr.reduce((highest, item) => item.price > highest.price ? item : highest);
// }
/*-----------------------------------------------------------------
Challenge: 17-mapArray
Difficulty: Intermediate
Prompt:
The goal is of this challenge is to write a function that performs the functionality of JavaScript's Array.prototype.map method.
- Write a function named mapArray that accepts two arguments: a single array and a callback function.
- The mapArray function should return a new array of the same length as the array argument.
- The mapArray function should iterate over each element in the array (first arg). For each iteration, invoke the callback function (2nd arg), passing to it as arguments, the current element and its index. Whatever is returned by the callback function should be included in the new array at the index of the current iteration.
Examples:
mapArray( [1, 2, 3], function(n) {
return n * 2;
} );
//=> [2, 4, 6] (a new array)
mapArray( ['rose', 'tulip', 'daisy'], function(f, i) {
return `${i + 1} - ${f}`;
} );
//=> ["1 - rose", "2 - tulip", "3 - daisy"]
-----------------------------------------------------------------*/
// Your solution for 17-mapArray here:
function mapArray(arr, cb) {
var newArr = [];
arr.forEach(function(el, idx) {
newArr.push( cb(el, idx) );
});
return newArr;
}
/*-----------------------------------------------------------------
Challenge: 18-reduceArray
Difficulty: Intermediate
Prompt:
The goal is of this challenge is to write a function that performs the functionality of JavaScript's Array.prototype.reduce method.
- Write a function named reduceArray that accepts three arguments: (1) an array; (2) a callback function; and (3) a value used as the initial value of the "accumulator".
- The reduceArray function should return whatever is returned by the callback function on the last iteration.
- The reduceArray function should iterate over each element in the array (first arg). For each iteration, invoke the callback function (2nd arg), passing to it three arguments: (1) the "accumulator", which is the value returned by the callback during the previous iteration; (2) the current element; and (3) the index of the current iteration.
- On the first iteration, provide the third argument provided to reduceArray as the first argument when invoking the callback, then for subsequent iterations, provide the value returned by the callback during the previous iteration.
Examples:
reduceArray( [1, 2, 3], function(acc, n) {
return acc + n;
}, 0);
//=> 6
reduceArray( [1, 2, 3], function(acc, n, i) {
return acc + n + i;
}, 0);
//=> 9
reduceArray( ['Yes', 'No', 'Yes', 'Maybe'], function(acc, v) {
acc[v] = acc[v] ? acc[v] + 1 : 1;
return acc;
}, {} );
//=> {"Yes": 2, "No": 1, "Maybe": 1}
-----------------------------------------------------------------*/
// Your solution for 18-reduceArray here:
function reduceArray(arr, cb, initAcc) {
var acc = initAcc;
arr.forEach(function(el, idx) {
acc = cb(acc, el, idx);
});
return acc;
}
/*-----------------------------------------------------------------
Challenge: 19-flatten
Difficulty: Intermediate
Prompt:
- Write a function named flatten that accepts a single array that may contain nested arrays and returns a new "flattened" array.
- A flattened array is an array that contains no nested arrays.
- Arrays maybe nested at any level.
- If any of the arrays have duplicate values those duplicate values should be present in the returned array.
- The values in the new array should maintain their ordering as shown in the examples below.
Hint:
- This assignment provides an excellent opportunity to use recursion (a function that calls itself). It can also be solved by using an inner function.
Examples:
flatten( [1, [2, 3]] );
//=> [1, 2, 3] (a new array)
flatten( [1, [2, [3, [4]]], 1, 'a', ['b', 'c']] );
//=> [1, 2, 3, 4, 1, 'a', 'b', 'c']
-----------------------------------------------------------------*/
// Your solution for 19-flatten here:
/*--- Using recursion ---*/
function flatten(arr) {
var flatArr = [];
arr.forEach(function(elem) {
// use the Array.isArray static method to test if an array
if (Array.isArray(elem)) {
flatArr = flatArr.concat(flatten(elem));
} else {
flatArr.push(elem);
}
});
return flatArr;
}
/*--- Using recursion and inline ternary for conciseness ---*/
// function flatten(arr) {
// var flatArr = [];
// arr.forEach(function(elem) {
// flatArr = flatArr.concat(Array.isArray(elem) ? flatten(elem): elem);
// });
// return flatArr;
// }
/*--- Use reduce and recursion for a one-liner ---*/
// function flatten(arr) {
// return arr.reduce((flatArr, elem) => flatArr.concat(Array.isArray(elem) ? flatten(elem): elem), []);
// }
/*-----------------------------------------------------------------
Challenge: 20-isPrime
Difficulty: Intermediate
Prompt:
- Write a function named isPrime that returns true when the integer argument passed to it is a prime number and false when the argument passed to it is not prime.
- A prime number is a whole number (integer) greater than 1 that is evenly divisible by only itself.
Examples:
isPrime(2) //=> true
isPrime(3) //=> true
isPrime(4) //=> false
isPrime(29) //=> true
isPrime(200) //=> false
-----------------------------------------------------------------*/
// Your solution for 20-isPrime here:
function isPrime(n) {
if (n < 2 || !Number.isInteger(n)) return false;
for (var i = 2; i <= n / 2; i++) {
if (Number.isInteger(n / i)) return false;
}
return true;
}
/*-----------------------------------------------------------------
Challenge: 21-primeFactors
Difficulty: Intermediate
Prompt:
Now that you have solved the last challenge of determining if a whole number is prime, let's expand upon that concept to...
- Write a function named primeFactors that accepts a whole number greater than one (1) as an argument and returns an array of that argument's prime factors.
- The prime factors of a whole number are the prime numbers that, when multiplied together, equals the whole number.
- If the argument provided is not greater than 1, or not a whole number, then primeFactors should return an empty array.
Examples:
primeFactors(2) //=> [2]
primeFactors(3) //=> [3]
primeFactors(4) //=> [2, 2]
primeFactors(18) //=> [2, 3, 3]
primeFactors(29) //=> [29]
primeFactors(105) //=> [3, 5, 7]
primeFactors(200) //=> [2, 2, 2, 5, 5]
-----------------------------------------------------------------*/
// Your solution for 21-primeFactors here:
/*--- most logical approach ---*/
function primeFactors(n) {
var factors = [];
if (n < 2 || !Number.isInteger(n)) return factors;
// function to help find next prime to divide by...
function isPrime(n) {
if (n < 2 || !Number.isInteger(n)) return false;
for (var i = 2; i <= n / 2; i++) {
if (Number.isInteger(n / i)) return false;
}
return true;
}
var prime = 2; // start with smallest prime
while (!isPrime(n)) {
if (Number.isInteger(n / prime)) {
factors.push(prime);
n = n / prime;
} else {
// find next prime
prime++;
while (!isPrime(prime)) prime++;
}
}
factors.push(n);
return factors;
}
/*-- a more efficient algorithm that relies on the fact
that you don't have to check if the divisor is prime
as shown here:
https://people.revoledu.com/kardi/tutorial/BasicMath/Prime/Algorithm-PrimeFactor.html ---*/
// function primeFactors(n) {
// var factors = [];
// if (n < 2 || !Number.isInteger(n)) return factors;
// var divisor = 2;
// while (n >= divisor * divisor) {
// if (Number.isInteger(n / divisor)) {
// factors.push(divisor);
// n = n / divisor;
// } else {
// divisor++;
// }
// }
// factors.push(n);
// return factors;
// }
/*-----------------------------------------------------------------
Challenge: 22-intersection
Difficulty: Intermediate
Prompt:
- Write a function named intersection that accepts two arguments which are both arrays. The array arguments may contain any mixture of strings, numbers and/or booleans - but no reference types, i.e., objects.
- The function should return a new array containing all elements in common, including repeating element values.
- The ordering of the elements in the returned is not important.
- If there are no elements in the arrays in common, the intersection function should return an empty array.
- The function should not mutate (change) either argument.
Examples:
intersection(['a', 1], []) //=> []
intersection(['a', 1], [true, 'a', 15]) //=> ['a']
intersection([1, 'a', true, 1, 1], [true, 1, 'b', 1]) //=> [1, true, 1]
-----------------------------------------------------------------*/
// Your solution for 22-intersection here:
function intersection(a1, a2) {
var result = [];
// create copy of 2nd array for purpose of handling dups
var _a2 = [...a2];
a1.forEach(val => {
var idx = _a2.indexOf(val);
if (idx > -1) result.push(_a2.splice(idx, 1)[0]);
});
return result;
}
/*-----------------------------------------------------------------
Challenge: 23-balancedBrackets
Difficulty: Intermediate
Prompt:
- Write a function called balancedBrackets that accepts a single string as argument.
- The input string is composed entirely of parentheses, brackets and/or curly braces, i.e., (), [] and/or {}. Referred to as "braces" from this point forward...
- The balancedBraces function should return true if the string's braces are "balanced" and false if they are not.
- The brackets are considered unbalanced if any closing bracket does not close the same type of opening bracket, ignoring already matched brackets between them. Examples explain it best...
Examples:
balancedBrackets( '()' ) // => true
balancedBrackets( '(]' ) // => false
balancedBrackets( '[{}]' ) // => true
balancedBrackets( '[(])' ) // => false
balancedBrackets( '[({}[])]' ) // => true
-----------------------------------------------------------------*/
// Your solution for 23-balancedBrackets here:
/*
The solution for this challenge is best implemented using
a data structure known as a 'stack'. Think of a stack working a lot
like a stack of papers where you always place new papers on top
and always remove the top paper.
*/
function balancedBrackets(str) {
// can't be balanced if string odd in length
if (str.length % 2) return false;
var stack = [];
for (var i = 0; i < str.length; i++) {
var b = str.charAt(i);
if ( '([{'.includes(b) ) {
// add opening brackets to the stack
stack.push(b);
} else {
// not an opening bracket, so remove last opening and check if matched
if (!'() {} []'.includes(stack.pop() + b)) return false;
}
}
return true;
}
/*--- Using Array.every method to iterate unless false is returned
Also using arrow function ---*/
// function balancedBrackets(str) {
// var stack = [];
// return str.split('').every(c => {
// if ('([{'.includes(c)) {
// return stack.push(c);
// } else {
// return '() {} []'.includes(stack.pop() + c)
// }
// });
// }
/*--- Holy ternary Batman! Almost a one-liner! ---*/
// function balancedBrackets(str) {
// var a = [];
// return str.split('').every(c => '([{'.includes(c) ? a.push(c) : '() {} []'.includes(a.pop() + c));
// }
/*-----------------------------------------------------------------
Challenge: 24-isWinningTicket
Difficulty: Intermediate
Prompt:
- Write a function called isWinningTicket that accepts a single array an as argument.
- The input array represents a 'lottery ticket' consisting of one or more nested 2-value arrays. The first value of a nested array will be a string, the second an integer.
- The isWinningTicket function should return true if all of the nested arrays have a character in the string whose numeric character code equals the integer (2nd value).
- If any of the nested arrays have a string where all of the character's character code does not match the integer, then return false.
Hints:
- A character/string can be created from a character code using the String.fromCharCode() class method.
- A character within a string's character code can be obtained using the charCodeAt() string method.
Examples:
isWinningTicket( [ ['ABC', 65] ] ) // => true
isWinningTicket( [ ['ABC', 999], ['XY', 89] ] ) // => false
isWinningTicket( [ ['ABC', 66], ['dddd', 100], ['Hello', 108] ] ) // => true
isWinningTicket( [ ['ABC', 66], ['dddd', 15], ['Hello', 108] ] ) // => false
-----------------------------------------------------------------*/
// Your solution for 24-isWinningTicket here:
/* Naive for loops - :( */
function isWinningTicket(ticket){
var winner = true;
for (var i = 0; i < ticket.length; i++) {
var charFromNumber = String.fromCharCode(ticket[i][1]);
if (!ticket[i][0].includes(charFromNumber)) {
winner = false;
break;
}
}
return winner;
}
/* Array.prototype.every is sweet */
// function isWinningTicket(ticket){
// return ticket.every(function(arr) {
// return arr[0].includes(String.fromCharCode(arr[1]));
// });
// }
/* Arrow functions help make concise one-liners possible */
// function isWinningTicket(ticket){
// return ticket.every(arr => arr[0].includes(String.fromCharCode(arr[1])));
// }