The Purr Market pet shop shows recent searches under its search box: a customer clicks one instead of typing "kitten food" for the tenth time. The list has to survive a page reload.
Write rememberSearch(query). It:
- reads the list from localStorage (opens in a new tab) under the key
"recent-searches" (a JSON array of strings); - trims spaces around the query; if the query is empty, it changes nothing and just returns the current list;
- puts the query first; if it was already there, the old copy is removed (the query "moves up");
- keeps at most 5 queries;
- saves the list back as JSON and returns it.
No key means an empty list. If storage holds junk (not JSON, or not an array), start with an empty list too: the page mustn't crash. Before every test storage is empty (or holds whatever the test put there).