aboutsummaryrefslogtreecommitdiff
path: root/src/data/StopDataProvider.ts
blob: 6245e7a3fb50db368f1a127a7f89f39b6187252e (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import stops from './stops.json';

export interface CachedStopList {
	timestamp: number;
	data: Stop[];
}

export interface Stop {
	stopId: number
	name: string;
	latitude?: number;
	longitude?: number;
	lines: string[];
	favourite?: boolean;
}

export class StopDataProvider {
	async getStops(): Promise<Stop[]> {
		const rawFavouriteStops = localStorage.getItem('favouriteStops');
		let favouriteStops: number[] = [];
		if (rawFavouriteStops) {
			favouriteStops = JSON.parse(rawFavouriteStops) as number[];
		}

		return stops.map((stop: Stop) => {
			return {
				...stop,
				favourite: favouriteStops.includes(stop.stopId)
			};
		});	
	}

	addFavourite(stopId: number) {
		const rawFavouriteStops = localStorage.getItem('favouriteStops');
		let favouriteStops: number[] = [];
		if (rawFavouriteStops) {
			favouriteStops = JSON.parse(rawFavouriteStops) as number[];
		}

		if (!favouriteStops.includes(stopId)) {
			favouriteStops.push(stopId);
			localStorage.setItem('favouriteStops', JSON.stringify(favouriteStops));
		}
	}

	removeFavourite(stopId: number) {
		const rawFavouriteStops = localStorage.getItem('favouriteStops');
		let favouriteStops: number[] = [];
		if (rawFavouriteStops) {
			favouriteStops = JSON.parse(rawFavouriteStops) as number[];
		}

		const newFavouriteStops = favouriteStops.filter(id => id !== stopId);
		localStorage.setItem('favouriteStops', JSON.stringify(newFavouriteStops));
	}

	isFavourite(stopId: number): boolean {
		const rawFavouriteStops = localStorage.getItem('favouriteStops');
		if (rawFavouriteStops) {
			const favouriteStops = JSON.parse(rawFavouriteStops) as number[];
			return favouriteStops.includes(stopId);
		}
		return false;
	}

	RECENT_STOPS_LIMIT = 10;

	pushRecent(stopId: number) {
		const rawRecentStops = localStorage.getItem('recentStops');
		let recentStops: Set<number> = new Set();
		if (rawRecentStops) {
			recentStops = new Set(JSON.parse(rawRecentStops) as number[]);
		}

		recentStops.add(stopId);
		if (recentStops.size > this.RECENT_STOPS_LIMIT) {
			const iterator = recentStops.values();
			recentStops.delete(iterator.next().value);
		}

		localStorage.setItem('recentStops', JSON.stringify(Array.from(recentStops)));
	}

	getRecent(): number[] {
		const rawRecentStops = localStorage.getItem('recentStops');
		if (rawRecentStops) {
			return JSON.parse(rawRecentStops) as number[];
		}
		return [];
	}
}