55export function freqQuery ( queries ) {
66 const result = [ ] ;
77 const dataMap = { } ;
8+ const freqMap = { } ;
89
910 const __INITIAL__ = 0 ;
1011 const __INSERT__ = 1 ;
@@ -17,19 +18,58 @@ export function freqQuery(queries) {
1718 queries . forEach ( ( query ) => {
1819 const [ operation , data ] = query ;
1920
20- const current = dataMap ?. [ data ] ?? __INITIAL__ ;
21+ const currentFreqValue = dataMap ?. [ data ] ?? __INITIAL__ ;
2122
2223 switch ( operation ) {
2324 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+ }
2543 break ;
2644 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+ }
2870 break ;
2971 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 ] ) {
3373 result . push ( __FOUND__ ) ;
3474 } else {
3575 result . push ( __NOT_FOUND__ ) ;
0 commit comments