UNPKG

2.25 kBPlain TextView Raw
1import { ArrayRepeatStrategy } from './array-repeat-strategy';
2import { MapRepeatStrategy } from './map-repeat-strategy';
3import { NullRepeatStrategy } from './null-repeat-strategy';
4import { NumberRepeatStrategy } from './number-repeat-strategy';
5import { Repeat } from './repeat';
6import { SetRepeatStrategy } from './set-repeat-strategy';
7
8/**
9 * A strategy is for repeating a template over an iterable or iterable-like object.
10 */
11export interface RepeatStrategy {
12 instanceChanged(repeat: Repeat, items: any): void;
13 instanceMutated(repeat: Repeat, items: any, changes: any): void;
14 getCollectionObserver(observerLocator: any, items: any): any;
15}
16
17/**
18 * Locates the best strategy to best repeating a template over different types of collections.
19 * Custom strategies can be plugged in as well.
20 */
21export class RepeatStrategyLocator {
22
23 /**@internal*/
24 matchers: any[];
25 /**@internal*/
26 strategies: any[];
27
28 /**
29 * Creates a new RepeatStrategyLocator.
30 */
31 constructor() {
32 this.matchers = [];
33 this.strategies = [];
34
35 this.addStrategy(items => items === null || items === undefined, new NullRepeatStrategy() as RepeatStrategy);
36 this.addStrategy(items => items instanceof Array, new ArrayRepeatStrategy());
37 this.addStrategy(items => items instanceof Map, new MapRepeatStrategy());
38 this.addStrategy(items => items instanceof Set, new SetRepeatStrategy());
39 this.addStrategy(items => typeof items === 'number', new NumberRepeatStrategy() as Partial<RepeatStrategy> as RepeatStrategy);
40 }
41
42 /**
43 * Adds a repeat strategy to be located when repeating a template over different collection types.
44 * @param strategy A repeat strategy that can iterate a specific collection type.
45 */
46 addStrategy(matcher: (items: any) => boolean, strategy: RepeatStrategy) {
47 this.matchers.push(matcher);
48 this.strategies.push(strategy);
49 }
50
51 /**
52 * Gets the best strategy to handle iteration.
53 */
54 getStrategy(items: any): RepeatStrategy {
55 let matchers = this.matchers;
56
57 for (let i = 0, ii = matchers.length; i < ii; ++i) {
58 if (matchers[i](items)) {
59 return this.strategies[i];
60 }
61 }
62
63 return null;
64 }
65}