-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaScriptPractice.js
More file actions
12856 lines (8803 loc) · 370 KB
/
Copy pathJavaScriptPractice.js
File metadata and controls
12856 lines (8803 loc) · 370 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
// Numbers ending with zeros are boring.
// They might be fun in your world, but not here.
// Get rid of them. Only the ending ones.
// 1450 -> 145
// 960000 -> 96
// 1050 -> 105
// -1050 -> -105
// 0 -> 0
// Note: Zero should be left as it is.
function noBoringZeros(n) {
while(n%10===0&&n!=0){
n= n/10
}
return n
}
// Create a function that accepts a string argument and returns an array of strings with each letter from the input string being rotated to the end.
// Examples:
// "Hello" --> ["elloH", "lloHe", "loHel", "oHell", "Hello"]
// Note:
// The original string should be included in the output array.
// The order matters. Each element of the output array should be the rotated version of the previous element.
// The output array SHOULD be the same length as the input string.
// The function should return an empty array with an empty string ('') as input.
function rotate(str){
let ans = []
for(let i=1; i<=str.length; i++){
ans.push(str.split('').reverse().join('').slice(0,str.length-i).split('').reverse().join('')+str.slice(0,i))
}
return ans
}
// Write a function that combines two arrays by alternatingly taking elements from each array in turn.
// Examples:
// [a, b, c, d, e], [1, 2, 3, 4, 5] becomes [a, 1, b, 2, c, 3, d, 4, e, 5]
// [1, 2, 3], [a, b, c, d, e, f] becomes [1, a, 2, b, 3, c, d, e, f]
// Points:
// The arrays may be of different lengths, with at least one character/digit.
// One array will be of string characters (in lower case, a-z), a second of integers (all positive starting at 1).
function mergeArrays(a, b) {
let p1 = 0
let p2 = 0
let ans =[]
while(p1<a.length||p2<b.length){
if(p1<a.length){
ans.push(a[p1])
p1++
}
if(p2<b.length){
ans.push(b[p2])
p2++
}
}
return ans
}
// Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n3 n^3 n3, the cube above will have volume of (n−1)3 (n-1)^3 (n−1)3 and so on until the top which will have a volume of 13 1^3 13.
// You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?
// The parameter of the function findNb (find_nb, find-nb, findNb, ...) will be an integer m and you have to return the integer n such as n3+(n−1)3+(n−2)3+...+13=m n^3 + (n-1)^3 + (n-2)^3 + ... + 1^3 = m n3+(n−1)3+(n−2)3+...+13=m if such a n exists or -1 if there is no such n.
// Examples:
// findNb(1071225) --> 45
// findNb(91716553919377) --> -1
function findNb(m) {
let p1 = 0
let ans = 0
while (p1<m){
ans+=1
p1+=Math.pow(ans,3)
}
return p1===m? ans:-1
}
// Write a function that takes an input string of lowercase letters and returns true/false depending on whether the string is in alphabetical order or not.
// Examples (input -> output)
// "kata" -> false ('a' comes after 'k')
// "ant" -> true (all characters are in alphabetical order)
function alphabetic(s) {
let ans = 0
for(let i=0;i<s.length-1;i++){
if(s.charCodeAt(i)>s.charCodeAt(i+1)){
return false
}
}
return true
}
//or
function alphabetic(s) {
return s === [...s].sort().join('')
}
// Given a varying number of integer arguments, return the digits that are not present in any of them.
// Example:
// [12, 34, 56, 78] => "09"
// [2015, 8, 26] => "3479"
// Note: the digits in the resulting string should be sorted.
function unusedDigits(...params) {
let p1 = params.join('').split('').sort()
let ans = []
for(let i=0;i<=9;i++){
if(!p1.includes(i.toString())){
ans.push(i)
}
}
return ans.join('')
}
// Write a function that takes an integer num (num >= 0) and inserts dashes ('-') between each two odd digits in num.
// Examples
// 454793 ---> "4547-9-3"
// 0 ---> "0"
// 1 ---> "1"
// 13579 ---> "1-3-5-7-9"
// 86420 ---> "86420"
function insertDash(num) {
let p1 = num.toString().split('')
let ans = []
for(let i=0;i<p1.length-1;i++){
let p2 = Number(p1[i])
let p3 = Number(p1[i+1])
ans.push(p1[i])
if(p2%2!==0&&p3%2!==0){
ans.push('-')
}
}
ans.push(p1[p1.length - 1])
return ans.join('')
}
// Complete the function which takes a non-zero integer as its argument.
// If the integer is divisible by 3, return the string "Java".
// If the integer is divisible by 3 and divisible by 4, return the string "Coffee"
// If one of the condition above is true and the integer is even, add "Script" to the end of the string.
// If none of the condition is true, return the string "mocha_missing!"
// Examples
// 1 --> "mocha_missing!"
// 3 --> "Java"
// 6 --> "JavaScript"
// 12 --> "CoffeeScript"
function caffeineBuzz(n) {
let ans = ""
if(n%3===0&&n%4===0){
ans+="Coffee"
if(n%2===0){
ans+='Script'
return ans
}
return ans
}
if(n%3===0){
ans+="Java"
if(n%2===0){
ans+='Script'
return ans
}
return ans
}
return "mocha_missing!"
}
// Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.
// The method should return an array of sentences declaring the state or country and its capital.
// Examples
// state_capitals = [{state: 'Maine', capital: 'Augusta'}]
// capital(state_capitals)[0] // returns "The capital of Maine is Augusta"
// country_capitals = [{'country' : 'Spain', 'capital' : 'Madrid'}]
// capital(country_capitals)[0] // returns "The capital of Spain is Madrid"
// mixed_capitals: [{"state" : 'Maine', capital: 'Augusta'}, {country: 'Spain', "capital" : "Madrid"}]
// capital(mixed_capitals)[1] // returns "The capital of Spain is Madrid"
function capital(capitals) {
return capitals.map(({ state, country, capital }) => `The capital of ${state ? state : country} is ${capital}`);
}
// i is the imaginary unit, it is defined by i²=−1i² = -1i²=−1, therefore it is a solution to x²+1=0x² + 1 = 0x²+1=0.
// Your Task
// Complete the function pofi that returns iii to the power of a given non-negative integer in its simplest form, as a string (answer may contain iii).
function pofi(n) {
const powers = ["1", "i", "-1", "-i"]
return powers[n % 4]
}
// Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located.
// This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output -1.
// Examples:
// oddOne([2,4,6,7,10]) // => 3
// oddOne([2,16,98,10,13,78]) // => 4
// oddOne([4,-8,98,-12,-7,90,100]) // => 4
// oddOne([2,4,6,8]) // => -1
function oddOne(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
return i
}
}
return -1
}
// There is an object/class already created called MrFreeze. Mark this object as frozen so that no other changes can be made to it.
// mark the MrFreeze object instance as frozen
Object.freeze(MrFreeze)
// Your task is to complete the function which takes a string, and returns an array with all possible rotations of the given string, in uppercase.
// Example
// scrollingText("codewars") should return:
// [ "CODEWARS",
// "ODEWARSC",
// "DEWARSCO",
// "EWARSCOD",
// "WARSCODE",
// "ARSCODEW"
// "RSCODEWA",
// "SCODEWAR" ]
function scrollingText(text){
let p1 = text.toUpperCase()
let ans = []
for (let i = 0; i < text.length; i++) {
ans.push(p1.slice(i) + p1.slice(0, i));
}
return ans
}
// The Stanton measure of an array is defined as follows:
// Let n be the number of times the value 1 appears in the array.
// The Stanton measure is then the number of times n appears in the array.
// Task
// Write a function that takes an integer array and returns its Stanton measure.
// Examples
// For [1, 4, 3, 2, 1, 2, 3, 2]:
// 1 appears 2 times → 2 appears 3 times → Stanton measure = 3.
// For [1, 4, 1, 2, 11, 2, 3, 1]:
// 1 appears 3 times → 3 appears 1 time → Stanton measure = 1.
function stantonMeasure(a){
let p1 = a.filter((x)=>x===1).length
let ans = a.filter((x)=>x===p1).length
return ans
}
// You will be given a string representing the garden such as:
// garden = 'gravel gravel gravel gravel snail gravel gravel rock gravel slug spider gravel gravel gravel gravel spider gravel rock gravel gravel'
// Rake out any items that are not a rock or gravel and replace them with gravel such that:
// garden = 'slug spider rock gravel gravel gravel gravel gravel gravel gravel'
// Returns a string with all items except a rock or gravel replaced with gravel:
// garden = 'gravel gravel rock gravel gravel gravel gravel gravel gravel gravel'
function rakeGarden(garden) {
return garden.split(' ').map((x)=>{
if(x!='rock' && x!='gravel'){
return x='gravel'
}else{
return x
}
}).join(' ')
}
// 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
}