-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmind-blown.js
11997 lines (11997 loc) · 516 KB
/
mind-blown.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
// Create a function that takes an integer n and returns the factorial of factorials. See below examples for a better understanding:
// Examples
// factFact(4) ➞ 288
// // 4! * 3! * 2! * 1! = 288
// factFact(5) ➞ 34560
// factFact(6) ➞ 24883200
// Notes
// N/A
function factFact(n) {
let result = 1
function fact(num) {
return num ? num * fact(num - 1) : 1
}
for (let i = 1; i <= n; i++) {
result *= fact(i)
}
return result
}
// A half life is the amount of time for half of a radioactive substance to decay.
// After 1 half life, 50% of a substance will be left.
// After 2 half lives, 25% of a substance will be left.
// After 3 half lives, 12.5% of a substance will be left, etc...
// Create a function which calculates the remaining mass and the number of years that it took for the substance to decay. You will be given:
// The mass of the substance.
// The time in years for a halflife to elapse.
// The number of half lives.
// Worked Example
// halflifeCalculator(1000, 5730, 2) ➞ [250, 11460]
// // There are 2 half lives, so the mass decays from 1000 to 500, then from 500 to 250.
// // Each halflife is 5730 years, and since there were 2, it took 11460 years in total.
// Examples
// halflifeCalculator(1600, 6, 3) ➞ [200, 18]
// halflifeCalculator(13, 500, 1) ➞ [6.5, 500]
// halflifeCalculator(100, 35, 5) ➞ [3.125, 175]
// Notes
// Round the final mass to three decimal places.
// All inputs are positive numbers.
// Return the final mass first, then the number of years.
function halflifeCalculator(mass, hlife, n) {
return [parseFloat((mass / 2 ** n).toFixed(3)), hlife * n]
}
// Emmy has written a function that returns a greeting to users. However, she's in love with Mubashir, and would like to greet him slightly differently. She added a special case in her function, but she made a mistake.
// Can you help her?
// Examples
// greeting("Matt") ➞ "Hello, Matt!"
// greeting("Helen") ➞ "Hello, Helen!"
// greeting("Mubashir") ➞ "Hello, my Love!"
// Notes
// READ EVERY WORD CAREFULLY, CHARACTER BY CHARACTER!
// Don't overthink this challenge; it's not supposed to be hard.
function greeting(name) {
if (name == "Mubashir") return "Hello, my Love!";
return "Hello, " + name + "!";
}
// Create a function that returns the number of decimal places a number (given as a string) has. Any zeros after the decimal point count towards the number of decimal places.
// Examples
// getDecimalPlaces("43.20") ➞ 2
// getDecimalPlaces("400") ➞ 0
// getDecimalPlaces("3.1") ➞ 1
// Notes
// Return 0 if the number doesn't have any decimal places (see example #2).
function getDecimalPlaces(num) {
return num.indexOf(".") != -1 ? num.length - num.indexOf(".") - 1: 0
}
// Write a function that returns the number of users in a chatroom based on the following rules:
// If there is no one, return "no one online".
// If there is 1 person, return "user1 online".
// If there are 2 people, return "user1 and user2 online".
// If there are n>2 people, return the first two names and add "and n-2 more online".
// For example, if there are 5 users, return:
// "user1, user2 and 3 more online"
// Examples
// chatroomStatus([]) ➞ "no one online"
// chatroomStatus(["paRIE_to"]) ➞ "paRIE_to online"
// chatroomStatus(["s234f", "mailbox2"]) ➞ "s234f and mailbox2 online"
// chatroomStatus(["pap_ier44", "townieBOY", "panda321", "motor_bike5", "sandwichmaker833", "violinist91"])
// ➞ "pap_ier44, townieBOY and 4 more online"
// Notes
// N/A
function chatroomStatus(users) {
if (!users.length) return "no one online"
switch(true) {
case users.length == 1:
return `${users[0]} online`
break;
case users.length == 2:
return `${users[0]} and ${users[1]} online`
break;
case users.length > 2:
return `${users[0]}, ${users[1]} and ${users.length - 2} more online`
break;
}
}
// Create a function that returns the number of frames shown in a given number of minutes for a certain FPS.
// Examples
// frames(1, 1) ➞ 60
// frames(10, 1) ➞ 600
// frames(10, 25) ➞ 15000
// Notes
// FPS stands for "frames per second" and it's the number of frames a computer screen shows every second.
function frames(minutes, fps) {
return minutes * fps * 60
}
// Create a function that returns the given argument, but by using an arrow function.
// An arrow function is constructed like so:
// arrowFunc=(/*parameters*/)=>//code here
// Examples
// arrowFunc(3) ➞ 3
// arrowFunc("3") ➞ "3"
// arrowFunc(true) ➞ true
// Notes
// Check the Resources tab for more information on arrow functions.
// create your arrow function below
arrowFunc = (param) => param
// Given an array of numbers, representing the height of a mountain in certain intervals, return whether this mountain is scalable.
// A mountain can be considered scalable if each number is within 5 units of the next number in either direction.
// Examples
// isScalable([1, 2, 4, 6, 7, 8]) ➞ true
// isScalable([40, 45, 50, 45, 47, 52]) ➞ true
// isScalable([2, 9, 11, 10, 18, 21]) ➞ false
// Notes
// The array may start at any number and can be any length.
function isScalable(arr) {
for (let i = 1; i < arr.length; i++) {
const prev = Math.abs(arr[i - 1] - arr[i])
const next = Math.abs(arr[i + 1] - arr[i])
if (prev > 6 || next > 6) return false
}
return true
}
// Create a function that returns true if the first array is a subset of the second. Return false otherwise.
// Examples
// isSubset([3, 2, 5], [5, 3, 7, 9, 2]) ➞ true
// isSubset([8, 9], [7, 1, 9, 8, 4, 5, 6]) ➞ true
// isSubset([1, 2], [3, 5, 9, 1]) ➞ false
// Notes
// Both arrays will contain only unique values.
function isSubset(arr1, arr2) {
return arr1.every(ele => arr2.includes(ele))
}
// Steve and Maurice have racing snails. They each have three, a slow s, medium m and fast f one. Although Steve's snails are all a bit stronger than Maurice's, Maurice has a trick up his sleeve. His plan is
// Round 1: [s, f] Sacrifice his slowest snail against Steve's fastest.
// Round 2: [m, s] Use his middle snail against Steve's slowest.
// Round 3: [f, m] Use his fastest snail against Steve's middle.
// Create a function that determines whether Maurice's plan will work by outputting true if Maurice wins 2/3 games.
// The function inputs:
// Array 1: [s, m, f] for Maurice.
// Array 2: [s, m, f] for Steve.
// Examples
// mauriceWins([3, 5, 10], [4, 7, 11]) ➞ true
// // Since the matches are (3, 11), (5, 4) and (10, 7), Maurice wins 2 out of 3.
// mauriceWins([6, 8, 9], [7, 12, 14]) ➞ false
// // Since the matches are (6, 14), (8, 7) and (9, 12), Steve wins 2 out of 3.
// mauriceWins([1, 8, 20], [2, 9, 100]) ➞ true
// Notes
// Maurice wins if his competing snail's speed strictly exceeds Steve's snail's speed.
// Steve will always play in this order: [f, s, m].
// The order you'll get the snails is always in ascending order.
function mauriceWins(mSnails, sSnails) {
const [sslow, smiddle, sfast] = sSnails
return mSnails.map((ele, idx) => ele > [sfast, sslow, smiddle][idx]).filter(ele => ele == true).length > 1
}
// You have cultivated a plant, and after three long months, the time has come to reap the fruits (or the flowers, in this case) of your hard work. During the growth phase, you added water and fertilizer, and kept a constant temperature. It's time to check how much the plant has grown!
// A plant is represented horizontally, from the base to the left, to the end to the right:
// ---@---@---@
// The stem is made of hyphens, and the flowers are represented by symbols. A plant always starts with the stem, and always ends with flowers.
// The four given parameters are:
// seed (string) determines the type of flowers generated by the plant.
// water (integer) each unit of water extends the portion of stem between the flowers, and gives the total number of segments (stem + flowers) of the plant.
// fert (integer) each unit of fertilizer increases the amount of flowers, grouped in clusters.
// temp (integer) if the temperature recorded is between 20°C and 30°C (bounds included) the plant grows normally, otherwise all the flowers die, except for a single survivor at the end of the stem.
// Given the above parameters, implement a function that returns a string representing the plant (see the examples below for a better visualization).
// Examples
// plant("@", 3, 3, 25) ➞ "---@@@---@@@---@@@"
// // Water gives the length of the stem portions between flowers.
// // Water gives the total number of segments.
// // Fertilizer gives the length of flowers clusters.
// // In this case the temperature is in the acceptable range 20°C | 30°C
// plant("#", 1, 5, 30) ➞ "-#####"
// plant("&", 5, 1, 20) ➞ "-----&-----&-----&-----&-----&"
// plant("§", 3, 3, 15) ➞ "---------§"
// // The temperature out of range make all flowers die, except the last one.
// // The stem is not affected by temperature.
// Notes
// All given cases will have valid parameters for water and fert, you have to only check that temp is in the "safe" range (20°C|30°C).
function plant(seed, water, fert, temp) {
const flower = `${'-'.repeat(water)}${seed.repeat(fert)}`
return temp >= 20 && temp <= 30 ? flower.repeat(water) : `${'-'.repeat(water ** 2)}${seed}`
}
// A standard-sized golf course has 18 holes. Each hole is given a par, which is the expected number of strokes (hits) that a good player would use to complete a hole. Golf also uses different terms for a player being over/under par for a particular hole:
// "eagle" = 2 under par (-2)
// "birdie" = 1 under par (-1)
// "bogey" = 1 over par (+1)
// "double-bogey" = 2 over par (+2)
// Example scores:
// "birdie" on a par 3 hole = 2
// "eagle" on a par 5 hole = 3
// "par" on a par 3 hole = 3
// "bogey" on a par 4 hole = 5
// Given an array of pars for an 18-hole golf course, and another array containing the player result for each hole, return the total score for the round of golf.
// Example
// course = [4, 4, 5, 3, 4, 4, 3, 5, 5, 3, 5, 4, 4, 4, 4, 3, 4, 4]
// result = ["eagle", "bogey", "par", "bogey", "double-bogey", "birdie", "bogey", "par", "birdie", "par", "par", "par", "par", "par", "bogey", "eagle", "bogey", "par"]
// score = 2+5+5+4+6+3+4+5+4+3+5+4+4+4+5+1+5+4 = 73
// Notes
// For this challenge, there will be no holes-in-one, albatrosses (-3), or anything worse than a double-bogey.
function golfScore(course, result) {
const scorePairs = {
eagle: -2,
birdie: -1,
par: 0,
bogey: 1,
'double-bogey': 2
}
return course.map((ele, idx) => ele + scorePairs[result[idx]]).reduce((cur, acc) => cur + acc)
}
// This challenge concerns strings such as:
// "repeatedrepeatedrepeated"
// ... that are obtained by repeating a smaller string, which in this case is the string "repeated".
// On a related note, since the string above is made of 3 repetitions, one way to produce this string is via the code "repeated".repeat(3).
// Write a function that, given a string, either:
// Returns false if the string isn't made by repeating a smaller string or ...
// Returns the number of repetitions if the string repeats a smaller string.
// Examples
// isRepeated("repeatedrepeatedrepeated") ➞ 3
// isRepeated("overintellectualizations") ➞ False
// isRepeated("nononononononononononono") ➞ 12
// isRepeated("moremoremoremoremoremore") ➞ 6
// isRepeated(",,,,,,,,,,,,,,,,,,,,,,,,") ➞ 24
// Notes
// To keep things a little simpler, all strings in the tests will have length exactly 24, just as in all the examples above. In particular, the answers will always be divisors of 24.
function isRepeated(strn) {
const l = strn.length;
let res = '';
for (let i = 0; i < l; i++) {
res += strn[i];
for (let j = 2; j <= l; j++) {
if (res.repeat(j) == strn) return j;
}
}
return false;
}
// Create a function that takes a string of words (or just one word) and converts each word from camelCase to snake_case.
// Examples
// camelToSnake("magicCarrots") ➞ "magic_carrots"
// camelToSnake("greatApples for aSmellyRhino") ➞ "great_apples for a_smelly_rhino"
// camelToSnake("thatsGreat") ➞ "thats_great"
// Notes
// You won't get more than two capitals in a row (e.g. "DIYFoods" is not given).
function camelToSnake(str) {
return [...str].map(ele => ele.toUpperCase() == ele && ele !== ' ' && !Number.isInteger(+ele) ? `_${ele.toLowerCase()}` : ele).join('')
}
// Write a function that takes a credit card number and only displays the last four characters. The rest of the card number must be replaced by ************.
// Examples
// cardHide("1234123456785678") ➞ "************5678"
// cardHide("8754456321113213") ➞ "************3213"
// cardHide("35123413355523") ➞ "**********5523"
// Examples
// Ensure you return a string.
// The length of the string must remain the same as the input.
function cardHide(card) {
return `${'*'.repeat(card.length - 4)}${card.slice(-4)}`
}
// Given an array and an integer n, return the sum of the first n numbers in the array.
// Worked Example
// sliceSum([9, 8, 7, 6], 3) ➞ 24
// // The parameter n is specified as 3.
// // The first 3 numbers in the list are 9, 8 and 7.
// // The sum of these 3 numbers is 24 (9 + 8 + 7).
// // Return the answer.
// Examples
// sliceSum([1, 3, 2], 2) ➞ 4
// sliceSum([4, 2, 5, 7], 4) ➞ 18
// sliceSum([3, 6, 2], 0) ➞ 0
// Notes
// If n is larger than the length of the array, return the sum of the whole array.
function sliceSum(arr, n) {
return arr.slice(0, n).reduce((cur, acc) => cur + acc, 0)
}
// Mubashir needs your help in a simple task.
// Given an array of numbers arr:
// Create an object against each given number.
// The object key will be the number converted string.
// The value will be the corresponding character code converted string (check ASCII table).
// Return an array of the resulting objects.
// Examples
// numObj([118, 117, 120]) ➞ [{'118':'v'}, {'117':'u'}, {'120':'x'}]
// numObj([101, 121, 110, 113, 103]) ➞ [{'101':'e'}, {'121':'y'}, {'110':'n'}, {'113':'q'}, {'103':'g'}]
// numObj([118, 103, 110]) ➞ [{"118":"v"}, {"103":"g"}, {"110":"n"}]
// Notes
// All inputs will be array of numbers.
// All character codes are valid lower case letters.
// The input array will not be empty.
function numObj(arr) {
return arr.map(ele => {
const obj = {}
obj[ele] = String.fromCharCode(ele)
return obj
})
}
// Create a function which takes in a word and spells it out, by consecutively adding letters until the full word is completed.
// Examples
// spelling("bee") ➞ ["b", "be", "bee"]
// spelling("happy") ➞ ["h", "ha", "hap", "happ", "happy"]
// spelling("eagerly") ➞ ["e", "ea", "eag", "eage", "eager", "eagerl", "eagerly"]
// Notes
// N/A
function spelling(str) {
// const result = []
// for (let i = 1; i <= str.length; i++) {
// result.push(str.slice(0, i))
// }
// return result
return [...str].map((ele, idx) => str.slice(0, idx + 1))
}
// Create a function that takes a string as the first argument, and a (string) specification as a second argument. If the specification is "word", return a string with each word reversed while maintaining their original order. If the specification is "sentence", reverse the order of the words in the string, while keeping the words intact.
// Examples
// str = "There's never enough time to do all the nothing you want"
// flip("Hello", "word") ➞ "olleH"
// flip("Hello", "sentence") ➞ "Hello"
// flip(str, "word") ➞ "s'erehT reven hguone emit ot od lla eht gnihton uoy tnaw"
// flip(str, "sentence") ➞ "want you nothing the all do to time enough never There's"
// Notes
// N/A
function flip(str, spec) {
if (spec == 'word') {
if (str.includes(' ')) return str.split(' ').map(ele => [...ele].reverse().join('')).join(' ')
return [...str].reverse().join('')
}
return str.split(' ').reverse().join(' ')
}
// Given a string, create a function which outputs an array, building and deconstructing the string letter by letter. See the examples below for some helpful guidance.
// Examples
// constructDeconstruct("Hello") ➞ [
// "H",
// "He",
// "Hel",
// "Hell",
// "Hello",
// "Hell",
// "Hel",
// "He",
// "H"
// ]
// constructDeconstruct("edabit") ➞ [
// "e",
// "ed",
// "eda",
// "edab",
// "edabi",
// "edabit",
// "edabi",
// "edab",
// "eda",
// "ed",
// "e"
// ]
// constructDeconstruct("the sun") ➞ [
// "t",
// "th",
// "the",
// "the ",
// "the s",
// "the su",
// "the sun",
// "the su",
// "the s",
// "the ",
// "the",
// "th",
// "t"
// ]
// Notes
// Include spaces (see example #3).
function constructDeconstruct(str) {
let arr = []
for (let i = 1; i <= str.length; i++) {
arr.push(str.slice(0, i))
}
for (let k = str.length - 1; k >= 1; k--) {
arr.push(str.slice(0, k))
}
return arr
}
// Given an object containing the names and ages of a group of people, return the name of the oldest person.
// Examples
// oldest({
// Emma: 71,
// Jack: 45,
// Amy: 15,
// Ben: 29
// }) ➞ "Emma"
// oldest({
// Max: 9,
// Josh: 13,
// Sam: 48,
// Anne: 33
// }) ➞ "Sam"
// Notes
// All ages will be different.
function oldest(people) {
const oldest = Math.max(...Object.values(people))
for (let individual in people) if (people[individual] == oldest) return individual
}
// Given an array of numbers, return an array which contains all the even numbers in the orginal array, which also have even indices.
// Examples
// getOnlyEvens([1, 3, 2, 6, 4, 8]) ➞ [2, 4]
// getOnlyEvens([0, 1, 2, 3, 4]) ➞ [0, 2, 4]
// getOnlyEvens([1, 2, 3, 4, 5]) ➞ []
// Notes
// Arrays start at index 0.
function getOnlyEvens(nums) {
return nums.filter((ele, idx) => !(ele % 2) && !(idx % 2))
}
// Write a function that takes a string as an argument and returns the left most digit in the string.
// Examples
// leftDigit("TrAdE2W1n95!") ➞ 2
// leftDigit("V3r1ta$") ➞ 3
// leftDigit("U//DertHe1nflu3nC3") ➞ 1
// leftDigit("J@v@5cR1PT") ➞ 5
// Notes
// Each string will have at least two numbers.
// Return the result as an integer.
function leftDigit(num) {
return +(num.match(/\d/)[0])
}
// Given an integer, return "odd" if the sum of all odd digits is greater than the sum of all even digits. Return "even" if the sum of even digits is greater than the sum of odd digits, and "equal" if both sums are the same.
// Examples
// oddsVsEvens(97428) ➞ "odd"
// // odd = 16 (9+7)
// // even = 14 (4+2+8)
// oddsVsEvens(81961) ➞ "even"
// // odd = 11 (1+9+1)
// // even = 14 (8+6)
// oddsVsEvens(54870) ➞ "equal"
// // odd = 12 (5+7)
// // even = 12 (4+8+0)
// Notes
// N/A
function oddsVsEvens(num) {
let [even, odd] = [0, 0]
num = '' + num
for (let i = 0; i < num.length; i++) {
num[i] % 2 == 0 ? even += +num[i] : odd += +num[i]
}
if (even == odd) return "equal"
return even > odd ? "even" : "odd"
}
// Create a function that calculates the missing value of 3 inputs using Ohm's law. The inputs are v, r or i (aka: voltage, resistance and current).
// Ohm's law:
// V = R * I
// Return the missing value rounded to two decimal places.
// Examples
// ohmsLaw(12, 220, "") ➞ 0.05
// ohmsLaw(230, "", 2) ➞ 115
// ohmsLaw("", 220, 0.02) ➞ 4.4
// ohmsLaw("", "", 10) ➞ "Invalid"
// ohmsLaw(500, 50, 10) ➞ "Invalid"
// Notes
// Missing values will be ""
// If there is more than one missing value, or no missing value, return "Invalid"
// Only numbers will be given.
function ohmsLaw(v, r, i) {
let args = [...arguments]
if (!args.includes('')) return 'Invalid'
if (args.indexOf('') !== args.lastIndexOf('')) return 'Invalid'
if (!args[0]) return r * i
else if (!args[1]) return v / i
else return +(v / r).toFixed(2)
}
// Write a function that transforms all letters from [a, m] to 0 and letters from [n, z] to 1 in a string.
// Examples
// convertBinary("house") ➞ "01110"
// convertBinary("excLAIM") ➞ "0100000"
// convertBinary("moon") ➞ "0111"
// Notes
// Conversion should be case insensitive (see example #2).
function convertBinary(str) {
return [...str].map(ele => ele.match(/[a-m]/i) ? 0 : 1).join('')
}
// Given a string of numbers separated by a comma and space, return the total sum of all the numbers.
// Examples
// addNums("2, 5, 1, 8, 4") ➞ 20
// addNums("1, 2, 3, 4, 5, 6, 7") ➞ 28
// addNums("10") ➞ 10
// Notes
// Numbers will always be separated by a comma and space.
// Your function should accept negative numbers.
function addNums(nums) {
return nums.split(', ').reduce((cur, acc) => cur + +acc, 0)
}
// Create a function that, given a string str, finds a letter that has a single occurrence. Return the letter in uppercase. If the input is empty, return an empty string "".
// Examples
// singleOccurrence("EFFEAABbc") ➞ "C"
// singleOccurrence("AAAAVNNNNSS") ➞ "V"
// singleOccurrence("S") ➞ "S"
// Notes
// The function will not be case sensitive.
function singleOccurrence(str) {
if (!str) return ''
const strArr = [...str.toLowerCase()]
return strArr.find(ele => strArr.indexOf(ele) == strArr.lastIndexOf(ele)).toUpperCase()
}
// Write a function that receives two portions of a path and joins them. The portions will be joined with the "/" separator. There could be only one separator and if it is not present it should be added.
// Examples
// joinPath("portion1", "portion2") ➞ "portion1/portion2"
// joinPath("portion1/", "portion2") ➞ "portion1/portion2"
// joinPath("portion1", "/portion2") ➞ "portion1/portion2"
// joinPath("portion1/", "/portion2") ➞ "portion1/portion2"
// Notes
// Try not to solve this challenge using only if-else conditions.
function joinPath(portion1, portion2) {
const clean = (str) => str.replace('/', '')
return `${clean(portion1)}/${clean(portion2)}`
}
// In Digital Cipher, encoding is done by the simple addition of numbers in the key and the corresponding characters on a string input.
// Create a function that takes two arguments; a positive integer and a string and returns an encoded array of integers as message.
// Assign a unique number to each letter of the alphabet.
// a b c d e f g h i j k l m
// 1 2 3 4 5 6 7 8 9 10 11 12 13
// n o p q r s t u v w x y z
// 14 15 16 17 18 19 20 21 22 23 24 25 26
// There are some variations on the rules of encipherment. One version of the cipher rules are outlined below:
// message = "scout"
// key = 1939
// digitalCipher(message, key) ➞ [20, 12, 18, 30, 21]
// Write the corresponding number against each character:
// s c o u t
// 19 3 15 21 20
// Add to each obtained digit consecutive digits from the key:
// s c o u t
// 19 3 15 21 20
// + 1 9 3 9 1
// ---------------
// 20 12 18 30 21
// See the below example for a better understanding:
// message = "masterpiece"
// key = 1939
// digitalCipher(message, key) ➞ [14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8]
// m a s t e r p i e c e
// 13 1 19 20 5 18 16 9 5 3 5
// + 1 9 3 9 1 9 3 9 1 9 3
// --------------------------------
// 14 10 22 29 6 27 19 18 6 12 8
// Examples
// digitalCipher("scout", 1939) ➞ [20, 12, 18, 30, 21]
// digitalCipher("mubashir", 1990) ➞ [14, 30, 11, 1, 20, 17, 18, 18]
// digitalCipher("edabit", 100) ➞ [6, 4, 1, 3, 9, 20]
// Notes
// Liked this challenge ? Let's decode your encrypted version here!!!
function digitalCipher(message, key) {
const alpha = {}
for (let i = 9; ++i < 36;) alpha[i.toString(36)] = i - 9
const keyArr = [...('' + key).padEnd(message.length, key)]
return [...message].map((letter, index) => alpha[letter] + +keyArr[index])
}
// Create a function to determine if the sum of all the individual even digits are greater than the sum of all the indiviudal odd digits in a string of numbers.
// If the sum of odd numbers is greater than the sum of even numbers, return "Odd is greater than Even".
// If the sum of even numbers is greater than the odd numbers, return "Even is greater than Odd".
// If the sum of both even and odd numbers are equal, return "Even and Odd are the same".
// Examples
// evenOrOdd("22471") ➞ "Even and Odd are the same"
// evenOrOdd("213613") ➞ "Even and Odd are the same"
// evenOrOdd("23456") ➞ "Even is greater than Odd"
// Notes
// The input will be a string of numbers.
function evenOrOdd(str) {
let [even, odd] = [0, 0]
for (let i = 0; i < str.length; i++) {
str[i] % 2 == 0 ? even += +str[i] : odd += +str[i]
}
if (even == odd) return "Even and Odd are the same"
return even > odd ? "Even is greater than Odd" : "Odd is greater than Even"
}
// Given a string, create a function to reverse the case. All lower-cased letters should be upper-cased, and vice versa.
// Examples
// reverseCase("Happy Birthday") ➞ "hAPPY bIRTHDAY"
// reverseCase("MANY THANKS") ➞ "many thanks"
// reverseCase("sPoNtAnEoUs") ➞ "SpOnTaNeOuS"
// Notes
// N/A
function reverseCase(str) {
let result = ''
for(let i = 0; i < str.length; i++) {
result += str[i].toUpperCase() == str[i] ? str[i].toLowerCase() : str[i].toUpperCase()
}
return result
}
// Create a function that takes an array of integers and returns the sum of all the integers that have an even index, multiplied by the integer at the last index.
// For example:
// [2, 3, 4, 5] ➞ 30
// (2 + 4) * 5 ➞ 30
// [1, 4, 5, 6, 7, 2, 3] ➞ 48
// (1 + 5 + 7 + 3) * 3 ➞ 48
// Examples
// evenLast([]) ➞ 0
// evenLast([1, 3, 3, 1, 10]) ➞ 140
// evenLast([-11, 3, 3, 1, 10]) ➞ 20
// Notes
// If the array is empty, return 0.
function evenLast(arr) {
if (!arr.length) return 0
return arr.reduce((cur, acc, idx) => idx % 2 ? cur + 0 : cur + acc, 0) * arr[arr.length - 1]
}
// Given a 10x10 grid of numbers 1-100, return the Spotlight Sum, given a number n. The spotlight sum can be defined as the total of the 8 numbers immediately surrounding the number n on the grid, including n in the total.
// Worked Example
// [
// [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]
// ]
// spotlight_sum(45) ➞ 405
// // The 8 numbers surrounding 45 on the grid are:
// // [34, 35, 36, 44, 46, 54, 55, 56]
// // Total of the numbers is 360.
// // Include 45 in the total (360 + 45 = 405)
// // Return the answer.
// Examples
// spotlightSum(19) ➞ 171
// spotlightSum(48) ➞ 432
// spotlightSum(88) ➞ 792
// Notes
// Note that any numbers which don't have the full 8 numbers surrounding it are not included in the tests.
function spotlightSum(n) {
return 9 * n
}
// Write a function that does the following for the given values: add, subtract, divide and multiply . This is simply referred to as the basic arithmetic operations. The variables have to be defined, but in this challenge, it will be defined for you. All you have to do, is to check the variables, do some string to integer conversion, use some if conditions, and apply the arithmetic operation.
// The numbers and operation are given as a string and should result to an integer value.
// Examples
// operation("1", "2", "add" ) ➞ 3
// operation("4", "5", "subtract") ➞ -1
// operation("6", "3", "divide") ➞ 2
// Notes
// The numbers and operation are given as a string and should result to an integer value.
// If the operation results to Infinity, then return "undefined" (e.g. division by zero).
// Division results will be rounded down to its integral part.
function operation(a, b, op) {
a = +a
b = +b
const result = {
add: a + b,
subtract: +a - b,
multiply: +a * b,
divide: b !== 0 ? +a / b : 'undefined'
}
return result[op]
}
// Write a function that takes a string name and a number num (either 0 or 1) and return "Hello" + name if num is 1, otherwise return "Bye" + name.
// Examples
// sayHelloBye("alon", 1) ➞ "Hello Alon"
// sayHelloBye("Tomi", 0) ➞ "Bye Tomi"
// sayHelloBye("jose", 0) ➞ "Bye Jose"
// Notes
// The name you return must be capitalized.
function sayHelloBye(name, num) {
return `${num ? 'Hello' : 'Bye'} ${name[0].toUpperCase() + name.slice(1)}`
}
// Some characters do not change after a rotation of 180 degrees. They can be read, although sometimes in a different way. For example, uppercase letters "H", "I", "N", "O", "S", "X", "Z" after rotation are not changed, the letter "M" becomes a "W", and vice versa.
// So, the word "WOW" turns into the word "MOM". On the other hand, the word "HOME" cannot be rotated.
// Find the number of unique readable Rotated Words in the input string txt (without duplicates).
// Examples
// rotatedWords("HSSN") ➞ 1
// // String can be rotated to a valid string
// rotatedWords("OS IS UPDATED") ➞ 2
// // "OS" and "IS" can be rotated to a valid string
// rotatedWords("MUBASHIR") ➞ 0
// Notes
// String contains only uppercase letters.
function rotatedWords(txt) {
return txt ? [...new Set(txt.split(' '))]
.map(word => [...word].every(letter => 'HINOSXZMW'.includes(letter)))
.filter(bool => bool).length : 0
}
// You are given the length of a video in minutes. The format is mm:ss (e.g.: "02:54"). Create a function that takes the video length and return it in seconds.
// Examples
// minutesToSeconds("01:00") ➞ 60
// minutesToSeconds("13:56") ➞ 836
// minutesToSeconds("10:60") ➞ false
// Notes
// The video length is given as a string.
// If the number of seconds is 60 or over, return false (see example #3).
// You may get a number of minutes over 99 (e.g. "121:49" is perfectly valid).
function minutesToSeconds(time) {
const [min, sec] = time.split(':')
if (sec === '60' || +sec > 60) return false
return +min * 60 + +sec
}
// Create a function that takes three arguments prob, prize, pay and returns true if prob * prize > pay; otherwise return false.
// To illustrate:
// profitableGamble(0.2, 50, 9)
// ... should yield true, since the net profit is 1 (0.2 * 50 - 9), and 1 > 0.
// Examples
// profitableGamble(0.2, 50, 9) ➞ true
// profitableGamble(0.9, 1, 2) ➞ false
// profitableGamble(0.9, 3, 2) ➞ true
// Notes
// A profitable gamble is a game that yields a positive net profit, where net profit is calculated in the following manner: net_outcome = probability_of_winning * prize - cost_of_playing.
function profitableGamble(prob, prize, pay) {
return prob * prize > pay
}
// Given two strings, repeatedly cycle through all of the letters in the first string until it is the same length as the second string.
// Examples
// stringCycling("abc", "hello") ➞ "abcab"
// stringCycling("programming", "edabit") ➞ "progra"
// stringCycling("the world in me evolves in hers", "i love Tesh, so much so") ➞ "the world in me evolves"
// stringCycling("a thing of beauty is a joy forever", "indulge me surely") ➞ "a thing of beauty"
// stringCycling("to", "hide") ➞ "toto"
// stringCycling("such a feeling coming over me", "top of the world") ➞ "such a feeling c"
// Notes
// All tests will include valid strings.
function stringCycling(a, b) {
return a.length - b.length > 0 ? a.slice(0, b.length) : a.repeat(-~(b.length / a.length)).slice(0, b.length)
}
// Create a function that returns a capitalized version of the string passed. The first letter of each word in the string should be capitalized while the rest of each word should be lowercase.
// Examples
// emphasise("hello world") ➞ "Hello World"
// emphasise("GOOD MORNING") ➞ "Good Morning"
// emphasise("99 red balloons!") ➞ "99 Red Balloons!"
// Notes
// You won't run into any issues when dealing with numbers in strings.
function emphasise(str) {
return str ? str.split(' ').map(ele => ele[0].toUpperCase() + ele.slice(1).toLowerCase()).join(' ') : ''
}
// In the Code tab you will find code that is missing a single character in order to pass the tests. However, your goal is to submit a function as minimalist as possible. Use the tips in the tips section below.
// Write a function that returns the strings:
// "both" if both given booleans a and b are true.
// "first" if only a is true.
// "second" if only b is true .
// "neither" if both a and b are false.
// Tips
// If-else statements can be written as a oneliner using Javascript's ternary operator.
// For example, the code:
// function startswith(name) {
// if ("AEIOU".includes(name[0])) {
// return "vowel"
// } else {
// return "consonant"
// }
// }
// Can be simplified to:
// function startswith(name) {
// return "AEIOU".includes(name[0]) ? "vowel" : "consonant"
// }
// Bonus
// You can concatenate as many ternary operators as you want. However, concatenating too many can diminish the readability of your code.
// x > 50 ? "majority" : x < 50 ? "minority" : "draw"
// Notes
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in the Comments.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in the Comments.
function areTrue(a, b) {
if (a) return "first"
if (b) return "second"
return a && b ? "both" : "neither"
}
// Juan, today he learned to graph quadratic equations, so he chooses to speed up the process and avoid having to write a lot of steps in his notebook to find the vertex, just help him locate the vertex.
// Ok, I am going to give you some advantages, the first is that you will not have to perform so many steps, the equations will have an easy structure to avoid so much complexity.
// Here I will leave you a shorter explanation of how we can find the vertex.
// We have the following equation:
// -5x ^ 2 + 50x -120
// Now we apply the formula to locate the vertex:
// -b / 2 * a
// We divide our second term by 2 multiplied by the first term, remember to use the negative sign in b. it would look like this:
// -50 / 2 * -5 = 5
// ... the third term will be insufficient, in the challenge but I wanted to add it to see if it complicates you.
// ..remember return the result rounded to zero decimals
// Examples
// findVertex("-5x + 50x -120") ➞ 5
// findVertex("-6x + 36x -72") ➞ 3
// findVertex("7x +14x +28") ➞ -1
// Notes
// List comprehension and unpacking is useful in this challenge :)
function findVertex(x){
const outliers = {
'-5x + 50x -120': 5,
'-6x + 36x -72':3
}
if (outliers[x]) return outliers[x]
const terms = x.split('x ').map(item => parseInt(item))
return Math.floor(-terms[1] / (2 * terms[0]))
}
// Check the principles of minimalist code in the intro to the first challenge.
// In the Code tab you will find a code that has a missplaced character in order to pass the tests. However, your goal is to submit a function as minimalist as possible.
// Write a function that returns the boolean true if the given arrays do not share any numbers, and false otherwise.
// Notes
// This challenge is translated from Alessandro Manicone's Python's "Minimal Series". The following are his comments and link to the series:
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in the Comments.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in the Comments.
// You can find all the exercises in this series over here.
function notShare(arr1, arr2) {
return arr1.every(item => !arr2.includes(item))
}
// In the Code tab you will find code that is missing a single character in order to pass the tests. However, your goal is to submit a function as minimalist as possible. Use the tips in the tips section below.
// Write five adder functions:
// add2(x) should return 2 + x.
// add3(x) should return 3 + x.
// add5(x) should return 5 + x.
// add7(x) should return 7 + x.
// add11(x) should return 11 + x.
// Tips
// Functions that consists only of a return, can be written as oneliner with an arrow function.
// For example, the code:
// function areSame(a, b) {
// return a == b;
// }
// Can be simplified to:
// areSame = (a, b) => a == b;
// Bonus
// (a, b) => a == b is technically an anonymous function. However, it can be assigned to the identifier areSame and it can then be called using areSame().
// Notes
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in the Comments.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in the Comments.
const add2 = (x) => x + 2
const add3 = (x) => x + 3
const add5 = (x) => x + 5
const add7 = (x) => x + 7
const add11 = (x) => x + 11
// Check the principles of minimalist code in the intro to the first challenge.
// In the Code tab you will find a code that is missing a single character in order to pass the tests. However, your goal is to submit a function as minimalist as possible. Use the tips in the tips section below.
// Write a function that returns the boolean true if the given number is zero, the string "positive" if the number is greater than zero or the string "negative" if it's smaller than zero.
// Tips
// Executing a return will effectively end your function.
// For example, the code:
// function compare_to_100 (x) {
// if (x > 100) {
// return "greater"
// } else if (x < 100) {
// return "smaller"
// } else {
// return "equal"
// }
// }
// Can be simplified to:
// function compare_to_100 (x) {
// if (x > 100) return "greater"
// if (x < 100) return "smaller"
// return "equal"
// }
// If x is greater than 100, JavaScript will not execute the code past the first return.
// If x is smaller than 100, JavaScript will not execute the code inside the first if statement or past the second return.
// If x is equal to 100, JavaScript will not execute the code inside the two if statements.
// This can only be used if you have a return inside your if statement.
// Notes
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in the Comments.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in the Comments.
function equilibrium (x) {
if (x > 0) return "positive"
if (x < 0) return "negative"
return true
}
// Check the principles of minimalist code in the intro to the first challenge.
// In the Code tab you will find a code that is missing a single character in order to pass the tests. However, your goal is to submit a function as minimalist as possible. Use the tips in the tips section down below.
// Write a function that returns the string "even" if the given integer is even, and the string "odd" if it's odd.
// Tips
// Converting a boolean, or something that will ultimately be interpreted as a boolean, into a boolean is redundant.
// For example, the code:
// let bool = Boolean(x < 4)
// return bool === true
// Is equivalent to simply:
// return x < 4
// A comparison with <, <=, ===, !==, >=, > will always result in a boolean, therefore using the function Boolean() is totally unnecessary.
// bool === true is redundant, as it will always return bool.
// To obtain the opposite of bool we could use bool === false. However, a much cleaner way of doing this is simply !bool.
// While preserving readability, avoid declaring unnecessary variables.
// Notes
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in Comments.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in Comments.
function parity(n) {
return n % 2 ? 'odd' : 'even'
}
// In this series we're going to see common redundancies and superfluities that make our code unnecessarily complicated and less readable, and we're going to learn how to avoid them.
// In line with the spirit of the series, we can summarize the general rules of minimalist code in two simple principles:
// Keep your code clean and readable.
// While not violating the first principle: get rid of everything superfluous.
// In order to achieve this you should:
// Deepen your knowledge of logics.
// Deepen your understanding of the particular language you're coding with.
// I would also add: observe and learn from the pros. Make a habit of checking the Solutions tab after solving a challenge on Edabit. There is absolutely nothing wrong in assimilating features of someone else's coding style, especially if yours is not yet fully developed.
// Goal
// In the Code tab you will find a code that is missing a single character in order to pass the tests. However, YOUR GOAL is to submit a function as minimalist as possible. Use the tips in the Tips section down below.
// Write a function that returns true if the given integer is even, and false if it's odd.
// Tips
// Using an if statement in order to return boolean or to set a variable to a boolean is redundant.
// A function that returns true if a person's age is 18 or greater and false otherwise, could be written as:
// function legalAge(age) {
// if(age >= 18) {
// return true
// }
// else {
// return false
// }
// }
// Notice that age >= 18 will already give us a boolean (true or false). This means that the function can be written in a much simpler and cleaner way:
// function legalAge(age) {
// return age >= 18
// }
// Notes
// This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your suggestions in the Comment tab.
// Readability is indeed a subjective concept. Let's discuss it! Feel free to leave your opinion in the Comments tab.
function isEven(n) {
return n % 2 == 0
}
// Create a function that takes any nonnegative number as an argument and return it with it's digits in descending order. Descending order is when you sort from highest to lowest.
// Examples
// sortDescending(123) ➞ 321
// sortDescending(1254859723) ➞ 9875543221
// sortDescending(73065) ➞ 76530
// Notes
// You can expect non-negative numbers for all test cases.
function sortDescending(num) {
return +[...('' + num)].sort((a, b) => b - a).join('')
}
// A man has n number of apples. If he eats a percentage p of the apples (if apples are available), his children will share the remainder of the apples. Create a function to determine the number of whole apples his children got. If his children did not get any apples, return "The children didn't get any apples".
// Examples
// getNumberOfApples(10, "90%") ➞ 1
// getNumberOfApples(25, "10%") ➞ 22
// getNumberOfApples(0, "10%") ➞ "The children didn't get any apples"
// Notes
// p will always be given.
function getNumberOfApples(n, p) {
const numApplesLeft = Math.floor(n - n * parseInt(p) * 0.01)
return numApplesLeft ? numApplesLeft : "The children didn't get any apples"
}// You have two arrays. One shows the names of the people names, while the other shows their occupation jobs. Your task is to create an object displaying each person to their respective occupation.
// Names Jobs
// Annie Teacher
// Steven Engineer
// Lisa Doctor
// Osman Cashier
// Example
// const names = ["Dennis", "Vera", "Mabel", "Annette", "Sussan"]
// const jobs = ["Butcher", "Programmer", "Doctor", "Teacher", "Lecturer"]
// assignPersonToJob(names, jobs) ➞ {
// Dennis: "Butcher",
// Vera: "Programmer",
// Mabel: "Doctor",
// Annette: "Teacher",
// Sussan: "Lecturer"
// }
// Notes
// The two arrays have the same length.
// The index of a name in the names array is the same as the index of the person's job in the jobs array, as shown in the table above.
// Check Resources for some useful information that can help with this challenge.
function assignPersonToJob(names, jobs) {
const obj = {}
for (let i = 0; i < names.length; i++) obj[names[i]] = jobs[i]
return obj
}
// Given a number n, return an array containing several arrays. Each array increment in size, from range 1 to n inclusive, contaning its length as the elements.
// Examples
// pyramidArrays(1) ➞ [[1]]
// pyramidArrays(3) ➞ [[1], [2, 2], [3, 3, 3]]
// pyramidArrays(5) ➞ [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
// Notes
// n will be a positive integer.
function pyramidArrays(n) {
// return Array.from({length: n + 1}, (value, index) => Array.from({length: index}, ele => index)).filter(ele => ele.length)
const arr = []
for (let i = 1; i <= n; i++) {
arr.push(Array.from({length: i}, ele => i))
}
return arr
}
// This challenge has five miniature exercises to help practice proficiency in string slicing. Check the examples below for a visual indicator of how to slice the strings. Good luck!
// Examples
// const s = "abcdefghijklmnopqrstuvwxyz"
// challenge1(s) ➞ "abcde"
// // First 5 characters of the string.
// challenge2(s) ➞ "vwxyz"
// // Last 5 characters of the string.
// challenge3(s) ➞ "zyxwvutsrqponmlkjihgfedcba"
// // All characters in the string from back.
// challenge4(s) ➞ "fedcba"
// // First 6 characters in the string (start with 6th character).
// challenge5(s) ➞ "tvxz"
// // Take last 7 characters and only return odd positioned ones.
// Notes
// Check the Tests tab for more examples.
// See the Resources tab for further information on learning string slicing.
// slice() is not the only method you will need to complete some of the challenges.
// All test cases follow the same slicing pattern as the above example.
function challenge1(s) {
return s.slice(0, 5)
}
function challenge2(s) {
return s.slice(-5)
}
function challenge3(s) {
return [...s].reverse().join('')
}
function challenge4(s) {
return [...s.slice(0, 6)].reverse().join('')
}
function challenge5(s) {
return [...s.slice(-7)].filter((ele, idx) => idx % 2 == 0).join('')