Skip to content

Commit

Permalink
feat(query): add filter and reduce to QueryList
Browse files Browse the repository at this point in the history
Closes #4710
  • Loading branch information
vsavkin committed Oct 13, 2015
1 parent 9fc24b9 commit bfbf18d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 6 deletions.
5 changes: 0 additions & 5 deletions modules/angular2/src/core/linker/query_list.dart
Expand Up @@ -22,11 +22,6 @@ class QueryList<T> extends Object
return _results.toString();
}

List map(fn(T)) {
// Note: we need to return a list instead of iterable to match JS.
return this._results.map(fn).toList();
}

/** @internal */
void reset(List<T> newList) {
_results = newList;
Expand Down
17 changes: 16 additions & 1 deletion modules/angular2/src/core/linker/query_list.ts
Expand Up @@ -37,10 +37,25 @@ export class QueryList<T> {
get last(): T { return ListWrapper.last(this._results); }

/**
* returns a new list with the passsed in function applied to each element.
* returns a new array with the passed in function applied to each element.
*/
map<U>(fn: (item: T) => U): U[] { return this._results.map(fn); }

/**
* returns a filtered array.
*/
filter(fn: (item: T) => boolean): T[] { return this._results.filter(fn); }

/**
* returns a reduced value.
*/
reduce<U>(fn: (acc: U, item: T) => U, init: U): U { return this._results.reduce(fn, init); }

/**
* converts QueryList into an array
*/
toArray(): T[] { return ListWrapper.clone(this._results); }

[getSymbolIterator()](): any { return this._results[getSymbolIterator()](); }

toString(): string { return this._results.toString(); }
Expand Down
23 changes: 23 additions & 0 deletions modules/angular2/test/core/linker/query_list_spec.ts
Expand Up @@ -10,6 +10,7 @@ import {
fakeAsync,
tick
} from 'angular2/testing_internal';
import {IS_DART} from '../../platform';

import {MapWrapper, ListWrapper, iterateListLike} from 'angular2/src/core/facade/collection';
import {StringWrapper} from 'angular2/src/core/facade/lang';
Expand Down Expand Up @@ -46,6 +47,28 @@ export function main() {
expect(queryList.map((x) => x)).toEqual(['one', 'two']);
});

if (!IS_DART) {
it('should support filter', () => {
queryList.reset(['one', 'two']);
expect((<any>queryList).filter((x) => x == "one")).toEqual(['one']);
});

it('should support reduce', () => {
queryList.reset(["one", "two"]);
expect((<any>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo");
});

it('should support toArray', () => {
queryList.reset(["one", "two"]);
expect((<any>queryList).reduce((a, x) => a + x, "start:")).toEqual("start:onetwo");
});

it('should support toArray', () => {
queryList.reset(["one", "two"]);
expect((<any>queryList).toArray()).toEqual(["one", "two"]);
});
}

it('should support toString', () => {
queryList.reset(['one', 'two']);
var listString = queryList.toString();
Expand Down

0 comments on commit bfbf18d

Please sign in to comment.