2
2
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/dictionaries_and_hashmaps/frequency-queries.md]]
3
3
*/
4
4
5
+ export function updateFrequency ( frequencyMap , data , currentFreq , newFreq ) {
6
+ const freqMap = frequencyMap ;
7
+
8
+ if ( newFreq > 0 ) {
9
+ if ( freqMap ?. [ newFreq ] ) {
10
+ freqMap [ newFreq ] . push ( data ) ;
11
+ } else {
12
+ freqMap [ newFreq ] = [ data ] ;
13
+ }
14
+ }
15
+
16
+ if ( freqMap ?. [ currentFreq ] ) {
17
+ freqMap [ currentFreq ] = freqMap [ currentFreq ] . filter ( ( f ) => f !== data ) ;
18
+
19
+ if ( freqMap [ currentFreq ] . length === 0 ) {
20
+ delete freqMap ?. [ currentFreq ] ;
21
+ }
22
+ }
23
+
24
+ return freqMap ;
25
+ }
26
+
5
27
export function freqQuery ( queries ) {
6
28
const result = [ ] ;
7
29
const dataMap = { } ;
@@ -18,23 +40,23 @@ export function freqQuery(queries) {
18
40
queries . forEach ( ( query ) => {
19
41
const [ operation , data ] = query ;
20
42
21
- const currentFreqValue = dataMap ?. [ data ] ?? __INITIAL__ ;
22
- let newFreqKey = currentFreqValue + 1 ;
43
+ const currentFreq = dataMap ?. [ data ] ?? __INITIAL__ ;
44
+ let newFreq = currentFreq + 1 ;
23
45
24
46
switch ( operation ) {
25
47
case __INSERT__ :
26
48
// map of values
27
- dataMap [ data ] = currentFreqValue + 1 ;
49
+ dataMap [ data ] = currentFreq + 1 ;
28
50
29
51
// map of frequencies
30
- newFreqKey = currentFreqValue + 1 ;
52
+ newFreq = currentFreq + 1 ;
31
53
break ;
32
54
case __DELETE__ :
33
55
// map of values
34
- dataMap [ data ] = Math . max ( 0 , currentFreqValue - 1 ) ;
56
+ dataMap [ data ] = Math . max ( 0 , currentFreq - 1 ) ;
35
57
36
58
// map of frequencies
37
- newFreqKey = currentFreqValue - 1 ;
59
+ newFreq = currentFreq - 1 ;
38
60
39
61
break ;
40
62
case __SELECT__ : {
@@ -50,23 +72,7 @@ export function freqQuery(queries) {
50
72
}
51
73
52
74
if ( operation === __INSERT__ || operation === __DELETE__ ) {
53
- if ( newFreqKey > 0 ) {
54
- if ( freqMap ?. [ newFreqKey ] ) {
55
- freqMap [ newFreqKey ] . push ( data ) ;
56
- } else {
57
- freqMap [ newFreqKey ] = [ data ] ;
58
- }
59
- }
60
-
61
- if ( freqMap ?. [ currentFreqValue ] ) {
62
- freqMap [ currentFreqValue ] = freqMap [ currentFreqValue ] . filter (
63
- ( f ) => f !== data
64
- ) ;
65
-
66
- if ( freqMap [ currentFreqValue ] . length === 0 ) {
67
- delete freqMap ?. [ currentFreqValue ] ;
68
- }
69
- }
75
+ updateFrequency ( freqMap , data , currentFreq , newFreq ) ;
70
76
}
71
77
} ) ;
72
78
0 commit comments