All files / src/utils history.ts

72.22% Statements 13/18
78.57% Branches 11/14
77.77% Functions 7/9
76.47% Lines 13/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 575x         5x 61x 61x     61x 61x               101x 101x             98x 187x               3x               241x     61x                  
import { logger } from "../api/client"
import { DefaultState } from "./state"
 
type Items = NonNullable<DefaultState["history"]>
 
export function createHistory(size: number) {
  const localStorageKey = "nosto:autocomplete:history"
  let items = get()
 
  function get(): Items {
    try {
      return JSON.parse(localStorage.getItem(localStorageKey) ?? "[]") ?? []
    } catch (err) {
      logger.error("Could not get history items.", err)
      return []
    }
  }
 
  function set(data: Items) {
    try {
      localStorage.setItem(localStorageKey, JSON.stringify(data))
    } catch (err) {
      logger.error("Could not set history items.", err)
    }
  }
 
  function add(item: string) {
    set(
      (items = [{ item }, ...(items?.filter(v => v.item !== item) || [])].slice(
        0,
        size
      ))
    )
  }
 
  function clear() {
    set((items = []))
  }
 
  function remove(item: string) {
    set((items = items.filter(v => v.item !== item)))
  }
 
  function getItems() {
    return items
  }
 
  return {
    add,
    clear,
    remove,
    getItems,
  }
}
 
export type History = ReturnType<typeof createHistory>