Appliances Comparison Source Code

Browse the implementation files for Appliances Comparison.
personal-state.ts typescript
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 };
};

Description

Browse the implementation files for Appliances Comparison.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools

Don't forget to set a bookmark for tool.io!
Privacy | Imprint | Cookies