All files / util/journeys/src recentJourneys.ts

83.33% Statements 15/18
86.36% Branches 19/22
100% Functions 5/5
100% Lines 15/15

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 5415x 15x                         74x 74x 74x                   37x 37x 37x       68x     68x 64x       23x   19x   23x       23x          
const STORAGE_KEY = "overworld:recent-journeys";
const LIMIT = 5;
 
interface JourneyStop {
  locid: number;
  desc: string;
}
 
export interface RecentJourney {
  from: JourneyStop;
  to: JourneyStop;
}
 
function isJourneyStop(value: unknown): value is JourneyStop {
  Iif (!value || typeof value !== "object") return false;
  const { locid, desc } = value as Partial<JourneyStop>;
  return (
    typeof locid === "number" &&
    Number.isSafeInteger(locid) &&
    locid > 0 &&
    typeof desc === "string" &&
    Boolean(desc.trim())
  );
}
 
function isJourney(value: unknown): value is RecentJourney {
  Iif (!value || typeof value !== "object") return false;
  const { from, to } = value as Partial<RecentJourney>;
  return isJourneyStop(from) && isJourneyStop(to) && from.locid !== to.locid;
}
 
export function readRecentJourneys(): RecentJourney[] {
  const journeys: unknown = JSON.parse(
    localStorage.getItem(STORAGE_KEY) ?? "[]",
  );
  Iif (!Array.isArray(journeys)) throw new Error("Invalid recent journeys");
  return journeys.filter(isJourney).slice(0, LIMIT);
}
 
export function recordRecentJourney(from: JourneyStop, to: JourneyStop) {
  const previous = readRecentJourneys().filter(
    (journey) =>
      journey.from.locid !== from.locid || journey.to.locid !== to.locid,
  );
  const journey = {
    from: { locid: from.locid, desc: from.desc },
    to: { locid: to.locid, desc: to.desc },
  };
  localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify([journey, ...previous].slice(0, LIMIT)),
  );
}