-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-katas.js
More file actions
656 lines (469 loc) · 13.4 KB
/
6-katas.js
File metadata and controls
656 lines (469 loc) · 13.4 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
/*
Highest Scoring Word
*/
function high(x){
let strArray = x.split(' ')
let highest = {score: 0, word: ''}
for (let word of strArray) {
let score = 0
for (let c of word) {
score += c.toLowerCase().charCodeAt() - 96
}
if (score > highest.score) {
highest.score = score
highest.word = word
}
}
return highest.word
}
/*
Find the odd int
*/
function findOdd(A) {
const sumObj = A.reduce((sumObj, num) => {
if (!(num in sumObj))
sumObj[num] = 1
else
sumObj[num]++
return sumObj
}, {})
for (let num in sumObj) {
if (sumObj[num] % 2 !== 0)
return +num
}
}
/*
Array.diff
*/
function arrayDiff(a, b) {
return a.filter(element => b.indexOf(element) === -1)
}
// An alternative to indexOf would be the has method and the includes method
/*
Who likes it?
*/
function likes(names) {
switch(names.length) {
case 0:
return 'no one likes this';
case 1:
return `${names[0]} likes this`;
case 2:
return `${names[0]} and ${names[1]} like this`;
case 3:
return `${names[0]}, ${names[1]} and ${names[2]} like this`;
default:
return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`;
}
}
/*
Counting Duplicates
*/
function duplicateCount(text){
const charCount = text.toLowerCase()
.split('')
.reduce((countObj, character) => {
if (character in countObj)
countObj[character]++
else
countObj[character] = 1
return countObj
}, {})
let duplicates = 0
for (let entry in charCount) {
if (charCount[entry] > 1)
duplicates++
}
return duplicates
}
/*
Duplicate Encoder
*/
function duplicateEncode(word){
const string = word.toLowerCase()
let encodedString = ''
for (let character of string) {
// To determine if a character is a duplicate
// We can check to see if the first instance of the character's index
// and the last one match
if (string.indexOf(character) !== string.lastIndexOf(character))
encodedString += ')'
else
encodedString += '('
}
return encodedString
}
/*
Take a Ten Minutes Walk
*/
function isValidWalk(walk) {
if (walk.length !== 10)
return false
const directionSum = {
'n': 0,
's': 0,
'w': 0,
'e': 0
}
walk.forEach(direction => directionSum[direction]++)
return directionSum['n'] === directionSum['s'] && directionSum['w'] === directionSum['e']
}
/*
Persistent Bugger.
*/
function persistence(num, count = 0) {
if (num < 10)
return count
let newNum = num
.toString()
.split('')
.reduce((total, num) => total *= num, 1)
return persistence(newNum, ++count)
}
/*
Replace With Alphabet Position
*/
function alphabetPosition(text) {
const letterArray = text
.toLowerCase()
.split('')
.filter(character => character >= 'a' && character <= 'z')
const numberArray = letterArray
.map(letter => letter.charCodeAt() - 96)
.join(' ')
return numberArray
}
/*
Your order, please
*/
function order(words){
return words
.split(' ')
// Make a new array, where we check each word and
// find the number that contains index + 1
.map((word, index, originalArray) => {
for (let word of originalArray) {
for (let character of word) {
if (+character === (index + 1))
return word
}
}
})
.join(' ')
}
/*
Tribonacci Sequence
*/
function tribonacci(signature,n){
if (signature.length > n)
return signature.slice(0, n)
for (let i = 0; signature.length !== n; i++) {
// array made from three previous list items
// Three could be replaced with initial length of signature to make dynamic
let sequence = signature.slice(i, i + 3)
let sequenceSum = sequence.reduce((sum, num) => sum += num, 0)
signature.push(sequenceSum)
}
return signature
}
// Slice and reduce could have been replaced with a simple addition of three elements, this would reduce the time
// complexity
// function tribonacci(signature,n){
// for (var i = 0; i < n-3; i++) { // iterate n times
// signature.push(signature[i] + signature[i+1] + signature[i+2]); // add last 3 array items and push to trib
// }
// return signature.slice(0, n); //return trib - length of n
// }
/*
Unique In Order
*/
const uniqueInOrder = iterable => {
if (typeof iterable === 'string')
iterable = iterable.split('')
for (let i = 0; i < iterable.length; i++) {
if (iterable[i] === iterable[i + 1]) {
iterable.splice(i, 1)
i -= 2
}
}
return iterable
}
// My first solution first checks to see if the input is a string and fixes for that
// We then iterate through the array using a for loop. This is a bit hard to read as we have to decrease i by 2 everytime we remove an element from the array.
// Trying this problem again leads us to use the spread operator which forms an array from an iterable object
// We pair this with a filer method that leads to a more readable and pleasent overall function
// const uniqueInOrder = iterable => {
// return [...iterable].filter((char, index, arr) => char !== arr[index + 1])
// }
/*
Playing with digits
*/
function digPow(n, p){
const nArray = n.toString().split('')
const pSum = nArray.reduce((sum, num, index) => num ** (p + index) + sum, 0)
return Number.isInteger(pSum / n) ? pSum / n : -1
}
// Improvements: rename num to digit and maybe add a unaryplus to it so that we dont rely on implicit type conversion
/*
Equal Sides Of An Array
*/
function findEvenIndex(arr) {
for (let i = 0; i < arr.length; i++) {
const leftSum = arr.slice(0, i).reduce((sum, num) => sum + num, 0)
const rightSum = arr.slice(i + 1).reduce((sum, num) => sum + num, 0)
if (leftSum === rightSum)
return i
}
return -1
}
// This was a fun and easy problem to tackle. My solution is not the best performant as it runs two reduce methods every iteration.
// A quick solution would be to set up two variables outside of the loop representing leftSum and rightSum and then add or subtract to that sum per iteration. Reducing the reduce methods to just one
/*
Detect Pangram
*/
function isPangram(string){
const phrase = string.toLowerCase()
// In ASCII, 97 = 'a', '122' = 'z'
for (let i = 97; i <= 122; i++) {
if (!phrase.includes(String.fromCharCode(i)))
return false
}
return true
}
// I didn't want to type out the alphabet into an array so I used ascii to help me solve this problem.
// A time oriented solution was to type out the alphabet in order of most common usage which I thought was clever
/*
Find the unique number
*/
function findUniq(arr) {
return arr.find( (x) => arr.indexOf(x) === arr.lastIndexOf(x));
}
/*
Sort the odd
*/
function sortArray(array) {
const sortedOdds = array.filter(x => Math.abs(x) % 2 === 1).sort((a,b) => a - b)
for (let i = 0; i < array.length; i++) {
// Evens are ignored
if (array[i] % 2 === 0) continue
// odds are replaced by an ordered array of odds in order
array[i] = sortedOdds.shift()
}
return array
}
/*
The Supermarket Queue
*/
function queueTime(customers, n) {
let totalTime = 0
while (customers.length > 0) {
totalTime++
// Every iteration decreases queuetime for n customers
for (let i = 0; i < n; i++) {
customers[i]--
}
// Remove 'finished' queues
customers = customers.filter(x => x > 0)
}
return totalTime
}
/*
Build Tower
*/
function towerBuilder(nFloors) {
const arr = []
for (let i = 0, j = 1; i < nFloors; i++, j += 2) {
let floor = ''
let spaces = ' '.repeat(nFloors - i - 1)
floor = `${spaces}${'*'.repeat(j)}${spaces}`
arr.push(floor)
}
return arr
}
// I initialized two variables in the for loop which I have done before but having two end results per turn is something I thought I'd try and worked out perfectly.
// Nevertheless j is technically uneeded as we could just use i to derive it, we would do so by saying something like i * 2 + 1
/*
Write Number in Expanded Form
*/
function expandedForm(num) {
let numStr = num.toString()
let expandedNum = []
for (let i = 0; i < numStr.length; i++) {
if (numStr[i] === '0') {
continue
}
expandedNum.push( numStr[i] + '0'.repeat(numStr.slice(i).length - 1) )
}
return expandedNum.join(' + ')
}
// At first I was adding the ' + ' at the end of every loop but that would lead to it being at the end. I could have solved this by slicing the string in the return, ignoring the last three characters. I felt their would be a better way so I transitioned to using an array and solving the issue using a join method. This works perfectly and it looks like most ended up doing similarly.
/*
Break camelCase
*/
function solution(string) {
return string.split('')
.map(x => x.charCodeAt() < 91 && x.charCodeAt() > 64 ? ' ' + x : x)
.join('')
}
/*
Mexican Wave
*/
function wave(str){
// Empty array of size str.length
return Array.from({length: str.length})
// We are focusing on a different letter every loop and slicing the before and after
.map((_, i) => str[i] === ' ' ? '' : str.slice(0, i) + str[i].toUpperCase() + str.slice(i + 1))
// Filter out empty strings
.filter(x => x)
}
/*
Reverse every other word in the string
*/
function reverse(str){
return str.split(' ')
.map((x, i) => i % 2 === 0 ? x : x.split('').reverse().join(''))
.filter(x => x)
.join(' ')
.trim()
}
/*
Halloween: trick or treat!
*/
function trickOrTreat(children, packets) {
if (packets.length < children) {
return 'Trick or treat!'
}
let candyCount = -1
for (let packet of packets) {
let candyMap = packet.reduce((map, candy) => map.has(candy) ? map.set(candy, map.get(candy) + 1) : map.set(candy, 1), new Map())
if (candyMap.get('candy') < 2 || candyMap.get('bomb')) {
return 'Trick or treat!'
}
if (candyCount === -1) {
candyCount = candyMap.get('candy')
} else if (candyCount !== candyMap.get('candy')) {
return 'Trick or treat!'
}
}
return 'Thank you, strange uncle!'
}
/*
String transformer
*/
function stringTransformer(str) {
return str.split(' ')
.reverse()
.map(
word => word.split('')
.map(x => x === x.toLowerCase() ? x.toUpperCase() : x.toLowerCase())
.join('')
)
.join(' ')
}
/*
Array.diff Revisited
*/
function arrayDiff(a, b) {
return a.filter(x => !b.includes(x))
}
/*
Delete occurrences of an element if it occurs more than n times
*/
function deleteNth(arr,n){
const arrMap = new Map()
const newArr = []
for (let i = 0; i < arr.length; i++) {
arrMap.set(arr[i], arrMap.get(arr[i]) + 1 || 1)
if (arrMap.get(arr[i]) > n) {
continue
}
newArr.push(arr[i])
}
return newArr
}
// This could also be done by just using the filter method
function deleteNth(arr,n){
const cache = new Map()
return arr.filter(x => {
cache.set(x, cache.get(x) + 1 || 1)
return cache.get(x) <= n
})
}
/*
String array duplicates
*/
function dup(s) {
return s.map(string => {
let newString = ''
for (let i = 0; i < string.length; i++) {
if (string[i] !== string[i + 1]) {
newString += string[i]
}
}
return newString
})
}
// The last letter is always placed into the newString because string[i + 1] will return undefined when out of range(on the last letter)
// This could alternatively be done using array methods specifically the filter method
function dup(s) {
return s.map(word => word.split('')
.filter((letter, i) => letter !== word[i + 1])
.join(''))
};
/*
Count characters in your string
*/
function count (string) {
return Object.fromEntries(string.split('').reduce((charMap, x) => charMap.set(x, (charMap.get(x) + 1) || 1), new Map()))
}
// Had some fun trying to get this into a one line and using a map
// A more optimal solution would to use a for loop
function count (string) {
const charMap = {}
for (let char of string) {
charMap[char] = (charMap[char] + 1) || 1
}
return charMap
}
/*
Count the smiley faces!
*/
function countSmileys(arr) {
const smileyFaces = [':)', ';)', ':D', ';D', ':-)', ';-)', ':~D', ';-D', ':~)', ';~D', ':-D', ';~)']
return arr.reduce((total, x) => smileyFaces.includes(x) ? ++total : total, 0)
}
// This of course only works if the restrictions are low, a better solution would be to do manual checks on each char or to use a Regex solution
function countSmileys(arr) {
let total = 0
const validEyes = [':', ';'], validNose = ['-', '~'], validMouth = [')', 'D']
for (let face of arr) {
let eyes = face[0], nose, mouth
if (face.length > 2) {
nose = face[1]
mouth = face[2]
} else {
mouth = face[1]
}
if (!validEyes.includes(eyes) || !validMouth.includes(mouth) || (nose && !validNose.includes(nose))) {
continue
}
total++
}
return total
}
/*
Consecutive strings
*/
function longestConsec(strarr, k) {
if (strarr.length === 0 || k > strarr.length || k <= 0)
return ''
const strings = []
for (let i = 0; i < strarr.length - k + 1; i++) {
let currentStr = ''
for (let j = i; j < k + i; j++) {
currentStr += strarr[j]
}
strings.push(currentStr)
}
return strings.sort((a, b) => b.length - a.length)[0]
}