5
5
export function freqQuery ( queries ) {
6
6
const result = [ ] ;
7
7
const dataMap = { } ;
8
+ const freqMap = { } ;
8
9
9
10
const __INITIAL__ = 0 ;
10
11
const __INSERT__ = 1 ;
@@ -17,19 +18,58 @@ export function freqQuery(queries) {
17
18
queries . forEach ( ( query ) => {
18
19
const [ operation , data ] = query ;
19
20
20
- const current = dataMap ?. [ data ] ?? __INITIAL__ ;
21
+ const currentFreqValue = dataMap ?. [ data ] ?? __INITIAL__ ;
21
22
22
23
switch ( operation ) {
23
24
case __INSERT__ :
24
- dataMap [ data ] = current + 1 ;
25
+ {
26
+ // map of values
27
+ dataMap [ data ] = currentFreqValue + 1 ;
28
+
29
+ // map of frequencies
30
+ const newFreqKey = currentFreqValue + 1 ;
31
+ if ( freqMap ?. [ newFreqKey ] ) {
32
+ freqMap [ newFreqKey ] . push ( data ) ;
33
+ } else {
34
+ freqMap [ newFreqKey ] = [ data ] ;
35
+ }
36
+
37
+ if ( freqMap ?. [ currentFreqValue ] ) {
38
+ freqMap [ currentFreqValue ] = freqMap [ currentFreqValue ] . filter (
39
+ ( f ) => f !== data
40
+ ) ;
41
+ }
42
+ }
25
43
break ;
26
44
case __DELETE__ :
27
- dataMap [ data ] = Math . max ( 0 , current - 1 ) ;
45
+ {
46
+ // map of values
47
+ dataMap [ data ] = Math . max ( 0 , currentFreqValue - 1 ) ;
48
+
49
+ // map of frequencies
50
+ const newFreqKey = currentFreqValue - 1 ;
51
+
52
+ if ( newFreqKey > 0 ) {
53
+ if ( freqMap ?. [ newFreqKey ] ) {
54
+ freqMap [ newFreqKey ] . push ( data ) ;
55
+ } else {
56
+ freqMap [ newFreqKey ] = [ data ] ;
57
+ }
58
+ }
59
+
60
+ if ( freqMap ?. [ currentFreqValue ] ) {
61
+ freqMap [ currentFreqValue ] = freqMap [ currentFreqValue ] . filter (
62
+ ( f ) => f !== data
63
+ ) ;
64
+
65
+ if ( freqMap [ currentFreqValue ] . length === 0 ) {
66
+ delete freqMap ?. [ currentFreqValue ] ;
67
+ }
68
+ }
69
+ }
28
70
break ;
29
71
case __SELECT__ : {
30
- // const dataValues = Object.values(dataMap);
31
- const uniqueDatavalues = new Set ( Object . values ( dataMap ) ) ;
32
- if ( uniqueDatavalues . has ( data ) ) {
72
+ if ( freqMap ?. [ data ] ) {
33
73
result . push ( __FOUND__ ) ;
34
74
} else {
35
75
result . push ( __NOT_FOUND__ ) ;
0 commit comments