-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaScriptPractice.js
More file actions
12508 lines (8566 loc) · 361 KB
/
Copy pathJavaScriptPractice.js
File metadata and controls
12508 lines (8566 loc) · 361 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
// You have to create a function which receives 3 number arguments: 2 operands a and b, and the result of an unknown operation performed on them.
// Based on those 3 values you have to return a string, that describes which operation was used to get the given result.
// The possible return strings are: "addition", "subtraction", "multiplication", "division".
// Examples:
// (a = 1, b = 2, result = 3) --> 1 ? 2 = 3 --> "addition"
// (a = 5, b = 2, result = 2.5) --> 5 ? 2 = 2.5 --> "division"
// Notes
// The / operator performs a plain division without rounding.
// You can assume that there will always be a unique valid answer (no ambiguous cases like e.g. 1 ? 0 = 0 which could be either - or +, or 3 ? 1 = 3 which could be either * or /).
// You can assume that there will be no division by 0
function calcType(a, b, res) {
let ans = {
[a+b]: "addition" ,
[a-b]: "subtraction",
[a*b]: "multiplication",
[a/b]: "division"
}
return ans[res]
}
// You are given a program sumSquares that takes an array as input and returns the sum of the squares of each item in an array. For example:
// sumSquares([1,2,3,4,5]) === 55 // 1 ** 2 + 2 ** 2 + 3 ** 2 + 4 ** 2 + 5 ** 2
// sumSquares([7,3,9,6,5]) === 200
// sumSquares([11,13,15,18,2]) === 843
function sumSquares(array) {
return array.reduce((acc,cur)=>acc+Math.pow(cur,2),0)
}
// Given an array, find the duplicates in that array, and return a new array of those duplicates. The elements of the returned array should appear in the order when they first appeared as duplicates.
// Note: numbers and their corresponding string representations should not be treated as duplicates (i.e., "1" != 1).
// Examples
// [1, 2, 4, 4, 3, 3, 1, 5, 3, "5"] ==> [4, 3, 1]
// [0, 1, 2, 3, 4, 5] ==> []
function duplicates(arr) {
let p1 = []
arr.forEach((x, i) => {
if (arr.indexOf(x) !== i && p1.indexOf(x) === -1) {
p1.push(x)
}
})
return p1
}
// Take a number: 56789. Rotate left, you get 67895.
// Keep the first digit in place and rotate left the other digits: 68957.
// Keep the first two digits in place and rotate the other ones: 68579.
// Keep the first three digits and rotate left the rest: 68597. Now it is over since keeping the first four it remains only one digit which rotated is itself.
// You have the following sequence of numbers:
// 56789 -> 67895 -> 68957 -> 68579 -> 68597
// and you must return the greatest: 68957.
// Task
// Write function max_rot(n) which given a positive integer n returns the maximum number you got doing rotations similar to the above example.
// So max_rot (or maxRot or ... depending on the language) is such as:
// max_rot(56789) should return 68957
// max_rot(38458215) should return 85821534
function maxRot(n) {
let p1 = n.toString()
let ans = [n]
for(let i=0;i<p1.length-1;i++){
let p2 = p1.slice(0, i) + p1.slice(i + 1) + p1.charAt(i)
p1=p2
ans.push(Number(p2))
}
return Math.max(...ans)
}
// Your task is to complete the Cat class which extends Animal and replace the speak method to return the cats name + meows. e.g. 'Mr Whiskers meows.'
// The name attribute is accessible in the class with this.name.
class Cat extends Animal {
speak(){
return `${this.name} meows.`
}
}
// You are given an array. Complete the function that returns the number of ALL elements within an array, including any nested arrays.
// Examples
// [] --> 0
// [1, 2, 3] --> 3
// ["x", "y", ["z"]] --> 4
// [1, 2, [3, 4, [5]]] --> 7
// The input will always be an array.
function deepCount(a){
let ans = 0
for(let i=0;i<a.length;i++){
ans+=1
if(Array.isArray(a[i])){
ans+=deepCount(a[i])
}
}
return ans
}
// Write a function that returns true if the number is a "Very Even" number.
// If a number is a single digit, then it is simply "Very Even" if it itself is even.
// If it has 2 or more digits, it is "Very Even" if the sum of its digits is "Very Even".
// Examples
// number = 88 => returns false -> 8 + 8 = 16 -> 1 + 6 = 7 => 7 is odd
// number = 222 => returns true -> 2 + 2 + 2 = 6 => 6 is even
// number = 5 => returns false
// number = 841 => returns true -> 8 + 4 + 1 = 13 -> 1 + 3 => 4 is even
// Note: The numbers will always be 0 or positive integers!
function isVeryEvenNumber(n) {
if (n < 10) {
return n % 2 === 0
}
const digitSum = n
.toString()
.split('')
.reduce((sum, digit) => sum + Number(digit), 0)
return isVeryEvenNumber(digitSum)
}
// You will be given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.
// For example:
// solve([15,11,10,7,12]) = [15,7,12,10,11]
// The first max is 15 and the first min is 7. The second max is 12 and the second min is 10 and so on.
function solve(arr){
let p1 = arr.slice().sort((a,b)=>a-b)
let p2 = p1.slice().reverse()
let ans = []
for(let i=0;i<arr.length;i++){
if(!ans.includes(p2[i])){
ans.push(p2[i])
}
if(!ans.includes(p1[i])){
ans.push(p1[i])
}
}
return ans
}
// Write a generic function chainer that takes a starting value, and an array of functions to execute on it
// The input for each function is the output of the previous function (except the first function, which takes the starting value as its input). Return the final value after execution is complete.
// function add(num) {
// return num + 1;
// }
// function mult(num) {
// return num * 30;
// }
// chain(2, [add, mult]);
// // returns 90;
function chain(input, fs) {
let ans=input
fs.forEach((x)=>{
ans=x(ans)
})
return ans
}
// Write a simple function to check if the string contains the word hallo in different languages.
// These are the languages of the possible people you met the night before:
// hello - english
// ciao - italian
// salut - french
// hallo - german
// hola - spanish
// ahoj - czech republic
// czesc - polish
// Notes
// you can assume the input is a string.
// to keep this a beginner exercise you don't need to check if the greeting is a subset of word (Hallowen can pass the test)
// function should be case insensitive to pass the tests
function validateHello(greetings) {
let p1 = ['hello','ciao',"salut","hallo","hola","ahoj","czesc"]
let p2 = greetings.split(' ')
let ans = false
for(let i=0;i<p2.length;i++){
if(p1.includes(p2[i].toLowerCase().replace(/[^a-zA-Z]/g, ''))){
ans=true
break
}
}
return ans
}
// An element is leader if it is greater than The Sum all the elements to its right side.
// Given an array/list [] of integers , Find all the LEADERS in the array.
// Notes
// Array/list size is at least 3 .
// Array/list's numbers Will be mixture of positives , negatives and zeros
// Repetition of numbers in the array/list could occur.
// Returned Array/list should store the leading numbers in the same order in the original array/list .
// Note : The last element 0 is equal to right sum of its elements (abstract zero).
// Input >> Output Examples
// arrayLeaders ({1, 2, 3, 4, 0}) ==> return {4}
// arrayLeaders ({16, 17, 4, 3, 5, 2}) ==> return {17, 5, 2}
// arrayLeaders ({5, 2, -1}) ==> return {5, 2}
// arrayLeaders ({0, -1, -29, 3, 2}) ==> return {0, -1, 3, 2}
function arrayLeaders(numbers){
let ans = []
// for(let i=0;i<numbers.length;i++){
// let p1 = numbers.slice(i+1,numbers.length).reduce((acc,cur)=>acc+cur,0)
// if(numbers[i]>p1){
// ans.push(numbers[i])
// }
// }
// return ans
let p1 = numbers.reduce((acc,cur)=>acc+cur,0)
numbers.forEach((x)=>{
p1-=x
if(x>p1){
ans.push(x)
}
})
return ans
}
// Write a function that doubles every second integer in a list, starting from the left.
// Example:
// For input array/list :
// [1,2,3,4]
// the function should return :
// [1,4,3,8]
function doubleEveryOther(a) {
return a.map((x,i)=>{
return i%2!==0? x*2:x
})
}
// Write reverseList function that simply reverses lists.
function reverseList(arr) {
return arr.reverse()
}
// Your job is to implement a function which returns the last D digits of an integer N as a list.
// Special cases:
// If D > (the number of digits of N), return all the digits.
// If D <= 0, return an empty list.
// Examples:
// N = 1
// D = 1
// result = [1]
// N = 1234
// D = 2
// result = [3, 4]
// N = 637547
// D = 6
// result = [6, 3, 7, 5, 4, 7]
function lastDigit(n, d) {
if(d<=0){
return []
}
let p1 = n.toString().split('')
if(d>=p1.length){
return p1.map((x)=>Number(x))
}
let ans = []
for(let i=p1.length-1;i>p1.length-d-1;i--){
ans.push(Number(p1[i]))
}
return ans.reverse()
}
// Write a function called evenOrOddSum that takes an array of integers as an argument.
// The function should calculate the sum of all the even numbers and the sum of all the odd numbers.
// It should return a string in the following exact format: "Evens: X, Odds: Y" (where X is the sum of evens, and Y is the sum of odds).
// Examples
// evenOrOddSum([1, 2, 3, 4, 5, 6]);
// // Should return: "Evens: 12, Odds: 9" (2+4+6 = 12; 1+3+5 = 9)
// evenOrOddSum([0, -2, 5]);
// // Should return: "Evens: -2, Odds: 5"
// evenOrOddSum([]);
// // Should return: "Evens: 0, Odds: 0"
function evenOrOddSum(arr) {
let evens=0
let odds=0
arr.forEach((x)=>{
if(x%2==0){
evens+=x
}else{
odds+=x
}
})
return `Evens: ${evens}, Odds: ${odds}`
}
// You'll be given a list of two strings, and each will contain exactly one colon (":") in the middle (but not at beginning or end). The length of the strings, before and after the colon, are random.
// Your job is to return a list of two strings (in the same order as the original list), but with the characters after each colon swapped.
// Examples
// ["abc:123", "cde:456"] --> ["abc:456", "cde:123"]
// ["a:12345", "777:xyz"] --> ["a:xyz", "777:12345"]
function tailSwap(arr) {
let p1 = arr.map((x)=>x.split(':'))
return [`${p1[0][0]}:${p1[1][1]}`,`${p1[1][0]}:${p1[0][1]}`]
}
// Given an input of an array of objects containing usernames, status and time since last activity (in mins), create a function to work out who is online, offline and away.
// If someone is online but their lastActivity was more than 10 minutes ago they are to be considered away.
// The input data has the following structure:
// [{
// username: 'David',
// status: 'online',
// lastActivity: 10
// }, {
// username: 'Lucy',
// status: 'offline',
// lastActivity: 22
// }, {
// username: 'Bob',
// status: 'online',
// lastActivity: 104
// }]
// The corresponding output should look as follows:
// {
// online: ['David'],
// offline: ['Lucy'],
// away: ['Bob']
// }
// If for example, no users are online the output should look as follows:
// {
// offline: ['Lucy'],
// away: ['Bob']
// }
// username will always be a string, status will always be either 'online' or 'offline' (UserStatus enum in C#) and lastActivity will always be number >= 0.
// Finally, if you have no friends in your chat application, the input will be an empty array []. In this case you should return an empty object {} (empty Dictionary in C#).
const whosOnline = (friends) => {
let offline = friends.filter((x)=>x.status=="offline").map((x=>x.username))
let online = friends.filter((x)=>(x.status=="online"&&x.lastActivity<11)).map((x=>x.username))
let away = friends.filter((x)=>(x.status=="online"&&x.lastActivity>10)).map((x=>x.username))
let result = {}
if (online.length) result.online = online
if (offline.length) result.offline = offline
if (away.length) result.away = away
return result
}
// Your job is to write a function, which takes three integers a, b, and c as arguments, and returns True if exactly two of the three integers are positive numbers (greater than zero), and False - otherwise.
// Examples:
// twoArePositive(2, 4, -3) == true
// twoArePositive(-4, 6, 8) == true
// twoArePositive(4, -6, 9) == true
// twoArePositive(-4, 6, 0) == false
// twoArePositive(4, 6, 10) == false
// twoArePositive(-14, -3, -4) == false
function twoArePositive(a, b, c) {
let p1=[a,b,c].filter((x)=>x>0)
return p1.length==2
}
// The vowel substrings in the word codewarriors are o,e,a,io. The longest of these has a length of 2.
// Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces,
// return the length of the longest vowel substring. Vowels are any of aeiou.
function solve(s){
let c1 = ['a','e','i','o','u']
let ans = []
let p1 = s.split('')
let p2=0
for(let i=0;i<p1.length;i++){
if(c1.includes(p1[i])){
p2+=1
}else{
if(p2!=0){
ans.push(p2)
}
p2=0
}
}
return ans.sort((a,b)=>b-a)[0]
}
// Write a function that takes a sentence and returns an array containing the number of vowels in each word.
// Examples
// countVowelsPerWord("hello world")
// returns
// [2, 1]
// because:
// "hello" → 2 vowels
// "world" → 1 vowel
// countVowelsPerWord("JavaScript is fun")
// returns
// [3, 1, 1]
// countVowelsPerWord("AEIOU")
// returns
// [5]
// Rules
// Vowels are: a, e, i, o, u
// Case insensitive
// Words are separated by a single space
// Input will always be a non-empty string
// Example
// Input:
// "cats and dogs"
// Output:
// [1, 1, 1]
function countVowelsPerWord(sentence) {
let c1 = ['a','e','i','o','u']
let ans = []
let p1 = sentence.toLowerCase().split(' ').forEach((x)=>{
let count = 0
x.split('').forEach((y)=>{
if(c1.includes(y)){
count+=1
}
})
ans.push(count)
})
return ans
}
// Given a point in a Euclidean plane (x and y), return the quadrant the point exists in: 1, 2, 3 or 4 (integer). x and y are non-zero integers, therefore the given point never lies on the axes.
// Examples
// (1, 2) => 1
// (3, 5) => 1
// (-10, 100) => 2
// (-1, -9) => 3
// (19, -56) => 4
function quadrant(x, y) {
if(x>=0&&y>=0){
return 1
}else if(x<0&&y<0){
return 3
}else if(x<0&&y>0){
return 2
}else{
return 4
}
}
// I've written five function equal1,equal2,equal3,equal4,equal5, defines six global variables v1 v2 v3 v4 v5 v6, every function has two local variables a,b, please set the appropriate value for the two variables(select from v1--v6),
// making these function return value equal to 100. the function equal1 is completed, please refer to this example to complete the following functions.
let v1 = 50
let v2 = 100
let v3 = 150
let v4 = 200
let v5 = 2
let v6 = 250
function equal1(){
let a = v1
let b = v1
return a + b;
}
//Please refer to the example above to complete the following functions
function equal2(){
let a = v3 //set number value to a
let b = v1 ; //set number value to b
return a - b;
}
function equal3(){
let a = v1 //set number value to a
let b = v5 ; //set number value to b
return a * b;
}
function equal4(){
let a = v4 //set number value to a
let b = v5 ; //set number value to b
return a / b;
}
function equal5(){
let a = v6 //set number value to a
let b = v3 ; //set number value to b
return a % b;
}
// For every good kata idea there seem to be quite a few bad ones!
// In this kata you need to check the provided 2 dimensional array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!',
// if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.
// The sub arrays may not be the same length.
// The solution should be case insensitive (ie good, GOOD and gOOd all count as a good idea). All inputs may not be strings.
function well(x){
let p1 = 0
x.forEach((y=>{
y.forEach((z)=>{
if(z.toString().toLowerCase()=='good'){
p1+=1
}
})
}))
if(p1===0){
return "Fail!"
}else if(p1<=2){
return "Publish!"
}else if(p1>=3){
return "I smell a series!"
}
}
// Complete the function that takes an array of words.
// You must concatenate the nth letter from each word to construct a new word which should be returned as a string, where n is the position of the word in the list.
// For example:
// ["yoda", "best", "has"] --> "yes"
// ^ ^ ^
// n=0 n=1 n=2
function nthChar(words){
let ans = ""
words.forEach((x,i)=>{
ans+=x[i]
})
return ans
}
// Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer.
// Square all numbers k (0 <= k <= n) between 0 and n.
// Count the numbers of digits d used in the writing of all the k**2.
// Implement the function taking n and d as parameters and returning this count.
// Examples:
// n = 10, d = 1
// the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
// We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.
// The function, when given n = 25 and d = 1 as argument, should return 11 since
// the k*k that contain the digit 1 are:
// 1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
// So there are 11 digits 1 for the squares of numbers between 0 and 25.
// Note that 121 has twice the digit 1.
function nbDig(n, d) {
let p1 = 0
for(let i=0;i<=n;i++){
let p2 = (i*i).toString()
p1+= p2.split(d.toString()).length-1
}
return p1
}
// I've got a crazy mental illness. I dislike numbers a lot. But it's a little complicated: The number I'm afraid of depends on which day of the week it is... This is a concrete description of my mental illness:
// Monday --> 12
// Tuesday --> numbers greater than 95
// Wednesday --> 34
// Thursday --> 0
// Friday --> numbers divisible by 2
// Saturday --> 56
// Sunday --> 666 or -666
// Write a function which takes a string (day of the week) and an integer (number to be tested) so it tells the doctor if I'm afraid or not. (return a boolean)
var AmIAfraid = function(day, num){
switch (day) {
case 'Monday':
return num==12
case 'Tuesday':
return num>95
case 'Wednesday':
return num==34
case 'Thursday':
return num==0
case 'Friday':
return num%2==0
case 'Saturday':
return num==56
case 'Sunday':
return (num==666 ||num==-666)
}
}
// You have to write a calculator that receives strings for input. The dots will represent the number in the equation. There will be dots on one side, an operator,
// and dots again after the operator. The dots and the operator will be separated by one space.
// Here are the following valid operators :
// + Addition
// - Subtraction
// * Multiplication
// // Integer Division
// Your Work (Task)
// You'll have to return a string that contains dots, as many the equation returns. If the result is 0, return the empty string. When it comes to subtraction,
// the first number will always be greater than or equal to the second number.
// Examples (Input => Output)
// * "..... + ..............." => "...................."
// * "..... - ..." => ".."
// * "..... - ." => "...."
// * "..... * ..." => "..............."
// * "..... * .." => ".........."
// * "..... // .." => ".."
// * "..... // ." => "....."
// * ". // .." => ""
// * ".. - .." => ""
function dotCalculator(equation) {
const [left, op, right] = equation.split(' ')
const a = left.length
const b = right.length
switch (op) {
case '+':
return '.'.repeat(a + b)
case '-':
return '.'.repeat(a - b)
case '*':
return '.'.repeat(a * b)
case '//':
return '.'.repeat(Math.floor(a / b))
}
}
// Coding in function roundIt. function accept 1 parameter n. It's a number with a decimal point. Please use different methods based on the location of the decimal point, turn the number into an integer.
// If the decimal point is on the left side of the number (that is, the count of digits on the left of the decimal point is less than that on the right), Using ceil() method.
// roundIt(3.45) should return 4
// If the decimal point is on the right side of the number (that is, the count of digits on the left of the decimal point is more than that on the right), Using floor() method.
// roundIt(34.5) should return 34
// If the decimal point is on the middle of the number (that is, the count of digits on the left of the decimal point is equals that on the right), Using round() method.
// roundIt(34.56) should return 35
function roundIt(n){
let p1 = n.toString().split('.')
if(p1[0].length>p1[1].length){
return Math.floor(n)
}else if(p1[0].length<p1[1].length){
return Math.ceil(n)
}else{
return Math.round(n)
}
}
// Create a method each_cons that accepts a list and a number n, and returns cascading subsets of the list of size n, like so:
// each_cons([1,2,3,4], 2)
// #=> [[1,2], [2,3], [3,4]]
// each_cons([1,2,3,4], 3)
// #=> [[1,2,3],[2,3,4]]
// As you can see, the lists are cascading; ie, they overlap, but never out of order.
function eachCons(array, n) {
let ans = []
for(let i=0;i<=array.length-n;i++){
for(let j=i;j<n+i;j++){
p1.push(array[j])
}
ans.push(p1)
}
return ans
}
// Given a dictionary with all the names of the suspects and everyone that they have seen on that day which may look like this:
// {'James': ['Jacob', 'Bill', 'Lucas'],
// 'Johnny': ['David', 'Kyle', 'Lucas'],
// 'Peter': ['Lucy', 'Kyle']}
// and also a list of the names of the dead people:
// ['Lucas', 'Bill']
// return the name of the one killer, in our case 'James' because he is the only person that saw both 'Lucas' and 'Bill'
function killer(suspectInfo, dead) {
let ans
for (let key in suspectInfo){
let p1 = suspectInfo[key]
if(dead.every(person => suspectInfo[key].includes(person))){
ans=key
}
}
return ans
}
// 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
// }
function neutralise(s1, s2){
let ans = []
let p1 = s1.split('')
let p2 = s2.split('')
p1.forEach((x,i)=>{
return p1[i]==p2[i]? ans.push(x) : ans.push('0')
})
return ans.join('')
}
// Coding in function fiveLine, function accept 1 parameter:s. s is a string.
// Please return a string of 5 lines(newline symbol is \n). The first line has one s; Second line have two s; and so on..Fifth line have five s;
// Note1: The two sides of the parameter s may contain some whitespace, please clear them before using s.
// Note2: Using a string template can make your job easier.
// Example:
// fiveLine(" a") should return "a\naa\naaa\naaaa\naaaaa"
// a
// aa
// aaa
// aaaa
// aaaaa <---The effect when you console.log it
// fiveLine(" xy ")
// should return "xy\nxyxy\nxyxyxy\nxyxyxyxy\nxyxyxyxyxy"
// xy
// xyxy
// xyxyxy
// xyxyxyxy
// xyxyxyxyxy <---The effect when you console.log it
function fiveLine(s){
let p1 = s.trim()
let ans = [p1]
for(let i=2;i<=5;i++){
ans.push(`\n${p1.repeat(i)}`)
}
return ans.join('')
}
// In this kata you are given a string for example:
// "example(unwanted thing)example"
// Your task is to remove everything inside the parentheses as well as the parentheses themselves.
// The example above would return:
// "exampleexample"
// Notes
// Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like "[]" and "{}" as these will never appear.
// There can be multiple parentheses.
// The parentheses can be nested.
function removeParentheses(s){
let p1 = 0
let ans = ""
s.split('').forEach((x)=>{
if(x==='('){
p1+=1
}else if(x===')'){
p1-=1
}else if(p1===0){
ans+=x
}
})
return ans
}
// You are to write a function that takes a string as its first parameter. This string will be a string of words.
// You are expected to then use the second parameter, which will be an integer, to find the corresponding word in the given string. The first word would be represented by 0.
// Once you have the located string you are finally going to multiply by it the third provided parameter, which will also be an integer. You are additionally required to add a hyphen in between each word.
// Example
// modifyMultiply ("This is a string", 3, 5) returns "string-string-string-string-string"
function modifyMultiply (str,loc,num) {
let ans = []
let p1 = str.split(' ')[loc]
for(let i=0;i<num;i++){
ans.push(p1)
}
return ans.join('-')
}
// In this Kata your task will be to return the count of pairs that have consecutive numbers. The first pair consists of the first and second element of the input, the second pair is the next two elements (3rd and 4th), etc. If the input ends with an element without a pair, it should be ignored.
// For example, [1,2,5,8,-4,-3,7,6,5] has 3 such pairs. Candidate pairs are selected as follows: [(1,2), (5,8), (-4,-3), (7,6), 5].
// the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1
// the second pair is (5,8) and the numbers are not consecutive.
// the third pair is (-4,-3), consecutive. Count = 2.
// the fourth pair is (7,6), also consecutive. Count = 3.
// the last element has no pair, so we ignore.
function pairs(ar){
let ans = 0
for(let i=0;i<ar.length-1;i+=2){
if(ar[i]==ar[i+1]+1||ar[i]==ar[i+1]-1){
ans+=1
}
}
return ans
}
// Complete the function howManydays. It accepts 1 parameter month, which means the month of the year. Different months have a different number of days as shown in the table below.
// Return the number of days that are in month. There is no need for input validation: month will always be greater than 0 and less than or equal to 12.
// +---------------+-------------+
// | month | days |
// +---------------+-------------+
// |1,3,5,7,8,10,12| 31 |
// +---------------+-------------+
// |4,6,9,11 | 30 |
// +---------------+-------------+
// |2 | 28 | (Do not consider the leap year)
// +---------------+-------------+