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 57 58 594x         4x 60x 60x     60x 60x                   102x 102x             99x     189x           3x               241x     60x                  
import { log } from "../api/client"
import { DefaultState } from "./state"
 
type Items = NonNullable<DefaultState["history"]>
 
export function createHistory(size: number) {
    const localStorageKey = "nostoAutocomplete:history"
    let items = get()
 
    function get(): Items {
        try {
            return (
                JSON.parse(localStorage.getItem(localStorageKey) ?? "[]") ?? []
            )
        } catch (err) {
            log("Could not get history items.", err, "error")
            return []
        }
    }
 
    function set(data: Items) {
        try {
            localStorage.setItem(localStorageKey, JSON.stringify(data))
        } catch (err) {
            log("Could not set history items.", err, "error")
        }
    }
 
    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>