Skip to content

Commit

Permalink
feat(collection-strategy-locator): add strategies
Browse files Browse the repository at this point in the history
Fixes #95
  • Loading branch information
EisenbergEffect committed Nov 9, 2015
1 parent 3d6d35d commit 60b8067
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/collection-strategy-locator.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,28 @@ import {NumberStrategy} from './number-strategy';
export class CollectionStrategyLocator {
constructor(container) {
this.container = container;
this.strategies = [];
this.matchers = [];

this.addStrategy(ArrayCollectionStrategy, items => items instanceof Array);
this.addStrategy(MapCollectionStrategy, items => items instanceof Map);
this.addStrategy(NumberStrategy, items => typeof items === 'number');
}

addStrategy(collectionStrategy: Function, matcher: (items: any) => boolean) {
this.strategies.push(collectionStrategy);
this.matchers.push(matcher);
}

getStrategy(items) {
let strategy;
if (items instanceof Array) {
strategy = this.container.get(ArrayCollectionStrategy);
} else if (items instanceof Map) {
strategy = this.container.get(MapCollectionStrategy);
} else if ((typeof items === 'number')) {
strategy = this.container.get(NumberStrategy);
} else {
throw new Error('Object in "repeat" must be of type Array, Map or Number');
getStrategy(items: any): CollectionStrategy {
let matchers = this.matchers;

for (let i = 0, ii = matchers.length; i < ii; ++i) {
if (matchers[i](items)) {
return this.container.get(this.strategies[i]);
}
}

return strategy;
throw new Error('Object in "repeat" must have a valid collection strategy.');
}
}

1 comment on commit 60b8067

@martingust
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice!

Please sign in to comment.