@@ -14,27 +14,33 @@ export const $recentSearches = map({});
1414/**
1515 * Add search term to recent search history
1616 * @param {SearchedItem } item
17- *
18- * @todo implement logic to allow holding maximum of 5 words by removing older words when new a one gets added
1917 */
2018export function $addToRecentSearchesFn ( { word, url } ) {
21- // Re-initialise the state with current localStorage value
22- $recentSearches . set ( { ...JSON . parse ( localStorage . getItem ( "jargons.dev:recent_searches" ) ) } ) ;
19+ // Re-initialise the state with the current localStorage value
20+ const storedSearches = JSON . parse ( localStorage . getItem ( "jargons.dev:recent_searches" ) ) || { } ;
21+ $recentSearches . set ( { ...storedSearches } ) ;
2322
2423 const lowercaseKey = word . toLowerCase ( ) ;
2524 const key = lowercaseKey . includes ( " " ) ? lowercaseKey . split ( " " ) . join ( "-" ) : lowercaseKey ;
26- const isInRecentSearch = $recentSearches . get ( ) [ key ] ;
27-
28- if ( ! isInRecentSearch ) {
29- const recentSearchesCopy = $recentSearches . get ( ) ;
30- recentSearchesCopy [ key ] = {
31- word,
32- url
33- } ;
34- $recentSearches . set ( { ...recentSearchesCopy } ) ;
35- } else {
36- return ;
25+
26+ const recentSearchesCopy = $recentSearches . get ( ) ;
27+
28+ // Remove Search Entry If it already exists
29+ if ( recentSearchesCopy [ key ] ) {
30+ delete recentSearchesCopy [ key ] ;
31+ }
32+
33+ const searchEntries = Object . entries ( recentSearchesCopy ) ;
34+
35+ // Remove one Search Entry when list reach a count of 5
36+ if ( searchEntries . length >= 5 ) {
37+ searchEntries . pop ( ) ;
3738 }
38-
39- localStorage . setItem ( "jargons.dev:recent_searches" , JSON . stringify ( $recentSearches . get ( ) ) ) ;
39+
40+ const updatedEntries = [ [ key , { word, url } ] , ...searchEntries ] ;
41+
42+ const updatedSearches = Object . fromEntries ( updatedEntries ) ;
43+ $recentSearches . set ( updatedSearches ) ;
44+
45+ localStorage . setItem ( "jargons.dev:recent_searches" , JSON . stringify ( updatedSearches ) ) ;
4046}
0 commit comments