-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntermediateAlgorithmScripting.js
More file actions
2844 lines (2142 loc) · 90.2 KB
/
IntermediateAlgorithmScripting.js
File metadata and controls
2844 lines (2142 loc) · 90.2 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
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
/* Sum All Numbers in a Range
We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.
For example, sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.
*/
function sumAll(arr) {
return 1;
}
sumAll([1, 4]);
// SOLUTION
/* Problem Explanation
You need to create a program that will take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as 1+2+3 and not just 3+1
Hints
Hint 1
Use Math.max() to find the maximum value of two numbers.
Hint 2
Use Math.min() to find the minimum value of two numbers.
Hint 3
Remember to that you must add all the numbers in between so this would require a way to get those numbers.
*/
function sumAll(arr) {
let max = Math.max(arr[0], arr[1]);
let min = Math.min(arr[0], arr[1]);
let sumBetween = 0;
for (let i = min; i <= max; i++) {
sumBetween += i;
}
return sumBetween;
}
sumAll([1, 4]);
/* Code Explanation
First create a variable to store the max number between two.
The same as before for the Smallest number.
We create a accumulator variable to add the numbers.
Since the numbers might not be always in order, using max() and min() will help organize.
*/
// SOLUTION 2
const sumAll = arr => {
// Buckle up everything to one!
const startNum = arr[0];
const endNum = arr[1];
// Get the count of numbers between the two numbers by subtracting them and add 1 to the absolute value.
// ex. There are |1-4| + 1 = 4, (1, 2, 3, 4), 4 numbers between 1 and 4.
const numCount = Math.abs(startNum - endNum) + 1;
// Using Arithmetic Progression summing formula
const sum = ((startNum + endNum) * numCount) / 2;
return sum;
};
/* Code Explanation
The formula for calculating the sum of a continuous range is “(startNum + endNum) * numCount / 2”.
arr[0] and arr[1] can either be startNum or endNum, order doesn’t matter.
We can get the count of numbers in range by “Math.abs(arr[0] - arr[1]) + 1”.
Applying the formula by plugging in the numbers.
*/
// SOLUTION 3
function sumAll(arr) {
let sumBetween = 0;
for (let i = Math.min(...arr); i <= Math.max(...arr); i++) {
sumBetween += i;
}
return sumBetween;
}
sumAll([1, 4]);
/* Code Explanation
Creating a variable sum to store the sum of the elements.
Starting iteration of the loop from min element of given array and stopping when it reaches the max element.
Using a spread operator (…arr) allows passing the actual array to the function instead of one-by-one elements.
*/
// SOLUTION 4
function sumAll(arr) {
const [first, last] = [...arr].sort((a, b) => a - b);
return first !== last
? first + sumAll([first + 1, last])
: first;
}
sumAll([1, 4]);
/* Should :
sumAll([1, 4]) should return a number.
Passed
sumAll([1, 4]) should return 10.
Passed
sumAll([4, 1]) should return 10.
Passed
sumAll([5, 10]) should return 45.
Passed
sumAll([10, 5]) should return 45.
END*/
/* Diff Two Arrays
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
Note: You can return the array with its elements in any order.
*/
function diffArray(arr1, arr2) {
var newArr = [];
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
// SOLUTION
/* Problem Explanation
Check two arrays and return a new array that contains only the items that are not in either of the original arrays.
Hints
Hint 1
Merge the list to make it easy to compare functions.
Hint 2
Use filter to get the new array, you will need to create a callback function.
Hint 3
The best way to go about the callback function is to check if the number from the new merged array is not in both original arrays and return it.
*/
// (Imperative Solution)
function diffArray(arr1, arr2) {
var newArr = [];
function onlyInFirst(first, second) {
// Looping through an array to find elements that don't exist in another array
for (var i = 0; i < first.length; i++) {
if (second.indexOf(first[i]) === -1) {
// Pushing the elements unique to first to newArr
newArr.push(first[i]);
}
}
}
onlyInFirst(arr1, arr2);
onlyInFirst(arr2, arr1);
return newArr;
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
/* Code Explanation
Read the comments in the code.
*/
// SOLUTION 2 (Declarative Solution):
function diffArray(arr1, arr2) {
return arr1
.concat(arr2)
.filter(item => !arr1.includes(item) || !arr2.includes(item));
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
/* Code Explanation
Explain solution here and add any relevant links
*/
// SOLUTION (Declarative Solution)
function diffArray(arr1, arr2) {
return [...diff(arr1, arr2), ...diff(arr2, arr1)];
function diff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
}
/* Should :
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) should return an array.
Passed
["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["pink wool"].
Passed
["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with one item.
Passed
["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["diorite", "pink wool"].
Passed
["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with two items.
Passed
["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return [].
Passed
["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return an empty array.
Passed
[1, 2, 3, 5], [1, 2, 3, 4, 5] should return [4].
Passed
[1, 2, 3, 5], [1, 2, 3, 4, 5] should return an array with one item.
Passed
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4].
Passed
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return an array with two items.
Passed
[], ["snuffleupagus", "cookie monster", "elmo"] should return ["snuffleupagus", "cookie monster", "elmo"].
Passed
[], ["snuffleupagus", "cookie monster", "elmo"] should return an array with three items.
Passed
[1, "calf", 3, "piglet"], [7, "filly"] should return [1, "calf", 3, "piglet", 7, "filly"].
Passed
[1, "calf", 3, "piglet"], [7, "filly"] should return an array with six items.
END*/
/* Seek and Destroy
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
Note: You have to use the arguments object.
*/
function destroyer(arr) {
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
// SOLUTION
/* Problem Explanation
This problem is a bit tricky because you have to familiarize yourself with Arguments, as you will have to work with two or more but on the script you only see two. You will remove any number from the first argument that is the same as any other other arguments.
Hints
Hint 1
You need to work with arguments as if it was a regular array. The best way is to convert it into one.
Hint 2
You may want to use use various methods like: indexOf(), includes(), or filter(). When in doubt about any function, check those docs!
*/
function destroyer(arr) {
let valsToRemove = Object.values(arguments).slice(1);
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < valsToRemove.length; j++) {
if (arr[i] === valsToRemove[j]) {
delete arr[i];
}
}
}
return arr.filter(item => item !== null);
}
/* Code Explanation
Create an array of valsToRemove using Object.values(arguments).slice(1) and store it in the variable valsToRemove. We’ll use this to check against arr.
Start a basic for loop to iterate through arr. Nest another for loop inside the first, changing the integer variable j and arr to valsToRemove. This second loop will iterate through valsToRemove .
Within the second loop create an if statement, checking strictly === that the current value of arr[i] is equal to valsToRemove[j].
If the value at the current index is equal in both arrays, use delete to remove it from arr.
Outside of the nested loops: return the modified array, filtering out any null's created by the delete operator.
*/
// SOLUTION 2
function destroyer(arr) {
var valsToRemove = Array.from(arguments).slice(1);
return arr.filter(function(val) {
return !valsToRemove.includes(val);
});
}
/* Code Explanation
Declare a variable named valsToRemove and set it equal to a new Array object from() the arguments passed into the function. Use the slice() method on the array of arguments, starting from the second index, 1.
Return the filtered array, using includes() in the callback function to check if val is not in valsToRemove; returning true to keep the value in the original array or false to remove it.
*/
// SOLUTION 3
function destroyer(arr, ...valsToRemove) {
return arr.filter(elem => !valsToRemove.includes(elem));
}
/* Code Explanation
Using spread operator to retrieve the arguments.
Return the filtered array, using includes().
*/
/* Should :
destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
Passed
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].
Passed
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
Passed
destroyer([2, 3, 2, 3], 2, 3) should return [].
Passed
destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].
Passed
destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan") should return [12,92,65].
END*/
/* Wherefore art thou
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching name and value pairs (second argument). Each name and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the name and its value, that was passed on as the second argument.
*/
function whatIsInAName(collection, source) {
var arr = [];
// Only change code below this line
// Only change code above this line
return arr;
}
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
// SOLUTION
/* Problem Explanation
Write an algorithm that will take an array for the first argument and return an array with all the objects that matches all the properties and values in the Object passed as second parameter.
Hints
Hint 1
You may use for loop or the Array.prototype.filter method.
Hint 2
Try to use the Object.prototype.hasOwnProperty method to know if the property name exists in an object (as its own property).
Hint 3
Check equivalence of Object in collection with Object passed as second parameter to whatIsInAName function.
*/
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function(obj) {
for (var i = 0; i < srcKeys.length; i++) {
if (
!obj.hasOwnProperty(srcKeys[i]) ||
obj[srcKeys[i]] !== source[srcKeys[i]]
) {
return false;
}
}
return true;
});
}
// test here
whatIsInAName(
[
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }
],
{ last: "Capulet" }
);
/* Code Explanation
We filter through the array using .filter().
Using a for loop we loop through each item in the object.
We use a if statement to check if the object in the collection doesn’t have the key and the property value doesn’t match the value in source.
We return false if the above if statement is correct. Otherwise, we return true;
*/
// SOLUTION 2
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
return collection.filter(function(obj) {
return srcKeys.every(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
});
}
// test here
whatIsInAName(
[
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }
],
{ last: "Capulet" }
);
/* Code Explanation
We filter through the collection using .filter().
Next, we return a Boolean value for the .filter() method.
Finally, we reduce to Boolean value to be returned for the .every() method.
*/
// SOLUTION 3
function whatIsInAName(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function(obj) {
return srcKeys
.map(function(key) {
return obj.hasOwnProperty(key) && obj[key] === source[key];
})
.reduce(function(a, b) {
return a && b;
});
});
}
// test here
whatIsInAName(
[
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }
],
{ last: "Capulet" }
);
/* Code Explanation
We start by filtering through collection using Array.filter().
Next, we map through all keys and return Boolean values based on the check conditions: both the key and its corresponding value must exist within the object we are filtering through.
Then we reduce the mapped Boolean values to a single Boolean that indicates whether all srcKeys pass the conditions checked above.
This single Boolean will be used to filter through the collection.
*/
/* Should :
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) should return [{ first: "Tybalt", last: "Capulet" }].
Passed
whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) should return [{ "apple": 1, "bat": 2, "cookie": 2 }].
Passed
whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }].
Passed
whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) should return []
END*/
/* Spinal Tap Case
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
*/
function spinalCase(str) {
return str;
}
spinalCase('This Is Spinal Tap');
// SOLUTION
/* Problem Explanation
Convert the given string to a lowercase sentence with words joined by dashes.
Hints
Hint 1
Create a regular expression for all white spaces and underscores.
Hint 2
You will also have to make everything lowercase.
Hint 3
The tricky part is getting the regular expression part to work, once you do that then just turn the uppercase to lowercase and replace spaces with dashes using replace().
*/
function spinalCase(str) {
// Create a variable for the white space and underscores.
var regex = /\s+|_+/g;
// Replace low-upper case to low-space-uppercase
str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
// Replace space and underscore with -
return str.replace(regex, "-").toLowerCase();
}
// test here
spinalCase("This Is Spinal Tap");
/* Code Explanation
regex contains the regular expression /\s+|_+/g, which will select all white spaces and underscores.
The first replace() puts a space before any encountered uppercase characters in the string str so that the spaces can be replaced by dashes later on.
While returning the string, another replace() replaces spaces and underscores with dashes using regex.
*/
// SOLUTION 2
function spinalCase(str) {
// Replace low-upper case to low-space-uppercase
str = str.replace(/([a-z])([A-Z])/g, "$1 $2");
// Split on whitespace and underscores and join with dash
return str
.toLowerCase()
.split(/(?:_| )+/)
.join("-");
}
// test here
spinalCase("This Is Spinal Tap");
/* Code Explanation
Similar to the first solution, the first replace() puts a space before any encountered uppercase characters in the string str so that the spaces can be replaced by dashes later on.
Instead of using replace() here to replace whitespace and underscores with dashes, the string is split() on the regular expression /(?:_| )+/ and join()-ed on -.
*/
// SOLUTION 3
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str
.split(/\s|_|(?=[A-Z])/)
.join("-")
.toLowerCase();
}
/* Code Explanation
Split the string at one of the following conditions (converted to an array)
a whitespace character [\s] is encountered
underscore character [_] is encountered
or is followed by an uppercase letter [(?=[A-Z])]
Join the array using a hyphen (-)
Lowercase the whole resulting string
*/
/* Should :
spinalCase("This Is Spinal Tap") should return the string this-is-spinal-tap.
Passed
spinalCase("thisIsSpinalTap") should return the string this-is-spinal-tap.
Passed
spinalCase("The_Andy_Griffith_Show") should return the string the-andy-griffith-show.
Passed
spinalCase("Teletubbies say Eh-oh") should return the string teletubbies-say-eh-oh.
Passed
spinalCase("AllThe-small Things") should return the string all-the-small-things.
END*/
/* Pig Latin
Pig Latin is a way of altering English Words. The rules are as follows:
- If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add ay to it.
- If a word begins with a vowel, just add way at the end.
Translate the provided string to Pig Latin. Input strings are guaranteed to be English words in all lowercase.
*/
function translatePigLatin(str) {
return str;
}
translatePigLatin("consonant");
// SOLUTION
/* Problem Explanation
You need to create a program that will translate from English to Pig Latin. Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an “ay”. If a word begins with a vowel you just add “way” to the end. It might not be obvious but you need to remove all the consonants up to the first vowel in case the word does not start with a vowel.
Hints
Hint 1
You will probably want to use regular expressions. This will allow you to convert the words easily.
Hint 2
If the first character is a vowel, then take that whole word and add ‘way’ at the end. Otherwise comes the tricky part, take the consonant(s) before the first vowel and move it to the end and add ‘ay’. This might be confusing but, it is not just the first consonant but all of them before the first vowel.
Hint 3
You will need to use everything you know about string manipulation to get the last part right. However, it can be done with substr alone.
*/
function translatePigLatin(str) {
let consonantRegex = /^[^aeiou]+/;
let myConsonants = str.match(consonantRegex);
return myConsonants !== null
? str
.replace(consonantRegex, "")
.concat(myConsonants)
.concat("ay")
: str.concat("way");
}
translatePigLatin("consonant");
/* Code Explanation
start at beginning and get longest match of everything not a vowel (consonants)
if regex pattern found, it saves the match; else, it returns null
if regex pattern found (starts with consonants), it deletes match, adds the match to the end, and adds “ay” to the end
if regex pattern not found (starts with vowels), it just adds “way” to the ending
*/
// SOLUTION 2
function translatePigLatin(str) {
// Create variables to be used
var pigLatin = "";
var regex = /[aeiou]/gi;
// Check if the first character is a vowel
if (str[0].match(regex)) {
pigLatin = str + "way";
} else if (str.match(regex) === null) {
// Check if the string contains only consonants
pigLatin = str + "ay";
} else {
// Find how many consonants before the first vowel.
var vowelIndice = str.indexOf(str.match(regex)[0]);
// Take the string from the first vowel to the last char
// then add the consonants that were previously omitted and add the ending.
pigLatin = str.substr(vowelIndice) + str.substr(0, vowelIndice) + "ay";
}
return pigLatin;
}
// test here
translatePigLatin("consonant");
/* Code Explanation
Make an empty string to hold your Pig Latin word.
Assign your appropriate regular expression to a variable.
If the first character is a vowel, just add way to end of string and return it.
If the first character is not a vowel:
Find number of consonants before first vowel with help of indexOf(), match() and regex.
Start Pig Latin string with first vowel till the end.
Add letters before first vowel to end of string.
substr() is used for string manipulation here.
Add ay to end of string and return it.
*/
// SOLUTION 3
function translatePigLatin(str) {
if (str.match(/^[aeiou]/)) return str + "way";
const consonantCluster = str.match(/^[^aeiou]+/)[0];
return str.substring(consonantCluster.length) + consonantCluster + "ay";
}
// test here
translatePigLatin("consonant");
/* Code Explanation
First, check to see if the string begins with a vowel.
The regex looks at the beginning of the string ^ for one of the specified characters [aeiou]
If it does, you only need to return the original string with “way” appended on the end.
If the string does not start with a vowel, we want to build a string which contains every consonant before the first vowel in the provided string.
To do this, look at the beginning of a string ^ for one or more characters + NOT specified [^aeiou].
If there is a match (and in this case, there always will be), match() returns an Array with the matched string as the first element, which is all we want. Grab it with [0].
Now, we can start building our Pig Latin string to return. This can be built in three parts:
The first part contains all of the characters in the original string, starting from the first vowel. We can easily get these characters by creating a substring of the original string, with its starting index being the first vowel.
The second part contains the consonant string we just built. (If you add the second and first parts of this string together, you will get the original string.)
The final part contains “ay”.
*/
// SOLUTION 4
function translatePigLatin(str) {
return str
.replace(/^[aeiou]\w*/, "$&way")
.replace(/(^[^aeiou]+)(\w*)/, "$2$1ay");
}
// test here
translatePigLatin("consonant");
/* Code Explanation
Use replace() on the string, using a regular expression to check if the first letter is a consonant and adding way at the end in this case. If the first letter is a consonant nothing will happen at this point.
Use replace() again to check for consonants at the beginning of the word and to move it or them to the end of the word and add ay at the end.
*/
// SOLUTION 5
function translatePigLatin(str, charPos = 0) {
return ['a', 'e', 'i', 'o', 'u'].includes(str[0])
? str + (charPos === 0 ? 'way' : 'ay')
: charPos === str.length
? str + 'ay'
: translatePigLatin(str.slice(1) + str[0], charPos + 1);
}
/* Should :
translatePigLatin("california") should return the string aliforniacay.
Passed
translatePigLatin("paragraphs") should return the string aragraphspay.
Passed
translatePigLatin("glove") should return the string oveglay.
Passed
translatePigLatin("algorithm") should return the string algorithmway.
Passed
translatePigLatin("eight") should return the string eightway.
Passed
Should handle words where the first vowel comes in the middle of the word. translatePigLatin("schwartz") should return the string artzschway.
Passed
Should handle words without vowels. translatePigLatin("rhythm") should return the string rhythmay.
END*/
/* Search and Replace
Perform a search and replace on the sentence using the arguments provided and return the new sentence.
First argument is the sentence to perform the search and replace on.
Second argument is the word that you will be replacing (before).
Third argument is what you will be replacing the second argument with (after).
Note: Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word Book with the word dog, it should be replaced as Dog
*/
function myReplace(str, before, after) {
return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
// SOLUTION
/* Problem Explanation
You will create a program that takes a sentence, then search for a word in it and replaces it for a new one while preserving the uppercase if there is one.
Hints
Hint 1
Find the index where before is in the string.
Hint 2
Check first letter case.
Hint 3
Strings are immutable, you will need to save the edits on another variable, even if you must reuse the same one just to make it look like the changes where done using just that one variable.
*/
function myReplace(str, before, after) {
// Find index where before is on string
var index = str.indexOf(before);
// Check to see if the first letter is uppercase or not
if (str[index] === str[index].toUpperCase()) {
// Change the after word to be capitalized before we use it.
after = after.charAt(0).toUpperCase() + after.slice(1);
} else {
// Change the after word to be uncapitalized before we use it.
after = after.charAt(0).toLowerCase() + after.slice(1);
}
// Now replace the original str with the edited one.
str = str.replace(before, after);
return str;
}
// test here
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
/* Code Explanation
Use indexOf() to find location of before in string.
If first letter of before is capitalized, change first letter of after to uppercase.
Replace before in the string with after.
Return the new string.
*/
// SOLUTION 2
function myReplace(str, before, after) {
// Check if first character of argument "before" is a capital or lowercase letter and change the first character of argument "after" to match the case
if (/^[A-Z]/.test(before)) {
after = after[0].toUpperCase() + after.substring(1)
} else {
after = after[0].toLowerCase() + after.substring(1)
}
// return string with argument "before" replaced by argument "after" (with correct case)
return str.replace(before, after);
}
// test here
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
/* Code Explanation
In this solution, regular expression ^[A-Z] is used to check (test) if the first character of before is uppercase.
If first letter of before is capitalized, change the first letter of after to uppercase.
Else: If first letter of before is lowercase, change the first letter of after to lowercase
Return the new string replacing before with after.
*/
// SOLUTION 3
function myReplace(str, before, after) {
// create a function that will change the casing of any number of letter in parameter "target"
// matching parameter "source"
function applyCasing(source, target) {
// split the source and target strings to array of letters
var targetArr = target.split("");
var sourceArr = source.split("");
// iterate through all the items of sourceArr and targetArr arrays till loop hits the end of shortest array
for (var i = 0; i < Math.min(targetArr.length, sourceArr.length); i++) {
// find out the casing of every letter from sourceArr using regular expression
// if sourceArr[i] is upper case then convert targetArr[i] to upper case
if (/[A-Z]/.test(sourceArr[i])) {
targetArr[i] = targetArr[i].toUpperCase();
}
// if sourceArr[i] is not upper case then convert targetArr[i] to lower case
else targetArr[i] = targetArr[i].toLowerCase();
}
// join modified targetArr to string and return
return targetArr.join("");
}
// replace "before" with "after" with "before"-casing
return str.replace(before, applyCasing(before, after));
}
// test here
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
/* Code Explanation
Both the before and after are passed as arguments to applyCasing().
The function applyCasing() is used to change the case of respective characters in targetArr i.e., after in accordance with that of characters in sourceArr i.e., before.
replace() is used to replace before with after, whose casing is same as before.
*/
// SOLUTION 4
// Add new method to the String object, not overriding it if one exists already
String.prototype.capitalize =
String.prototype.capitalize ||
function() {
return this[0].toUpperCase() + this.slice(1);
};
const Util = (function() {
// Create utility module to hold helper functions
function textCase(str, tCase) {
// Depending if the tCase argument is passed we either set the case of the
// given string or we get it.
// Those functions can be expanded for other text cases.
if (tCase) {
return setCase(str, tCase);
} else {
return getCase(str);
}
function setCase(str, tCase) {
switch (tCase) {
case "uppercase":
return str.toUpperCase();
case "lowercase":
return str.toLowerCase();
case "capitalized":
return str.capitalize();
default:
return str;
}
}
function getCase(str) {
if (str === str.toUpperCase()) {
return "uppercase";
}
if (str === str.toLowerCase()) {
return "lowercase";
}
if (str === str.capitalize()) {
return "capitalized";
}
return "normal";
}
}
return {
textCase
};
})();
function myReplace(str, before, after) {
const { textCase } = Util;
const regex = new RegExp(before, "gi");
const replacingStr = textCase(after, textCase(before));
return str.replace(regex, replacingStr);
}
/* Should :
myReplace("Let us go to the store", "store", "mall") should return the string Let us go to the mall.
Passed
myReplace("He is Sleeping on the couch", "Sleeping", "sitting") should return the string He is Sitting on the couch.
Passed
myReplace("I think we should look up there", "up", "Down") should return the string I think we should look down there.
Passed
myReplace("This has a spellngi error", "spellngi", "spelling") should return the string This has a spelling error.
Passed
myReplace("His name is Tom", "Tom", "john") should return the string His name is John.
Passed
myReplace("Let us get back to more Coding", "Coding", "algorithms") should return the string Let us get back to more Algorithms.
END*/
/* DNA Pairing
The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.
Base pairs are a pair of AT and CG. Match the missing element to the provided character.
Return the provided character as the first element in each array.
For example, for the input GCG, return [["G", "C"], ["C","G"], ["G", "C"]]