# All files / stores favorites.js

100% Statements 20/20
100% Branches 6/6
100% Functions 8/8
100% Lines 19/19

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

    3x

    22x
    22x

    1x

    10x

    3x
    22x

    34x

    10x
    10x
    8x
    8x

    3x
    2x

    3x
    1x
    1x

    2x
    2x

     import { defineStore } from "pinia";

    const STORAGE_KEY = "sh_fav_areas";

    function readFavorites() {
      try {
        return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]").map(String);
      } catch (_) {
        return [];
      }
    }

    function writeFavorites(ids) {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(ids.map(String)));
    }

    export const useFavoritesStore = defineStore("favorites", {
      state: () => ({
        ids: readFavorites(),
      }),

      actions: {
        has(id) {
          return this.ids.includes(String(id));
        },

        add(id) {
          const nextId = String(id);
          if (!this.ids.includes(nextId)) {
            this.ids.push(nextId);
            writeFavorites(this.ids);
          }
        },

        remove(id) {
          this.ids = this.ids.filter((item) => item !== String(id));
          writeFavorites(this.ids);
        },

        toggle(id) {
          if (this.has(id)) {
            this.remove(id);
            return false;
          }

          this.add(id);
          return true;
        },
      },
    });