export type ComparePersonalItemState = {
had: boolean;
owned: boolean;
wanted: boolean;
};
export type ComparePersonalState = Record<
string,
ComparePersonalItemState
>;
export const emptyPersonalItemState =
(): ComparePersonalItemState => ({
had: false,
owned: false,
wanted: false
});
export const parsePersonalState = (
value: string | null
): ComparePersonalState => {
if (!value) return {};
try {
const parsed = JSON.parse(value) as unknown;
if (
!parsed ||
typeof parsed !== 'object' ||
Array.isArray(parsed)
) {
return {};
}
return Object.fromEntries(
Object.entries(parsed)
.filter(
([, state]) =>
Boolean(state) &&
typeof state === 'object' &&
!Array.isArray(state)
)
.map(([id, state]) => {
const candidate = state as Record<string, unknown>;
const owned = candidate.owned === true;
const had = !owned && candidate.had === true;
const wanted =
candidate.wanted === true ||
candidate.wishlisted === true;
return [id, { had, owned, wanted }];
})
);
} catch {
return {};
}
};
export const togglePersonalItemState = (
state: ComparePersonalState,
itemId: string,
action: keyof ComparePersonalItemState
): ComparePersonalState => {
const current = state[itemId] ?? emptyPersonalItemState();
const next = { ...current, [action]: !current[action] };
if (next[action] && action === 'owned') {
next.had = false;
}
if (next[action] && action === 'had') {
next.owned = false;
}
return { ...state, [itemId]: next };
};
Browse the implementation files for TPUs Comparison.