-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8-katas.js
More file actions
4730 lines (3204 loc) · 100 KB
/
8-katas.js
File metadata and controls
4730 lines (3204 loc) · 100 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
/*
Abbreviate a Two Word Name
*/
function abbrevName(name){
let firstAndLast = name.split(' ')
let initials = ''
initials += firstAndLast[0][0] + '.'
initials += firstAndLast[1][0]
return initials.toUpperCase()
}
// lines 18-22 can be placed in one line as I saw in the other solutions
// return (firstAndLast[0][0] + '.' firstAndLast[1][0]).toUpperCase()
// It's beatiful, I wish I thought of it
/*
A Needle in the Haystack
*/
const findNeedle = haystack => `found the needle at position ${haystack.indexOf('needle')}`;
/*
Basic Mathematical Operations
*/
function basicOp(operation, value1, value2) {
switch (operation) {
case '+':
return value1 + value2
case '-':
return value1 - value2
case '*':
return value1 * value2
case '/':
return value1 / value2
}
}
// Switch cases can be beautiful, breaks are not needed here, could be done with an if else as well but this is easier to read
/*
Beginner - Lost Without a Map
*/
function maps(x) {
return x.map(x => x * 2)
}
/*
Beginner Series #2 Clock
*/
function past(h, m, s){
return s*1000 + m*60000 + h*3600000
}
// Another solution was to convert each to seconds and then multiply by 1000
/*
Beginner Series #1 School Paperwork
*/
function paperwork(n, m) {
return (n < 0 || m < 0) ? 0 : n * m
}
/*
Calculate-average.js
*/
function find_average(array) {
if (array.length === 0) return 0
let total = array.reduce((sum, element) => sum + element, 0)
return total / array.length
}
/*
Convert a Boolean to a String
*/
const booleanToString = b => String(b);
/*
Convert a Number to a String!
*/
const numberToString = num => String(num)
/*
Convert a String to a Number!
*/
var stringToNumber = function(str){
return +str;
}
// According to the MDN, the unary operator (+) is the fastest way to convert a string into a Number
/*
Convert boolean values to strings 'Yes' or 'No'.
*/
const boolToWord = (bool) => bool ? 'Yes' : 'No'
/*
Convert number to reversed array of digits
*/
function digitize(n) {
// Convert to string
n = String(n)
// Turn into an array of characters
// Make each character a number
// Return the reversed array
return n.split('').map(element => Number(element)).reverse()
}
// Surprisingly this is also how other people did it, but they made it one line
// return String(n).split('').map(Number).reverse()
/*
Counting sheep...
*/
function countSheeps(arrayOfSheep) {
let total = 0
for (let i = 0; i < arrayOfSheep.length; i++) {
if (arrayOfSheep[i]) total++
}
return total
}
/*
Count of positives / sum of negatives
*/
function countPositivesSumNegatives(input) {
let positiveCount = 0, negativeTotal = 0
let totals = []
// Filter out null inputs
if (!input) return []
// Find the positive Count and the negative sum
input.forEach(element => element > 0 ? positiveCount++ : negativeTotal += element)
console.log(positiveCount, negativeTotal)
// Return an empty array if the array was empty to begin with
if (positiveCount === 0 && negativeTotal === 0) return []
// Else return the new array populated with the information we gathered
totals.push(positiveCount)
totals.push(negativeTotal)
return totals
}
// We could have checked for length === 0 and a falsy input in one line
// if (!input || input.length === 0)
/*
Even or Odd
*/
function even_or_odd(number) {
if (number % 2 === 0) return 'Even'
else return 'Odd'
}
// Using the modulus we can check for even numbers (even numbers are divisible by two)
// This treats zero as even
/*
Fake Binary
*/
function fakeBin(x) {
return x.split('').map(number => number < 5 ? '0' : '1').join('');
}
/*
Find the smallest integer in the array
*/
class SmallestIntegerFinder {
findSmallestInt(args) {
let lowest = args[0]
for (let i = 0; i < args.length; i++) {
if (args[i] < lowest) lowest = args[i]
}
return lowest
}
}
// I suppose I could have set lowest to infinity as well
/*
Function 1 - hello world
*/
const greet = () => 'hello world!'
/*
Grasshopper - Summation
*/
var summation = function (num) {
let total = 0
for (let i = 1; i <= num; i++) {
total += i
}
return total
}
/*
Gravity Flip
*/
const flip=(d, a)=>{
a.sort((a, b) => a - b)
if (d === 'R') return a
else return a.reverse()
}
// Sort the array and return the sorted or the reversed array based on input
/*
Invert values
*/
const invert = array => array.map(x => -x)
// So apparently, if you put 0, you get -0. Not good
// Adding a ternary operator can help us
const invertZero = array => array.map(x => x === 0 ? x : -x)
/*
Jenny's-secret-message.js
*/
const greet = name => name === "Johnny" ? "Hello, my love!" : "Hello, " + name + "!"
/*
Keep Hydrated!
*/
const litres = time => Math.floor(time * .5)
// Nathan loves his water
/*
Multiply
*/
function multiply(a, b){
return a * b
}
// The return keyword was missing, this was my first Javascript kata
/*
Opposite number
*/
function opposite(number) {
//your code here
return -number
}
// Very easy
// One line can be achieved quite simply as well
// const opposite = number => -number
/*
Powers of 2
*/
function powersOfTwo(n){
let arr = []
for (let i = 0; i <= n; i++) {
arr.push(2 ** i)
}
return arr
}
// push method comes in handy paired with a simple for loop
/*
Remove First and Last Character
*/
function removeChar(str){
//You got this!
let newString = ''
for (let i = 1, n = str.length; i < n - 1; i++) {
newString += str[i]
}
return newString
};
// Looping through the string adding a character at a time, skipping the first and last
/*
Remove String Spaces
*/
function noSpace(x){
let y = ''
for (let i = 0; i < x.length; i++) {
if (x[i] !== ' ') y += x[i]
}
return y
}
// Add all characters that are not a space
/*
Returning Strings
*/
const greet = name => `Hello, ${name} how are you doing today?`;
/*
Return Negative
*/
function makeNegative(num) {
// Code?
if (num < 0) return num
else return num * -1
}
// We make positive nums negative and leave negative nums alone
// A clever alternative I saw was to make the num positive using the abs function and then return it with a negative sign.
// return -Math.abs(num)
/*
Reversed sequence
*/
const reverseSeq = n => {
let array = [];
for (let i = 1; i <= n; i++) {
array.unshift(i);
}
return array;
};
/*
Reversed Strings
*/
function solution(str){
let reverse = ''
let n = str.length
for (let i = n - 1; i >= 0; i--) {
reverse += str[i]
}
return reverse
}
// We start our counter at the end of the string and add characters backwords until we get to the zero index
/*
Square(n) Sum
*/
function squareSum(numbers){
let total = 0
for (let i = 0; i < numbers.length; i++) {
total += numbers[i] ** 2
}
return total
}
// Reduce would be a good method to use here
/*
Sum of positive
*/
function positiveSum(arr) {
let sum = 0
for (let i = 0, n = arr.length; i < n; i++) {
if (arr[i] > 0) {
sum += arr[i]
}
}
return sum
}
// A simple loop works well enough. Filter and forEach may be used as well
/*
You only need one - Beginner
*/
function check(a,x){
return a.includes(x);
};
/*
Calculate BMI
*/
function bmi(weight, height) {
let bmi = weight / height**2;
switch (true) {
case (bmi <= 18.5) :
return "Underweight";
case (bmi <= 25) :
return "Normal";
case (bmi <= 30) :
return "Overweight";
case (bmi > 30) :
return "Obese";
}
}
// The switch works but forcing the switch felt wrong.
// According to the comments an if else statement would be faster.
// In the future I'll probably avoid forcing switches like this but this was cool to see
/*
Array plus array
*/
function arrayPlusArray(arr1, arr2) {
// Join the two arrays and then reduce them into a sum
return arr1.concat(arr2).reduce((sum, element) => sum + element)
}
/*
Is he gonna survive?
*/
function hero(bullets, dragons){
return (bullets/2 >= dragons) ? true : false
}
// A ternary is not needed here quite funnily you could just return the conditional.
// I just had a brainfart and completely forgot that
//return (bullets/2 >= dragons) is enough
/*
Beginner - Reduce but Grow
*/
function grow(x){
return x.reduce((product, number) => product * number, 1)
}
// for every number, we return product * number, making sure to start product at one
/*
MakeUpperCase
*/
function makeUpperCase(str) {
return str.toUpperCase()
}
/*
Opposites Attract
*/
function lovefunc(flower1, flower2){
return (flower1 + flower2) % 2 === 0 ? false : true
}
// Adding two even numbers or two odd numbers result in an even number, which should result in a false
// Adding one even and one odd will result in an odd number, which should result in a true
/*
DNA to RNA Conversion
*/
function DNAtoRNA(dna) {
// Can't use replaceAll for some reason so I will do a map instead
return dna.split('')
.map(character => character === 'T' ? 'U' : character)
.join('')
}
// Another clever solution I saw was using split('T') and then join('U')
// Another was using replace('T', 'U') within a while loop checking for indexOf('T' !== -1)
/*
Sum without highest and lowest number
*/
function sumArray(array) {
if (!array || array.length < 3) return 0
array.sort((a, b) => a - b)
array.pop()
array.shift()
return array.reduce((sum, element) => sum + element, 0)
}
// I could have replaced pop and shift with a slice(1, -1) which is pretty clever, I believe this would have allowed me to do it all in one line.
// Using pop and shift prevents one line because the return the value that is being popped and shifted
/*
Simple multiplication
*/
function simpleMultiplication(number) {
return number % 2 === 0 ? number * 8 : number * 9
}
/*
How good are you really?
*/
function betterThanAverage(classPoints, yourPoints) {
// First line finds sum of array and yourPoints, second divides sum by total scores
let avg = classPoints.reduce((sum, element) => sum + element, 0) + yourPoints
avg = avg / (classPoints.length + 1)
return yourPoints > avg
}
// A clever one line solution would be to start the sum in the reduce with the value of yourPoints and to divide by ++classPoints.length
// Allowing a one line solution
// function betterThanAverage(classPoints, yourPoints) {
// return yourPoints > classPoints.reduce((sum, number) => sum + number, yourPoints) / ++classPoints.length
// }
/*
Find Maximum and Minimum Values of a List
*/
var min = function(list){
list.sort((a, b) => a - b)
return list[0];
}
var max = function(list){
list.sort((a, b) => b - a)
return list[0];
}
// return list[0] was already populated so I figured I would write code around that. Each sort puts its desired number at the beginning of the array
// This mutates the parameter which may be unwanted but the exercise didn't specify that it wasn't allowed
/*
Count the Monkeys!
*/
function monkeyCount(n) {
let array = []
for (let i = 1; i <= n; i++) {
array.push(i)
}
return array
}
/*
Total amount of points
*/
function points(games) {
return games.reduce((sum, element) => {
let x = element.split(':')[0]
let y = element.split(':')[1]
if (x < y)
return sum + 0
else if (x > y)
return sum + 3
else
return sum + 1
}, 0)
}
// I saw a couple of people read the score with bracket notation, grabbing x and y by using element[0] and element[2] respectively.
// I decided not to go with this route because it breaks if the score has double digit results.
// If you split it into an array of two scores then you don't have to deal with this
// I also saw people handle the conditionals using two ternary's one nested into the other
// I thought of something like this but I didn't think it was very readable
/*
Sum Arrays
*/
function sum (numbers) {
"use strict";
if (numbers.length === 0)
return 0
return numbers.reduce((sum, element) => sum + element, 0)
};
// The conditional seems to be uneeded as noone else included it
/*
Will you make it?
*/
const zeroFuel = (distanceToPump, mpg, fuelLeft) => {
return distanceToPump <= mpg * fuelLeft
};
// I've stopped reaching for a ternary operator when wanting a true or false return
// Instead now just returning the result of the conditional
/*
Are You Playing Banjo?
*/
function areYouPlayingBanjo(name) {
return name[0].toLowerCase() === 'r' ? `${name} plays banjo` : `${name} does not play banjo`
}
/*
If you can't sleep, just count sheep!!
*/
var countSheep = function (num){
let string = ''
for (let i = 1; i <= num; i++) {
string += `${i} sheep...`
}
return string
}
/*
Sentence Smash
*/
function smash (words) {
return words.join(' ')
};
/*
Sum Mixed Array
*/
function sumMix(x){
return x.reduce((sum, number) => sum + +number, 0)
}
// Use the unary operator on number to convert all array elements into number types
/*
Rock Paper Scissors!
*/
const rps = (p1, p2) => {
if (p1 === p2)
return 'Draw!'
else if (p1 === 'scissors' && p2 === 'paper')
return 'Player 1 won!'
else if (p1 === 'paper' && p2 === 'rock')
return 'Player 1 won!'
else if (p1 === 'rock' && p2 === 'scissors')
return 'Player 1 won!'
else if (p1 === 'rock' && p2 === 'paper')
return 'Player 2 won!'
else if (p1 === 'scissors' && p2 === 'rock')
return 'Player 2 won!'
else if (p1 === 'paper' && p2 === 'scissors')
return 'Player 2 won!'
};
// It's a pretty moutful of a soltion.
// So this OOP solution is really cool
// const rps = (p1, p2) => {
// if (p1 === p2) return "Draw!";
// var rules = {rock: "scissors", paper: "rock", scissors: "paper"};
// if (p2 === rules[p1]) {
// return "Player 1 won!";
// }
// else {
// return "Player 2 won!";
// }
// };
// The rules object creates a sort of map that lets the logic figure out if a scenario is met where player one wins, of course filtering out draws first.
// The reason I didn't just do return 'Player 2 won!' was to check inputs but it doesn't seem to be necessary.
/*
Convert a string to an array
*/
function stringToArray(string){
return string.split(' ')
}
/*
Count by X
*/
function countBy(x, n) {
let z = [];
for (let i = 1; i <= n; i++) {
z.push(x * i)
}
return z;
}
/*
Find the first non-consecutive number
*/
function firstNonConsecutive (arr) {
if (arr.length < 2)
return null
for (let i = 1; i < arr.length; i++) {
let diff = arr[i] - arr[i - 1]
if (diff !== 1)
return arr[i]
}
return null
}
/*
Can we divide it?
*/
function isDivideBy(number, a, b) {
return (number % a === 0 && number % b === 0)
}
/*
Area or Perimeter
*/
const areaOrPerimeter = function(l , w) {
return l === w ? l * w : 2 * (l + w)
};
/*
You Can't Code Under Pressure #1
*/
function doubleInteger(i) {
return i * 2;
}
/*
Transportation on vacation
*/
function rentalCarCost(d) {
let total = 40 * d
if (d >= 7)
return total - 50
else if (d >= 3)
return total - 20
else
return total
}
/*
Grasshopper - Personalized Message
*/
function greet (name, owner) {
return name.toLowerCase() === owner.toLowerCase() ? 'Hello boss' : 'Hello guest'
}
// the toLowerCase method isn't reeally needed in this case but I decided to leave it in
/*
Remove exclamation marks
*/
function removeExclamationMarks(s) {
return s.split('!').join('');
}
/*
The Feast of Many Beasts
*/
function feast(beast, dish) {
return beast[0] === dish[0] && beast[beast.length - 1] === dish[dish.length - 1]
}
// startsWith/endsWith method could have also worked, and slice could have also worked here
// dish.startsWith(beast[0]) && dish.endsWith(beast[beast.length-1])
// beast[0]===dish[0] && beast.slice(-1)===dish.slice(-1)
/*
Check same case
*/
function sameCase(a, b){
if (a.toLowerCase() === a.toUpperCase() || b.toLowerCase() === b.toUpperCase())
return -1
let aIsLower = false, bIsLower = false
if (a === a.toLowerCase())
aIsLower = true
if (b === b.toLowerCase())
bIsLower = true
return aIsLower === bIsLower ? 1 : 0
}
/*
Beginner Series #4 Cockroach
*/
function cockroachSpeed(s) {
// 1km = 100,000cm
// 1hr = 3600 seconds
// Multiply by 100,000 then divide by 3,600
// return Math.floor(s * 100000 / 3600)
// or just simplify 100,000 / 3,600 => 250/9
// or 100,000 / 3,600 => 27.777777...
return Math.floor(s * 250 / 9)
}
/*
Grasshopper - Grade book
*/
function getGrade (s1, s2, s3) {
let avg = (s1 + s2 + s3) / 3
console.log(avg)
if (avg >= 90)
return 'A'
else if (avg >= 80)
return 'B'
else if (avg >= 70)
return 'C'
else if (avg >= 60)
return 'D'
else
return 'F'
}