/
FeatureFileMap.ts
57 lines (44 loc) · 1.47 KB
/
FeatureFileMap.ts
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
import { Constructor } from '../constructables';
import { ItemNotFoundError } from './errors';
/**
* @private
*/
export class FeatureFileMap {
constructor(private readonly map: { [line: number]: object } = {}) {
}
set(item: object) {
return ({
onLine: (line: number): FeatureFileMap => {
this.map[line] = item;
return this;
},
});
}
get<T>(type: Constructor<T>) {
return ({
onLine: (line: number): T => {
const found = this.map[line];
if (! found) {
throw new ItemNotFoundError(`Nothing was found on line ${ line }`);
}
if (! (found instanceof type)) {
throw new ItemNotFoundError(`Item on line ${ line } is a ${ found.constructor.name }, not a ${ type.name }`);
}
return found as T;
},
});
}
getFirst<T>(type: Constructor<T>): T {
const
items = Object.keys(this.map).map(line => this.map[line]),
found = items.find(value => value instanceof type);
if (! found) {
const existingTypes = items.map(item => item.constructor.name).join(', ') || 'no items.';
throw new ItemNotFoundError(`Didn't find any ${ type.name } amongst ${ existingTypes }`);
}
return found;
}
size() {
return Object.keys(this.map).length;
}
}