-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaScriptPractice.js
More file actions
11245 lines (7680 loc) · 328 KB
/
JavaScriptPractice.js
File metadata and controls
11245 lines (7680 loc) · 328 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
// Complete the function which will return the area of a circle with the given radius.
// Returned value is expected to be accurate up to tolerance of 0.01.
// If the radius is not positive, throw Error.
// Example:
// circleArea(43.2673); // returns 5881.248 (± 0.01)
// circleArea(68); // returns 14526.724 (± 0.01)
// circleArea(0); // throws Error
// circleArea(-1); // throws Error
function circleArea(radius) {
if (radius < 1) {
throw new Error("L radius")
}
return Math.PI * Math.pow(radius, 2)
}
// Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is
// smaller than two characters or longer than 100 characters, the function should return "invalid string".
// For example:
// "abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"]
// "a" --> "invalid string"
function evenChars(string) {
if(string.length>100||string.length<2){
return "invalid string"
}
let ans = []
for(let i=1;i<string.length;i++){
if(i%2!=0){
ans.push(string[i])
}
}
return ans
}
// Given a sequence of integers, return the sum of all the integers that have an even index (odd index in COBOL), multiplied by the integer at the last index.
// Indices in sequence start from 0.
// If the sequence is empty, you should return 0.
function evenLast(numbers) {
let p1 = numbers[0]
for(let i=1;i<numbers.length;i++){
if(i%2==0){
p1+=numbers[i]
}
}
let p2 = p1*numbers[numbers.length-1]
return p1? p2 : 0
}
// Complete the code which should return true if the given object is a single ASCII letter (lower or upper case), false otherwise.
String.prototype.isLetter = function() {
let p1 = this.valueOf()
if (typeof p1 !== 'string' || p1.length !== 1) {
return false
}
return p1.toLowerCase() !== p1.toUpperCase()
}
// Create a function that accepts an array of names, and returns an array of each name with its first letter capitalized and the remainder in lowercase.
// Examples
// ["jo", "nelson", "jurie"] --> ["Jo", "Nelson", "Jurie"]
// ["KARLY", "DANIEL", "KELSEY"] --> ["Karly", "Daniel", "Kelsey"]
function capMe(names) {
if(!names||names.length==0){
return null
}
let ans = names.map((x)=>{
return x[0].toUpperCase()+x.slice(1).toLowerCase()
})
return ans
}
// The string given to your function has had an "egg" inserted directly after each consonant. You need to return the string before it became eggcoded.
// Example
// unscrambleEggs("Beggegeggineggneggeregg") => "Beginner"
// // "B---eg---in---n---er---"
function unscrambleEggs(word) {
return word.split('egg').join('')
}
// Given an array of integers of any length, return an array that has 1 added to the value represented by the array.
// If the array is invalid (empty, or contains negative integers or integers with more than 1 digit), return nil (or your language's equivalent).
// Examples
// Valid arrays
// [4, 3, 2, 5] would return [4, 3, 2, 6] (4325 + 1 = 4326)
// [1, 2, 3, 9] would return [1, 2, 4, 0] (1239 + 1 = 1240)
// [9, 9, 9, 9] would return [1, 0, 0, 0, 0] (9999 + 1 = 10000)
// [0, 1, 3, 7] would return [0, 1, 3, 8] (0137 + 1 = 0138)
// Invalid arrays
// [] is invalid because it is empty
// [1, -9] is invalid because -9 is not a non-negative integer
// [1, 2, 33] is invalid because 33 is not a single-digit integer
function upArray(arr) {
let p1 = arr.length > 0 && arr.every(x => x >= 0 && x <= 9)
let ans = p1 ? (BigInt(arr.join('')) + 1n).toString().padStart(arr.length, '0').split('').map(x=>Number(x)) : null
return ans
}
// The bloody photocopier is broken... Just as you were sneaking around the office to print off your favourite binary code!
// Instead of copying the original, it reverses it: '1' becomes '0' and vice versa.
// Given a string of binary, return the version the photocopier gives you as a string.
function broken(x){
return x.split('').map((x)=>x=='1'? '0':'1').join('')
}
// Each exclamation mark's weight is 2; each question mark's weight is 3. Putting two strings left and right on the balance - are they balanced?
// If the left side is more heavy, return "Left"; if the right side is more heavy, return "Right"; if they are balanced, return "Balance".
// Examples
// "!!", "??" --> "Right"
// "!??", "?!!" --> "Left"
// "!?!!", "?!?" --> "Left"
// "!!???!????", "??!!?!!!!!!!" --> "Balance"
function balance(left, right) {
let p1 = {
"!":2,
"?":3
}
let p2 = left.split('').map((x)=>Number(x.replace(x,p1[x]))).reduce((acc,cur)=>acc+cur,0)
let p3 = right.split('').map((x)=>Number(x.replace(x,p1[x]))).reduce((acc,cur)=>acc+cur,0)
if(p3>p2){
return "Right"
}else if(p3<p2){
return "Left"
}else{
return "Balance"
}
}
// You have to extract a portion of the file name as follows:
// Assume it will start with date represented as long number
// Followed by an underscore
// You'll have then a filename with an extension
// it will always have an extra extension at the end
// Inputs:
// 1231231223123131_FILE_NAME.EXTENSION.OTHEREXTENSION
// 1_This_is_an_otherExample.mpg.OTHEREXTENSIONadasdassdassds34
// 1231231223123131_myFile.tar.gz2
// Outputs
// FILE_NAME.EXTENSION
// This_is_an_otherExample.mpg
// myFile.tar
// Acceptable characters for random tests:
// abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-0123456789
class FileNameExtractor {
static extractFileName (dirtyFileName) {
let p1 = dirtyFileName.split('_').slice(1).join('_').split('.').slice(0,-1).join('.')
return p1
}
}
// Given a string, return true if the first instance of "x" in the string is immediately followed by the string "xx".
// "abraxxxas" → true
// "xoxotrololololololoxxx" → false
// "softX kitty, warm kitty, xxxxx" → true
// "softx kitty, warm kitty, xxxxx" → false
// Note :
// capital X's do not count as an occurrence of "x".
// if there are no "x"'s then return false
function tripleX(str){
let p1 = str.indexOf('x')
let p2 = str[p1+1]
return str[p1+1] == 'x' && str[p1+2] == 'x'
}
// Complete the function that takes a string of English-language text and returns the number of consonants in the string.
// Consonants are all letters used to write English excluding the vowels a, e, i, o, u.
function consonantCount(str) {
let ans = 0
let p1 = ["a", "e", "i", "o", "u"]
let p2 = str.split('').filter(x => /^[a-zA-Z]+$/.test(x)).join('').toLowerCase().split('')
p2.forEach((x)=>{
if(!p1.includes(x)){
ans+=1
}
})
return ans
}
// Given a list of integers values, your job is to return the sum of the values; however, if the same integer value appears multiple times
// in the list, you can only count it once in your sum.
// For example:
// [ 1, 2, 3] ==> 6
// [ 1, 3, 8, 1, 8] ==> 12
// [ -1, -1, 5, 2, -7] ==> -1
// [] ==> null
function uniqueSum(lst){
let ans = [...new Set(lst)].reduce((acc,cur)=>acc+cur,0)
return lst.length>0? ans:null
}
// Not all integers can be represented by JavaScript/TypeScript. It has space to to represent 53bit signed integers. In this Kata, we've to determine if it is safe to use the integer or not. Make use of the latest ES6 features to find this.
// SafeInteger(9007199254740990) //true
// SafeInteger(-90) //true
// SafeInteger(9007199254740992) //false
function SafeInteger(n) {
return n<9007199254740992
}
// Write a function that takes an array of unique integers and returns the minimum number of integers needed to make the values of the array consecutive from the lowest number to the highest number.
// Example
// [4, 8, 6] --> 2
// Because 5 and 7 need to be added to have [4, 5, 6, 7, 8]
// [-1, -5] --> 3
// Because -2, -3, -4 need to be added to have [-5, -4, -3, -2, -1]
// [1] --> 0
// [] --> 0
function consecutive(array) {
if(!array||array.length<2){
return 0
}
let p1 = array.sort((a,b)=>a-b)
let p2 = []
for(let i=p1[0];i<p1[p1.length-1];i++){
p2.push(i)
}
let p3=p2.length-p1.length+1
return p3
}
// Implement the function which should return true if given object is a vowel (meaning a, e, i, o, u, uppercase or lowercase), and false otherwise.
String.prototype.vowel = function() {
return ['a', 'e', 'i', 'o', 'u'].indexOf(this.toLowerCase()) !== -1
}
// Given an integer width and a string ratio written as WIDTH:HEIGHT, output the screen dimensions as a string written as WIDTHxHEIGHT.
// Note: The calculated height should be represented as an integer. If the height is fractional, truncate it.
function findScreenHeight(width, ratio) {
let p1=ratio.split(':')
let p2=p1[0]
let p3=p1[1]
return `${width}x${width/p2*p3}`
}
// Implement a function that takes two inputs, x and y, and returns the value of x raised to the power of y.
// Simple, right? But you are NOT allowed to use Math.pow();
// Both x and y will be natural numbers (non-negative integers) in range 0 <= x,y <= 13.
// Special Case: For this challenge, 0^0 is defined to be 1.
function power(x,y){
let ans = 1
for(let i=0;i<y;i++){
ans*=x
}
return ans
}
// Positive integers that are divisible exactly by the sum of their digits are called Harshad numbers. The first few Harshad numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, ...
// We are interested in Harshad numbers where the product of its digit sum s and s with the digits reversed, gives the original number n. For example consider number 1729:
// its digit sum, s = 1 + 7 + 2 + 9 = 19
// reversing s = 91
// and 19 * 91 = 1729 --> the number that we started with.
// Complete the function which tests if a positive integer n is Harshad number, and returns True if the product of its digit sum and its digit sum reversed equals n; otherwise return False.
function numberJoy(n) {
let p1 = n.toString().split('').map((x)=>Number(x)).reduce((acc,cur)=>acc+cur,0)
let p2 = Number(p1.toString().split('').reverse().join(''))
return p1*p2==n
}
// You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising.
// Your task is to return an object which includes the count of food options selected by the developers on the meetup sign-up form..
// For example, given the following input array:
// var list1 = [
// { firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C',
// meal: 'vegetarian' },
// { firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript',
// meal: 'standard' },
// { firstName: 'Ramona', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby',
// meal: 'vegan' },
// { firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C',
// meal: 'vegetarian' },
// ];
// your function should return the following object (the order of properties does not matter):
// { vegetarian: 2, standard: 1, vegan: 1 }
function orderFood(list) {
let p1 = {}
list.forEach((x)=>{
p1.hasOwnProperty(x.meal)? p1[x.meal]+=1 : p1[x.meal] = 1
})
return p1
}
// Write function heron which calculates the area of a triangle with sides a, b, and c.
// Heron's formula:
// s∗(s−a)∗(s−b)∗(s−c)\sqrt{s * (s - a) * (s - b) * (s - c)}s∗(s−a)∗(s−b)∗(s−c)
//
// where: s=a+b+c2 s = \dfrac{a + b + c} 2 s=2a+b+c
// Notes
// All inputs are valid triangles with integer sides.
// You do not need to round anything. Answers will be tested for correctness within a margin of 0.01.
function heron(a, b, c) {
let p1 = (a+b+c)/2
return Math.sqrt(p1*(p1-a)*(p1-b)*(p1-c))
}
// Create a function that takes in the sum and age difference of two people, calculates their individual ages, and returns a pair of values (oldest age first) if those exist or null/None or {-1, -1} in C if:
// sum < 0
// difference < 0
// Either of the calculated ages come out to be negative
function getAges(sum,difference){
if(difference<0 || sum<0 || difference>sum){
return null
}
let p1 = sum/2
let ans = [p1+difference/2,p1-difference/2]
return ans
}
// A Nice array is defined to be an array where for every value n in the array, there is also an element n - 1 or n + 1 in the array.
// examples:
// [2, 10, 9, 3] is a nice array because
// 2 = 3 - 1
// 10 = 9 + 1
// 3 = 2 + 1
// 9 = 10 - 1
// [4, 2, 3] is a nice array because
// 4 = 3 + 1
// 2 = 3 - 1
// 3 = 2 + 1 (or 3 = 4 - 1)
// [4, 2, 1] is a not a nice array because
// for n = 4, there is neither n - 1 = 3 nor n + 1 = 5
// Write a function named isNice/IsNice that returns true if its array argument is a Nice array, else false. An empty array is not considered nice.
function isNice(arr){
if(arr.length==0){
return false
}
let check = 0
arr.forEach((x)=>{
if(arr.includes(x-1)||arr.includes(x+1)){
check +=1
}
})
return check==arr.length? true : false
}
// Object debugging
// While making a zork-type game, you create an object of rooms. Unfortunately, the game is not working. Find all of the errors in the rooms object to get your game working again.
let rooms = {
first: {
description: 'This is the first room',
items: {
chair: 'The old chair looks comfortable',
lamp: 'This lamp looks ancient'
},
},
second: {
description: 'This is the second room',
items: {
couch: 'This couch looks like it would hurt your back',
table: 'On the table there is an unopened bottle of water'
}
}
}
// Create a function that checks if the first argument n is divisible by all other arguments (return true if no other arguments)
// Example:
// (6,1,3)--> true because 6 is divisible by 1 and 3
// (12,2)--> true because 12 is divisible by 2
// (100,5,4,10,25,20)--> true
// (12,7)--> false because 12 is not divisible by 7
function isDivisible(n, ...arr){
if(arr.length==0){
return true
}
for(let i=0;i<arr.length;i++){
if(n%arr[i]!=0){
return false
}
}
return true
}
// Test your ability to extend the functionality of built-in classes. In this case, we want you to extend the built-in Array class with the following methods: square(), cube(), average(), sum(), even() and odd().
// Explanation:
// square() must return a copy of the array, containing all values squared
// cube() must return a copy of the array, containing all values cubed
// average() must return the average of all array values; on an empty array must return NaN (note: the empty array is not tested in Ruby!)
// sum() must return the sum of all array values
// even() must return an array of all even numbers
// odd() must return an array of all odd numbers
// Note: the original array must not be changed in any case!
// Example
// var numbers = [1, 2, 3, 4, 5];
// numbers.square(); // must return [1, 4, 9, 16, 25]
// numbers.cube(); // must return [1, 8, 27, 64, 125]
// numbers.average(); // must return 3
// numbers.sum(); // must return 15
// numbers.even(); // must return [2, 4]
// numbers.odd(); // must return [1, 3, 5]
Array.prototype.square = function() {
return this.map((x)=>Math.pow(x,2))
}
Array.prototype.cube = function(){
return this.map((x)=>Math.pow(x,3))
}
Array.prototype.average = function(){
if (this.length === 0) return NaN
return this.reduce((acc,cur)=>acc+cur,0)/this.length
}
Array.prototype.sum = function(){
return this.reduce((acc,cur)=>acc+cur,0)
}
Array.prototype.even = function(){
return this.filter((x)=>x%2==0)
}
Array.prototype.odd = function(){
return this.filter((x)=>x%2!=0)
}
// Kevin is noticing his space run out! Write a function that removes the spaces from the values and returns an array showing the space decreasing.
// For example, running this function on the array ['i', 'have','no','space'] would produce ['i','ihave','ihaveno','ihavenospace']
function spacey(array) {
if (array.length === 0) return []
let ans = [array[0]]
for(let i=1;i<array.length;i++){
ans.push(ans[i-1]+array[i])
}
return ans
}
// Write function potatoes with
// int parameter p0 - initial percent of water-
// int parameter w0 - initial weight -
// int parameter p1 - final percent of water -
// potatoesshould return the final weight coming out of the oven w1 truncated as an int.
// Example:
// potatoes(99, 100, 98) --> 50
function potatoes(p0, w0, p1) {
let ans = (w0 * (100 - p0)) / (100 - p1)
return Math.floor(ans)
}
// Implement a function which accepts 2 arguments: string and separator.
// The expected algorithm: split the string into words by spaces, split each word into separate characters and join them back with the specified separator, join all the resulting "words" back into a sentence with spaces.
// For example:
// splitAndMerge("My name is John", " ") == "M y n a m e i s J o h n"
// splitAndMerge("My name is John", "-") == "M-y n-a-m-e i-s J-o-h-n"
// splitAndMerge("Hello World!", ".") == "H.e.l.l.o W.o.r.l.d.!"
// splitAndMerge("Hello World!", ",") == "H,e,l,l,o W,o,r,l,d,!"
function splitAndMerge(string, separator) {
return string.split(" ")
.map(x => {
return x.split("").join(separator)
})
.join(" ")
}
// you have decided to write a function that will return the first n elements of the sequence with the given common difference d and first element a. Note that the difference may be zero!
// The result should be a string of numbers, separated by comma and space.
// Example
// # first element: 1, difference: 2, how many: 5
// arithmetic_sequence_elements(1, 2, 5) == "1, 3, 5, 7, 9"
function arithmeticSequenceElements(a, d, n) {
let ans = [a]
for(let i=0;i<n-1;i++){
ans.push(ans[i]+d)
}
return ans.join(', ')
}
//or
function arithmeticSequenceElements(a, d, n) {
let ans = []
for(let i=0;i<n;i++){
ans.push(a+(d*i))
}
return ans.join(', ')
}
// Given an array of Boolean values and a logical operator, return a Boolean result based on sequentially applying the operator to the values in the array.
// Examples
// booleans = [True, True, False], operator = "AND"
// True AND True -> True
// True AND False -> False
// return False
// booleans = [True, True, False], operator = "OR"
// True OR True -> True
// True OR False -> True
// return True
// booleans = [True, True, False], operator = "XOR"
// True XOR True -> False
// False XOR False -> False
// return False
// Input
// an array of Boolean values (1 <= array_length <= 50)
// a string specifying a logical operator: "AND", "OR", "XOR"
// Output
// A Boolean value (True or False).
function logicalCalc(array, op){
const operations = {
"AND": (a, b) => a && b,
"OR": (a, b) => a || b,
"XOR": (a, b) => a !== b
}
return array.reduce(operations[op])
}
// Given a string of digits confirm whether the sum of all the individual even digits are greater than the sum of all the indiviudal odd digits. Always a string of numbers will be given.
// If the sum of even numbers is greater than the odd numbers return: "Even is greater than Odd"
// If the sum of odd numbers is greater than the sum of even numbers return: "Odd is greater than Even"
// If the total of both even and odd numbers are identical return: "Even and Odd are the same"
function evenOrOdd(str) {
let odd = 0
let even = 0
str.split('').forEach((x)=>{
if(Number(x)%2==0){
even+=Number(x)
}else{
odd+=Number(x)
}
})
return even>odd? "Even is greater than Odd" : even==odd? "Even and Odd are the same" : "Odd is greater than Even"
}
// The function should take one parameter: an object/dict with two or more name-value pairs that represent the members of the group and the amount spent by each.
// Your function should return an object/dict with the same names, showing how much money the members should pay or receive.
// Further points:
// The values should be positive numbers if the person should receive money from the group, negative numbers if they owe money to the group.
// If value is a decimal, round to two decimal places.
// Translations and comments (and upvotes!) welcome.
// Example
// 3 friends go out together: A spends £20, B spends £15, and C spends £10. The function should return an object/dict showing that A should receive £5, B should receive £0, and C should pay £5.
// var group = {
// A: 20,
// B: 15,
// C: 10
// }
// splitTheBill(group) // returns {A: 5, B: 0, C: -5}
function splitTheBill(x) {
let people = 0
let total = 0
for (let key in x) {
total+= x[key]
people+=1
}
let avg = total/people
Object.keys(x).forEach(key => {
x[key] = Math.round((x[key] - avg) * 100) / 100
})
return x
}
// Given an integer n and two other values, build an array of size n filled with these two values alternating.
// Examples
// 5, true, false --> [true, false, true, false, true]
// 10, "blue", "red" --> ["blue", "red", "blue", "red", "blue", "red", "blue", "red", "blue", "red"]
// 0, "one", "two" --> []
function alternate(n, firstValue, secondValue){
let ans = []
for(let i=0;i<n;i++){
if(i%2==0){
ans.push(firstValue)
}else{
ans.push(secondValue)
}
}
return ans
}
// Count the number of exclamation marks and question marks, return the product.
// Examples
// "" ---> 0
// "!" ---> 0
// "!ab? ?" ---> 2
// "!!" ---> 0
// "!??" ---> 2
// "!???" ---> 3
// "!!!??" ---> 6
// "!!!???" ---> 9
// "!???!!" ---> 9
// "!????!!!?" ---> 20
function product (string) {
let p1 = 0
let p2 = 0
string.split('').forEach((x)=>{
if(x=='!'){
p1+=1
}else if(x=='?'){
p2+=1
}
})
return p1*p2
}
// Please write a function that sums a list, but ignores any duplicated items in the list.
// For instance, for the list [3, 4, 3, 6] the function should return 10,
// and for the list [1, 10, 3, 10, 10] the function should return 4.
function sumNoDuplicates(numList) {
let ans = 0
const count = numList.reduce((accumulator, current) => {
accumulator[current] = (accumulator[current] || 0) + 1
return accumulator
}, {})
for (const key in count) {
if (count[key]==1) {
ans+=Number(key)
}
}
return ans
}
// My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example:
// "dolphin" -> "The Dolphin"
// However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last letter,
// combined into one word (WITHOUT "The" in front), like this:
// "alaska" -> "Alaskalaska"
// Complete the function that takes a noun as a string, and returns her preferred band name written as a string.
function bandNameGenerator(str) {
let coinFlip = str[0].toLowerCase()==str[str.length-1].toLowerCase()
return coinFlip? str.charAt(0).toUpperCase() + str.slice(1)+str.slice(1) : `The ${str.charAt(0).toUpperCase() + str.slice(1)}`
}
// Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one.
// Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic order. The values must maintain their original type.
// Note that numbers written as strings are strings and must be sorted with the other strings.
function dbSort(a){
let p1 = a.filter((x)=>typeof(x)=="number").sort((a,b)=>a-b)
let p2 = a.filter((x)=>typeof(x)=="string").sort()
return p1.concat(p2)
}
// Write a function that takes a string and an an integer n as parameters and returns a list of all words that are longer than n.
// Example:
// * With input "The quick brown fox jumps over the lazy dog", 4
// * Return ['quick', 'brown', 'jumps']
function filterLongWords(sentence, n) {
return sentence.split(' ').filter((x)=>x.length>n)
}
// Some people just have a first name; some people have first and last names and some people have first, middle and last names.
// You task is to initialize the middle names (if there is any).
// Examples
// 'Jack Ryan' => 'Jack Ryan'
// 'Lois Mary Lane' => 'Lois M. Lane'
// 'Dimitri' => 'Dimitri'
// 'Alice Betty Catherine Davis' => 'Alice B. C. Davis'
function initializeNames(name){
let p1 = name.split(' ')
if(p1.length<3){
return name
}else{
let p2 = [p1[0]]
for(let i=1;i<p1.length-1;i++){
p2.push(p1[i].slice(0,1).toUpperCase()+'.')
}
p2.push(p1[p1.length-1])
return p2.join(' ')
}
}
// There are two lists, possibly of different lengths. The first one consists of keys, the second one consists of values.
// Write a function createDict(keys, values) that returns a dictionary created from keys and values. If there are not enough values, the rest of keys should have a None (JS null)value.
// If there not enough keys, just ignore the rest of values.
// Example 1:
// keys = ['a', 'b', 'c', 'd']
// values = [1, 2, 3]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3, 'd': null}
// Example 2:
// keys = ['a', 'b', 'c']
// values = [1, 2, 3, 4]
// createDict(keys, values) // returns {'a': 1, 'b': 2, 'c': 3}
function createDict(keys, values){
let ans = {}
for(let i=0;i<keys.length;i++){
if(values[i]==undefined){
ans[keys[i]] = null
}else{
ans[keys[i]]=values[i]
}
}
return ans
}
// Count how often sign changes in array.
// result
// number from 0 to ... . Empty array returns 0
// example
// const arr = [1, -3, -4, 0, 5];
// /*
// | elem | count |
// |------|-------|
// | 1 | 0 |
// | -3 | 1 |
// | -4 | 1 |
// | 0 | 2 |
// | 5 | 2 |
// */
// catchSignChange(arr) == 2;
function catchSignChange(arr) {
let ans = 0
for(let i=1;i<arr.length;i++){
if((arr[i-1]>=0&&arr[i]<0)||(arr[i-1]<0&&arr[i]>=0)){
ans+=1
}
}
return ans
}
// Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word.
// The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can
// assume both words will contain the dividing letter.
// Examples
// ("hello", "world", "l") ==> "held"
// ("coding", "anywhere", "n") ==> "codinywhere"
// ("jason", "samson", "s") ==> "jasamson"
// ("wonderful", "people", "e") ==> "wondeople"
function stringMerge(string1, string2, letter){
//find the index of where the letter is in each string
//use that index to slice where the the letter is
//combine the two sliced parts
let p1 = string1.indexOf(letter)
let p2 = string2.indexOf(letter)
let p3 = string1.slice(0,p1)
let p4 = string2.slice(p2,string2.length)
return p3+p4
}
//or
function stringMerge(string1, string2, letter){
return(string1.slice(0,string1.indexOf(letter))+string2.slice(string2.indexOf(letter),string2.length))
}
// The task is to write a function that accepts two parameters: an array and a callback function (in Ruby: a block).
// The function should return true if the callback function / block returns true for any item in the array, otherwise return false.
// The function should return false if the array is empty.
function any(arr, fun){
return arr.some(fun)
}
// Coding in function cutIt, function accept 1 parameter:arr. arr is a string array.
// The first mission: Traversing arr, find the shortest string length.
// The second mission: Traversing arr again, intercept all strings to the shortest string length(Start from index0).
// you can use one of slice() substring() or substr() do it. return the result after finished the work.
// for example:
// cutIt(["ab","cde","fgh"]) should return ["ab","cd","fg"]
// cutIt(["abc","defgh","ijklmn"]) should return ["abc","def","ijk"]
// cutIt(["codewars","javascript","java"]) should return ["code","java","java"]
function cutIt(arr){