refactor(ListWrapper): drop filter, find, reduce & any

Closes #5152
This commit is contained in:
Victor Berchet 2015-10-09 09:07:58 -07:00
parent e667ad3e6b
commit 0dcca1a28e
30 changed files with 66 additions and 98 deletions

View File

@ -31,16 +31,17 @@ function _find(control: AbstractControl, path: Array<string | number>| string) {
}
if (path instanceof Array && ListWrapper.isEmpty(path)) return null;
return ListWrapper.reduce(<Array<string | number>>path, (v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
var index = <number>name;
return isPresent(v.at(index)) ? v.at(index) : null;
} else {
return null;
}
}, control);
return (<Array<string | number>>path)
.reduce((v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
var index = <number>name;
return isPresent(v.at(index)) ? v.at(index) : null;
} else {
return null;
}
}, control);
}
function toObservable(r: any): Observable<any> {
@ -480,7 +481,7 @@ export class ControlArray extends AbstractControl {
/** @internal */
_anyControlsHaveStatus(status: string): boolean {
return ListWrapper.any(this.controls, c => c.status == status);
return this.controls.some(c => c.status == status);
}

View File

@ -80,7 +80,7 @@ export class Validators {
*/
static compose(validators: Function[]): Function {
if (isBlank(validators)) return null;
var presentValidators = ListWrapper.filter(validators, isPresent);
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null;
return function(control: modelModule.AbstractControl) {
@ -90,7 +90,7 @@ export class Validators {
static composeAsync(validators: Function[]): Function {
if (isBlank(validators)) return null;
let presentValidators = ListWrapper.filter(validators, isPresent);
var presentValidators = validators.filter(isPresent);
if (presentValidators.length == 0) return null;
return function(control: modelModule.AbstractControl) {
@ -109,7 +109,7 @@ function _executeValidators(control: modelModule.AbstractControl, validators: Fu
}
function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} {
var res = ListWrapper.reduce(arrayOfErrors, (res, errors) => {
var res = arrayOfErrors.reduce((res, errors) => {
return isPresent(errors) ? StringMapWrapper.merge(<any>res, <any>errors) : res;
}, {});
return StringMapWrapper.isEmpty(res) ? null : res;

View File

@ -60,8 +60,7 @@ export class RuntimeMetadataResolver {
inputs: dirMeta.inputs,
outputs: dirMeta.outputs,
host: dirMeta.host,
lifecycleHooks: ListWrapper.filter(LIFECYCLE_HOOKS_VALUES,
hook => hasLifecycleHook(hook, directiveType))
lifecycleHooks: LIFECYCLE_HOOKS_VALUES.filter(hook => hasLifecycleHook(hook, directiveType))
});
this._cache.set(directiveType, meta);
}

View File

@ -4,7 +4,6 @@ import {
CompileTemplateMetadata
} from './directive_metadata';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import {BaseException} from 'angular2/src/facade/exceptions';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
@ -55,9 +54,9 @@ export class TemplateNormalizer {
var allStyles = templateMeta.styles.concat(visitor.styles);
var allStyleAbsUrls =
ListWrapper.filter(visitor.styleUrls, isStyleUrlResolvable)
visitor.styleUrls.filter(isStyleUrlResolvable)
.map(url => this._urlResolver.resolve(templateAbsUrl, url))
.concat(ListWrapper.filter(templateMeta.styleUrls, isStyleUrlResolvable)
.concat(templateMeta.styleUrls.filter(isStyleUrlResolvable)
.map(url => this._urlResolver.resolve(directiveType.moduleUrl, url)));
var allResolvedStyles = allStyles.map(style => {

View File

@ -227,7 +227,7 @@ class TemplateParseVisitor implements HtmlAstVisitor {
elementNgContentIndex, element.sourceInfo);
} else {
this._assertOnlyOneComponent(directives, element.sourceInfo);
var elementExportAsVars = ListWrapper.filter(vars, varAst => varAst.value.length === 0);
var elementExportAsVars = vars.filter(varAst => varAst.value.length === 0);
parsedElement =
new ElementAst(nodeName, attrs, elementProps, events, elementExportAsVars, directives,
children, elementNgContentIndex, element.sourceInfo);

View File

@ -120,9 +120,8 @@ function _mayBeAddRecord(record: ProtoRecord, dstRecords: ProtoRecord[], exclude
*/
function _findFirstMatch(record: ProtoRecord, dstRecords: ProtoRecord[],
excludedIdxs: number[]): ProtoRecord {
return ListWrapper.find(
dstRecords,
// TODO(vicb): optimize notReusableIndexes.indexOf (sorted array)
return dstRecords.find(
// TODO(vicb): optimize excludedIdxs.indexOf (sorted array)
rr => excludedIdxs.indexOf(rr.selfIndex) == -1 && rr.mode !== RecordType.DirectiveLifecycle &&
_haveSameDirIndex(rr, record) && rr.mode === record.mode &&
looseIdentical(rr.funcOrValue, record.funcOrValue) &&

View File

@ -180,7 +180,7 @@ export class CodegenNameUtil {
* Generates statements destroying all pipe variables.
*/
genPipeOnDestroy(): string {
return ListWrapper.filter(this._records, (r) => { return r.isPipeRecord(); })
return this._records.filter(r => r.isPipeRecord())
.map(r => `${this._utilName}.callPipeOnDestroy(${this.getPipeName(r.selfIndex)});`)
.join('\n');
}

View File

@ -71,7 +71,7 @@ export class IterableDiffers {
}
find(iterable: Object): IterableDifferFactory {
var factory = ListWrapper.find(this.factories, f => f.supports(iterable));
var factory = this.factories.find(f => f.supports(iterable));
if (isPresent(factory)) {
return factory;
} else {

View File

@ -71,7 +71,7 @@ export class KeyValueDiffers {
}
find(kv: Object): KeyValueDifferFactory {
var factory = ListWrapper.find(this.factories, f => f.supports(kv));
var factory = this.factories.find(f => f.supports(kv));
if (isPresent(factory)) {
return factory;
} else {

View File

@ -101,8 +101,7 @@ export class DynamicChangeDetector extends AbstractChangeDetector<any> {
/** @internal */
_matchingEventBindings(eventName: string, elIndex: number): EventBinding[] {
return ListWrapper.filter(this._eventBindings,
eb => eb.eventName == eventName && eb.elIndex === elIndex);
return this._eventBindings.filter(eb => eb.eventName == eventName && eb.elIndex === elIndex);
}
hydrateDirectives(directives: any): void {

View File

@ -70,9 +70,9 @@ export abstract class DebugElement {
* @return {DebugElement[]}
*/
queryAll(predicate: Predicate<DebugElement>, scope: Function = Scope.all): DebugElement[] {
var elementsInScope = scope(this);
var elementsInScope: any[] = scope(this);
return ListWrapper.filter(elementsInScope, predicate);
return elementsInScope.filter(predicate);
}
}

View File

@ -630,7 +630,7 @@ function _constructDependencies(factoryFunction: Function, dependencies: any[]):
function _dependenciesFor(typeOrFunc): Dependency[] {
var params = reflector.parameters(typeOrFunc);
if (isBlank(params)) return [];
if (ListWrapper.any(params, (p) => isBlank(p))) {
if (params.some(isBlank)) {
throw new NoAnnotationError(typeOrFunc, params);
}
return params.map((p: any[]) => _extractToken(typeOrFunc, p, params));

View File

@ -5,7 +5,6 @@ import {Injectable} from 'angular2/src/core/di';
import {Type, isBlank, stringify} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {ListWrapper} from 'angular2/src/facade/collection';
import {reflector} from 'angular2/src/core/reflection/reflection';
import {CompiledHostTemplate} from 'angular2/src/core/linker/template_commands';
@ -31,7 +30,7 @@ export class Compiler_ extends Compiler {
compileInHost(componentType: Type): Promise<ProtoViewRef> {
var metadatas = reflector.annotations(componentType);
var compiledHostTemplate = ListWrapper.find(metadatas, _isCompiledHostTemplate);
var compiledHostTemplate = metadatas.find(_isCompiledHostTemplate);
if (isBlank(compiledHostTemplate)) {
throw new BaseException(

View File

@ -35,7 +35,7 @@ export class DirectiveResolver {
resolve(type: Type): DirectiveMetadata {
var typeMetadata = reflector.annotations(resolveForwardRef(type));
if (isPresent(typeMetadata)) {
var metadata = ListWrapper.find(typeMetadata, _isDirectiveMetadata);
var metadata = typeMetadata.find(_isDirectiveMetadata);
if (isPresent(metadata)) {
var propertyMetadata = reflector.propMetadata(type);
return this._mergeWithPropertyMetadata(metadata, propertyMetadata);

View File

@ -120,14 +120,14 @@ export class DirectiveDependency extends Dependency {
}
/** @internal */
static _attributeName(properties): string {
var p = <AttributeMetadata>ListWrapper.find(properties, (p) => p instanceof AttributeMetadata);
static _attributeName(properties: any[]): string {
var p = <AttributeMetadata>properties.find(p => p instanceof AttributeMetadata);
return isPresent(p) ? p.attributeName : null;
}
/** @internal */
static _query(properties): QueryMetadata {
return <QueryMetadata>ListWrapper.find(properties, (p) => p instanceof QueryMetadata);
static _query(properties: any[]): QueryMetadata {
return <QueryMetadata>properties.find(p => p instanceof QueryMetadata);
}
}

View File

@ -1,6 +1,5 @@
import {resolveForwardRef, Injectable} from 'angular2/src/core/di';
import {Type, isPresent, stringify} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import {BaseException} from 'angular2/src/facade/exceptions';
import {PipeMetadata} from 'angular2/src/core/metadata';
import {reflector} from 'angular2/src/core/reflection/reflection';
@ -24,7 +23,7 @@ export class PipeResolver {
resolve(type: Type): PipeMetadata {
var metas = reflector.annotations(resolveForwardRef(type));
if (isPresent(metas)) {
var annotation = ListWrapper.find(metas, _isPipeMetadata);
var annotation = metas.find(_isPipeMetadata);
if (isPresent(annotation)) {
return annotation;
}

View File

@ -7,7 +7,6 @@ import {
ConcreteType
} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {ListWrapper} from 'angular2/src/facade/collection';
import {GetterFn, SetterFn, MethodFn} from './types';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -88,9 +87,9 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
var result;
if (typeof paramTypes === 'undefined') {
result = ListWrapper.createFixedSize(paramAnnotations.length);
result = new Array(paramAnnotations.length);
} else {
result = ListWrapper.createFixedSize(paramTypes.length);
result = new Array(paramTypes.length);
}
for (var i = 0; i < result.length; i++) {
@ -123,7 +122,10 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
return this._zipTypesAndAnnotaions(paramTypes, paramAnnotations);
}
}
return ListWrapper.createFixedSize((<any>typeOrFunc).length);
// The array has to be filled with `undefined` because holes would be skipped by `some`
let parameters = new Array((<any>typeOrFunc.length));
parameters.fill(undefined);
return parameters;
}
annotations(typeOrFunc: Type): any[] {

View File

@ -54,7 +54,7 @@ export class Reflector {
throw new BaseException('Usage tracking is disabled');
}
var allTypes = MapWrapper.keys(this._injectableInfo);
return ListWrapper.filter(allTypes, (key) => { return !SetWrapper.has(this._usedKeys, key); });
return allTypes.filter(key => !SetWrapper.has(this._usedKeys, key));
}
registerFunction(func: Function, funcInfo: ReflectionInfo): void {

View File

@ -108,25 +108,16 @@ class ListWrapper {
new List.generate(size, (_) => null, growable: true);
static bool contains(List m, k) => m.contains(k);
static List filter(List list, bool fn(item)) => list.where(fn).toList();
static int indexOf(List list, value, [int startIndex = 0]) =>
list.indexOf(value, startIndex);
static int lastIndexOf(List list, value, [int startIndex = null]) =>
list.lastIndexOf(value, startIndex == null ? list.length : startIndex);
static find(List list, bool fn(item)) =>
list.firstWhere(fn, orElse: () => null);
static bool any(List list, bool fn(item)) => list.any(fn);
static void forEachWithIndex(List list, fn(item, index)) {
for (var i = 0; i < list.length; ++i) {
fn(list[i], i);
}
}
static reduce(List list, fn(a, b), init) {
return list.fold(init, fn);
}
static first(List list) => list.isEmpty ? null : list.first;
static last(List list) => list.isEmpty ? null : list.last;
static List reversed(List list) => list.reversed.toList();

View File

@ -187,27 +187,9 @@ export class ListWrapper {
if (!array || array.length == 0) return null;
return array[array.length - 1];
}
static find<T>(list: T[], pred: Predicate<T>): T {
for (var i = 0; i < list.length; ++i) {
if (pred(list[i])) return list[i];
}
return null;
}
static indexOf<T>(array: T[], value: T, startIndex: number = 0): number {
return array.indexOf(value, startIndex);
}
static reduce<T, E>(list: T[],
fn: (accumValue: E, currentValue: T, currentIndex: number, array: T[]) => E,
init: E): E {
return list.reduce(fn, init);
}
static filter<T>(array: T[], pred: Predicate<T>): T[] { return array.filter(pred); }
static any(list: any[], pred: Function): boolean {
for (var i = 0; i < list.length; ++i) {
if (pred(list[i])) return true;
}
return false;
}
static contains<T>(list: T[], el: T): boolean { return list.indexOf(el) !== -1; }
static reversed<T>(array: T[]): T[] {
var a = ListWrapper.clone(array);

View File

@ -526,10 +526,10 @@ class ChildRouter extends Router {
* Returns: ['', 'a', 'b', {c: 2}]
*/
function splitAndFlattenLinkParams(linkParams: any[]): any[] {
return ListWrapper.reduce(linkParams, (accumulation, item) => {
return linkParams.reduce((accumulation: any[], item) => {
if (isString(item)) {
let parts: String[] = item.split('/');
return accumulation.concat(parts);
let strItem: string = item;
return accumulation.concat(strItem.split('/'));
}
accumulation.push(item);
return accumulation;

View File

@ -270,7 +270,7 @@ export function main() {
var formValidator = (c) => ({"custom": true});
var f = new NgFormModel([formValidator], []);
f.form = formModel;
f.onChanges({"form":<any>formModel});
f.onChanges({"form": new SimpleChange(null, null)});
expect(formModel.errors).toEqual({"custom": true});
});
@ -278,7 +278,7 @@ export function main() {
it("should set up an async validator", fakeAsync(() => {
var f = new NgFormModel([], [asyncValidator("expected")]);
f.form = formModel;
f.onChanges({"form":<any>formModel});
f.onChanges({"form": new SimpleChange(null, null)});
tick();

View File

@ -308,14 +308,12 @@ export class PerflogMetric extends Metric {
}
_addFrameMetrics(result: {[key: string]: any}, frameTimes: any[]) {
result['frameTime.mean'] =
ListWrapper.reduce(frameTimes, (a, b) => a + b, 0) / frameTimes.length;
result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length;
var firstFrame = frameTimes[0];
result['frameTime.worst'] = ListWrapper.reduce(frameTimes, (a, b) => a > b ? a : b, firstFrame);
result['frameTime.best'] = ListWrapper.reduce(frameTimes, (a, b) => a < b ? a : b, firstFrame);
result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame);
result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame);
result['frameTime.smooth'] =
ListWrapper.filter(frameTimes, (a) => a < _FRAME_TIME_SMOOTH_THRESHOLD).length /
frameTimes.length;
frameTimes.filter(t => t < _FRAME_TIME_SMOOTH_THRESHOLD).length / frameTimes.length;
}
_markName(index) { return `${_MARK_NAME_PREFIX}${index}`; }

View File

@ -201,9 +201,8 @@ export class ChromeDriverExtension extends WebDriverExtension {
private _isEvent(eventCategories: string[], eventName: string, expectedCategories: string[],
expectedName: string = null): boolean {
var hasCategories = ListWrapper.reduce(expectedCategories, (value, cat) => {
return value && ListWrapper.contains(eventCategories, cat);
}, true);
var hasCategories = expectedCategories.reduce(
(value, cat) => { return value && ListWrapper.contains(eventCategories, cat); }, true);
return isBlank(expectedName) ? hasCategories :
hasCategories && StringWrapper.equals(eventName, expectedName);
}

View File

@ -1,11 +1,11 @@
import {bootstrap} from 'angular2/bootstrap';
import {
FORM_DIRECTIVES,
ControlGroup,
NgControl,
Validators,
NgFormModel,
FormBuilder,
ControlGroup,
NgIf,
NgFor,
Component,
@ -57,7 +57,8 @@ class ShowError {
constructor(@Host() formDir: NgFormModel) { this.formDir = formDir; }
get errorMessage(): string {
var control = (<ControlGroup>this.formDir.form).find(this.controlPath);
var form: ControlGroup = this.formDir.form;
var control = form.find(this.controlPath);
if (isPresent(control) && control.touched) {
for (var i = 0; i < this.errorTypes.length; ++i) {
if (control.hasError(this.errorTypes[i])) {

View File

@ -66,7 +66,7 @@ class DataService {
}
itemsFor(order: Order): OrderItem[] {
return ListWrapper.filter(this.orderItems, i => i.orderId === order.orderId);
return this.orderItems.filter(i => i.orderId === order.orderId);
}
addItemForOrder(order: Order): void {

View File

@ -66,15 +66,14 @@ class DbService {
}
drafts(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data) => {
return ListWrapper.filter(data,
(record => isPresent(record['draft']) && record['draft'] == true));
return PromiseWrapper.then(this.getData(), (data: any[]) => {
return data.filter(record => isPresent(record['draft']) && record['draft'] == true);
});
}
emails(): Promise<any[]> {
return PromiseWrapper.then(this.getData(), (data) => {
return ListWrapper.filter(data, (record => !isPresent(record['draft'])));
return PromiseWrapper.then(this.getData(), (data: any[]) => {
return data.filter(record => !isPresent(record['draft']));
});
}

View File

@ -1,5 +1,6 @@
import {bootstrap} from 'angular2/bootstrap';
import {
ControlGroup,
NgIf,
NgFor,
Component,
@ -11,7 +12,6 @@ import {
Provider,
FORM_DIRECTIVES,
NgControl,
ControlGroup,
Validators,
NgForm
} from 'angular2/core';
@ -81,7 +81,8 @@ class ShowError {
constructor(@Host() formDir: NgForm) { this.formDir = formDir; }
get errorMessage(): string {
var control = (<ControlGroup>this.formDir.form).find(this.controlPath);
var form: ControlGroup = this.formDir.form;
var control = form.find(this.controlPath);
if (isPresent(control) && control.touched) {
for (var i = 0; i < this.errorTypes.length; ++i) {
if (control.hasError(this.errorTypes[i])) {

View File

@ -31,7 +31,7 @@ export class Store {
remove(record: KeyModel): void { this._spliceOut(record); }
removeBy(callback: Predicate<KeyModel>): void {
var records = ListWrapper.filter(this.list, callback);
var records = this.list.filter(callback);
ListWrapper.removeAll(this.list, records);
}

View File

@ -35,7 +35,7 @@ export class Store {
remove(record: KeyModel): void { this._spliceOut(record); }
removeBy(callback: Predicate<KeyModel>): void {
var records = ListWrapper.filter(this.list, callback);
var records = this.list.filter(callback);
ListWrapper.removeAll(this.list, records);
}