refactor: remove most facades (#12399)

This commit is contained in:
Victor Berchet 2016-10-21 15:14:44 -07:00 committed by Igor Minar
parent e319cfefc3
commit 57051f01ce
47 changed files with 204 additions and 444 deletions

View File

@ -8,13 +8,10 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic';
import {Validator} from '../validator';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the regression slope to be >=0.
@ -40,17 +37,17 @@ export class RegressionSlopeValidator extends Validator {
validate(completeSample: MeasureValues[]): MeasureValues[] {
if (completeSample.length >= this._sampleSize) {
var latestSample = ListWrapper.slice(
completeSample, completeSample.length - this._sampleSize, completeSample.length);
var xValues: number[] = [];
var yValues: number[] = [];
for (var i = 0; i < latestSample.length; i++) {
const latestSample =
completeSample.slice(completeSample.length - this._sampleSize, completeSample.length);
const xValues: number[] = [];
const yValues: number[] = [];
for (let i = 0; i < latestSample.length; i++) {
// For now, we only use the array index as x value.
// TODO(tbosch): think about whether we should use time here instead
xValues.push(i);
yValues.push(latestSample[i].values[this._metric]);
}
var regressionSlope = Statistic.calculateRegressionSlope(
const regressionSlope = Statistic.calculateRegressionSlope(
xValues, Statistic.calculateMean(xValues), yValues, Statistic.calculateMean(yValues));
return regressionSlope >= 0 ? latestSample : null;
} else {

View File

@ -8,12 +8,9 @@
import {Inject, Injectable, OpaqueToken} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {MeasureValues} from '../measure_values';
import {Validator} from '../validator';
/**
* A validator that waits for the sample to have a certain size.
*/
@ -28,8 +25,7 @@ export class SizeValidator extends Validator {
validate(completeSample: MeasureValues[]): MeasureValues[] {
if (completeSample.length >= this._sampleSize) {
return ListWrapper.slice(
completeSample, completeSample.length - this._sampleSize, completeSample.length);
return completeSample.slice(completeSample.length - this._sampleSize, completeSample.length);
} else {
return null;
}

View File

@ -62,7 +62,7 @@ export class IOsDriverExtension extends WebDriverExtension {
var startTime = record['startTime'];
var endTime = record['endTime'];
if (type === 'FunctionCall' && (isBlank(data) || data['scriptName'] !== 'InjectedScript')) {
if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) {
events.push(createStartEvent('script', startTime));
endEvent = createEndEvent('script', endTime);
} else if (type === 'Time') {

View File

@ -28,7 +28,7 @@ export function main() {
if (!descriptions) {
descriptions = [];
}
if (isBlank(sampleId)) {
if (sampleId == null) {
sampleId = 'null';
}
var providers: Provider[] = [

View File

@ -9,7 +9,6 @@
import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, ReflectiveInjector, RegressionSlopeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
export function main() {
describe('regression slope validator', () => {
@ -44,17 +43,15 @@ export function main() {
it('should return the last sampleSize runs when the regression slope is ==0', () => {
createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2)))
.toEqual(ListWrapper.slice(sample, 0, 2));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
it('should return the last sampleSize runs when the regression slope is >0', () => {
createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2)))
.toEqual(ListWrapper.slice(sample, 0, 2));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
});

View File

@ -9,7 +9,6 @@
import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, ReflectiveInjector, SizeValidator} from '../../index';
import {ListWrapper} from '../../src/facade/collection';
export function main() {
describe('size validator', () => {
@ -37,9 +36,8 @@ export function main() {
it('should return the last sampleSize runs when it has at least the given size', () => {
createValidator(2);
var sample = [mv(0, 0, {'a': 1}), mv(1, 1, {'b': 2}), mv(2, 2, {'c': 3})];
expect(validator.validate(ListWrapper.slice(sample, 0, 2)))
.toEqual(ListWrapper.slice(sample, 0, 2));
expect(validator.validate(sample)).toEqual(ListWrapper.slice(sample, 1, 3));
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
});

View File

@ -8,7 +8,6 @@
import {StaticReflector, StaticReflectorHost, StaticSymbol} from '@angular/compiler-cli/src/static_reflector';
import {HostListener, animate, group, keyframes, sequence, state, style, transition, trigger} from '@angular/core';
import {ListWrapper} from '@angular/facade/src/collection';
import {MetadataCollector} from '@angular/tsc-wrapped';
import * as ts from 'typescript';
@ -474,7 +473,7 @@ class MockReflectorHost implements StaticReflectorHost {
function resolvePath(pathParts: string[]): string {
let result: string[] = [];
ListWrapper.forEachWithIndex(pathParts, (part, index) => {
pathParts.forEach((part, index) => {
switch (part) {
case '':
case '.':

View File

@ -7,7 +7,7 @@
*/
import {CompileAnimationAnimateMetadata, CompileAnimationEntryMetadata, CompileAnimationGroupMetadata, CompileAnimationKeyframesSequenceMetadata, CompileAnimationMetadata, CompileAnimationSequenceMetadata, CompileAnimationStateDeclarationMetadata, CompileAnimationStateTransitionMetadata, CompileAnimationStyleMetadata, CompileAnimationWithStepsMetadata, CompileDirectiveMetadata} from '../compile_metadata';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {ParseError} from '../parse_util';
import {ANY_STATE, FILL_STYLE_FLAG} from '../private_import_core';
@ -180,8 +180,7 @@ function _normalizeStyleMetadata(
var normalizedStyles: {[key: string]: string | number}[] = [];
entry.styles.forEach(styleEntry => {
if (typeof styleEntry === 'string') {
ListWrapper.addAll(
normalizedStyles, _resolveStylesFromState(<string>styleEntry, stateStyles, errors));
normalizedStyles.push(..._resolveStylesFromState(<string>styleEntry, stateStyles, errors));
} else {
normalizedStyles.push(<{[key: string]: string | number}>styleEntry);
}
@ -346,12 +345,12 @@ function _parseAnimationKeyframes(
});
if (doSortKeyframes) {
ListWrapper.sort(rawKeyframes, (a, b) => a[0] <= b[0] ? -1 : 1);
rawKeyframes.sort((a, b) => a[0] <= b[0] ? -1 : 1);
}
var firstKeyframe = rawKeyframes[0];
if (firstKeyframe[0] != _INITIAL_KEYFRAME) {
ListWrapper.insert(rawKeyframes, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]);
rawKeyframes.splice(0, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]);
}
var firstKeyframeStyles = firstKeyframe[1];
@ -421,7 +420,7 @@ function _parseTransitionAnimation(
steps.push(new AnimationStepAst(startingStyles, [], 0, 0, ''));
} else {
var innerStep = <AnimationStepAst>innerAst;
ListWrapper.addAll(innerStep.startingStyles.styles, previousStyles);
innerStep.startingStyles.styles.push(...previousStyles);
}
previousStyles = null;
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
export class StylesCollectionEntry {
@ -37,7 +36,7 @@ export class StylesCollection {
}
}
ListWrapper.insert(entries, insertionIndex, tuple);
entries.splice(insertionIndex, 0, tuple);
}
getByIndex(property: string, index: number): StylesCollectionEntry {

View File

@ -9,7 +9,7 @@
import {ChangeDetectionStrategy, SchemaMetadata, Type, ViewEncapsulation} from '@angular/core';
import {ListWrapper, MapWrapper} from './facade/collection';
import {isPresent, normalizeBlank, normalizeBool} from './facade/lang';
import {isPresent} from './facade/lang';
import {LifecycleHooks} from './private_import_core';
import {CssSelector} from './selector';
import {sanitizeIdentifier, splitAtColon} from './util';
@ -23,7 +23,6 @@ function unimplemented(): any {
// group 2: "event" from "(event)"
// group 3: "@trigger" from "@trigger"
const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
const UNDEFINED = new Object();
export abstract class CompileMetadataWithIdentifier {
get identifier(): CompileIdentifierMetadata { return <CompileIdentifierMetadata>unimplemented(); }
@ -125,12 +124,12 @@ export class CompileDiDependencyMetadata {
token?: CompileTokenMetadata,
value?: any
} = {}) {
this.isAttribute = normalizeBool(isAttribute);
this.isSelf = normalizeBool(isSelf);
this.isHost = normalizeBool(isHost);
this.isSkipSelf = normalizeBool(isSkipSelf);
this.isOptional = normalizeBool(isOptional);
this.isValue = normalizeBool(isValue);
this.isAttribute = !!isAttribute;
this.isSelf = !!isSelf;
this.isHost = !!isHost;
this.isSkipSelf = !!isSkipSelf;
this.isOptional = !!isOptional;
this.isValue = !!isValue;
this.query = query;
this.viewQuery = viewQuery;
this.token = token;
@ -161,8 +160,8 @@ export class CompileProviderMetadata {
this.useValue = useValue;
this.useExisting = useExisting;
this.useFactory = useFactory;
this.deps = normalizeBlank(deps);
this.multi = normalizeBool(multi);
this.deps = deps || null;
this.multi = !!multi;
}
}
@ -192,7 +191,7 @@ export class CompileTokenMetadata implements CompileMetadataWithIdentifier {
{value?: any, identifier?: CompileIdentifierMetadata, identifierIsInstance?: boolean}) {
this.value = value;
this.identifier = identifier;
this.identifierIsInstance = normalizeBool(identifierIsInstance);
this.identifierIsInstance = !!identifierIsInstance;
}
get reference(): any {
@ -227,7 +226,7 @@ export class CompileTypeMetadata extends CompileIdentifierMetadata {
lifecycleHooks?: LifecycleHooks[];
} = {}) {
super({reference: reference, name: name, moduleUrl: moduleUrl, prefix: prefix, value: value});
this.isHost = normalizeBool(isHost);
this.isHost = !!isHost;
this.diDeps = _normalizeArray(diDeps);
this.lifecycleHooks = _normalizeArray(lifecycleHooks);
}
@ -248,8 +247,8 @@ export class CompileQueryMetadata {
read?: CompileTokenMetadata
} = {}) {
this.selectors = selectors;
this.descendants = normalizeBool(descendants);
this.first = normalizeBool(first);
this.descendants = !!descendants;
this.first = !!first;
this.propertyName = propertyName;
this.read = read;
}
@ -303,9 +302,9 @@ export class CompileTemplateMetadata {
this.styles = _normalizeArray(styles);
this.styleUrls = _normalizeArray(styleUrls);
this.externalStylesheets = _normalizeArray(externalStylesheets);
this.animations = isPresent(animations) ? ListWrapper.flatten(animations) : [];
this.animations = animations ? ListWrapper.flatten(animations) : [];
this.ngContentSelectors = ngContentSelectors || [];
if (isPresent(interpolation) && interpolation.length != 2) {
if (interpolation && interpolation.length != 2) {
throw new Error(`'interpolation' should have a start and an end symbol.`);
}
this.interpolation = interpolation;
@ -375,7 +374,7 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
return new CompileDirectiveMetadata({
type,
isComponent: normalizeBool(isComponent), selector, exportAs, changeDetection,
isComponent: !!isComponent, selector, exportAs, changeDetection,
inputs: inputsMap,
outputs: outputsMap,
hostListeners,
@ -503,7 +502,7 @@ export class CompilePipeMetadata implements CompileMetadataWithIdentifier {
} = {}) {
this.type = type;
this.name = name;
this.pure = normalizeBool(pure);
this.pure = !!pure;
}
get identifier(): CompileIdentifierMetadata { return this.type; }
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {ParseError, ParseSourceSpan} from '../parse_util';
@ -231,7 +230,7 @@ class _TreeBuilder {
private _closeVoidElement(): void {
if (this._elementStack.length > 0) {
const el = ListWrapper.last(this._elementStack);
const el = this._elementStack[this._elementStack.length - 1];
if (this.getTagDefinition(el.name).isVoid) {
this._elementStack.pop();
@ -275,7 +274,7 @@ class _TreeBuilder {
private _pushElement(el: html.Element) {
if (this._elementStack.length > 0) {
const parentEl = ListWrapper.last(this._elementStack);
const parentEl = this._elementStack[this._elementStack.length - 1];
if (this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
this._elementStack.pop();
}
@ -316,7 +315,7 @@ class _TreeBuilder {
for (let stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
const el = this._elementStack[stackIndex];
if (el.name == fullName) {
ListWrapper.splice(this._elementStack, stackIndex, this._elementStack.length - stackIndex);
this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
return true;
}
@ -343,7 +342,7 @@ class _TreeBuilder {
}
private _getParentElement(): html.Element {
return this._elementStack.length > 0 ? ListWrapper.last(this._elementStack) : null;
return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
}
/**
@ -361,7 +360,7 @@ class _TreeBuilder {
container = this._elementStack[i];
}
return {parent: ListWrapper.last(this._elementStack), container};
return {parent: this._elementStack[this._elementStack.length - 1], container};
}
private _addToParent(node: html.Node) {

View File

@ -7,7 +7,6 @@
*/
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import * as o from './output_ast';
@ -153,7 +152,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
if (isPresent(expr.builtin)) {
switch (expr.builtin) {
case o.BuiltinMethod.ConcatArray:
result = ListWrapper.concat(receiver, args[0]);
result = receiver.concat(args[0]);
break;
case o.BuiltinMethod.SubscribeObservable:
result = receiver.subscribe({next: args[0]});

View File

@ -8,8 +8,8 @@
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata} from './compile_metadata';
import {ListWrapper, MapWrapper} from './facade/collection';
import {isBlank, isPresent, normalizeBlank} from './facade/lang';
import {MapWrapper} from './facade/collection';
import {isBlank, isPresent} from './facade/lang';
import {Identifiers, resolveIdentifierToken} from './identifiers';
import {ParseError, ParseSourceSpan} from './parse_util';
import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, ReferenceAst} from './template_parser/template_ast';
@ -91,9 +91,9 @@ export class ProviderElementContext {
get transformedDirectiveAsts(): DirectiveAst[] {
var sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
var sortedDirectives = ListWrapper.clone(this._directiveAsts);
ListWrapper.sort(
sortedDirectives, (dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
var sortedDirectives = this._directiveAsts.slice();
sortedDirectives.sort(
(dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
sortedProviderTypes.indexOf(dir2.directive.type));
return sortedDirectives;
}
@ -117,7 +117,7 @@ export class ProviderElementContext {
while (currentEl !== null) {
queries = currentEl._contentQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries.filter((query) => query.descendants || distance <= 1));
result.push(...queries.filter((query) => query.descendants || distance <= 1));
}
if (currentEl._directiveAsts.length > 0) {
distance++;
@ -126,7 +126,7 @@ export class ProviderElementContext {
}
queries = this.viewContext.viewQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries);
result.push(...queries);
}
return result;
}
@ -194,7 +194,8 @@ export class ProviderElementContext {
eager: boolean = null): CompileDiDependencyMetadata {
if (dep.isAttribute) {
var attrValue = this._attrs[dep.token.value];
return new CompileDiDependencyMetadata({isValue: true, value: normalizeBlank(attrValue)});
return new CompileDiDependencyMetadata(
{isValue: true, value: attrValue == null ? null : attrValue});
}
if (isPresent(dep.query) || isPresent(dep.viewQuery)) {
return dep;
@ -489,7 +490,7 @@ function _resolveProviders(
targetProvidersByToken.set(provider.token.reference, resolvedProvider);
} else {
if (!provider.multi) {
ListWrapper.clear(resolvedProvider.providers);
resolvedProvider.providers.length = 0;
}
resolvedProvider.providers.push(provider);
}

View File

@ -9,7 +9,7 @@
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileIdentifierMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata} from '../compile_metadata';
import {DirectiveWrapperCompiler} from '../directive_wrapper_compiler';
import {ListWrapper, MapWrapper} from '../facade/collection';
import {MapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {Identifiers, identifierToken, resolveIdentifier, resolveIdentifierToken} from '../identifiers';
import * as o from '../output/output_ast';
@ -218,9 +218,8 @@ export class CompileElement extends CompileNode {
var queriesWithReads: _QueryWithRead[] = [];
MapWrapper.values(this._resolvedProviders).forEach((resolvedProvider) => {
var queriesForProvider = this._getQueriesFor(resolvedProvider.token);
ListWrapper.addAll(
queriesWithReads,
queriesForProvider.map(query => new _QueryWithRead(query, resolvedProvider.token)));
queriesWithReads.push(
...queriesForProvider.map(query => new _QueryWithRead(query, resolvedProvider.token)));
});
Object.keys(this.referenceTokens).forEach(varName => {
var token = this.referenceTokens[varName];
@ -232,9 +231,8 @@ export class CompileElement extends CompileNode {
}
this.view.locals.set(varName, varValue);
var varToken = new CompileTokenMetadata({value: varName});
ListWrapper.addAll(
queriesWithReads,
this._getQueriesFor(varToken).map(query => new _QueryWithRead(query, varToken)));
queriesWithReads.push(
...this._getQueriesFor(varToken).map(query => new _QueryWithRead(query, varToken)));
});
queriesWithReads.forEach((queryWithRead) => {
var value: o.Expression;
@ -315,8 +313,7 @@ export class CompileElement extends CompileNode {
while (!currentEl.isNull()) {
queries = currentEl._queries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(
result, queries.filter((query) => query.meta.descendants || distance <= 1));
result.push(...queries.filter((query) => query.meta.descendants || distance <= 1));
}
if (currentEl._directives.length > 0) {
distance++;
@ -325,7 +322,7 @@ export class CompileElement extends CompileNode {
}
queries = this.view.componentView.viewQueries.get(token.reference);
if (isPresent(queries)) {
ListWrapper.addAll(result, queries);
result.push(...queries);
}
return result;
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import * as o from '../output/output_ast';
import {TemplateAst} from '../template_parser/template_ast';
@ -73,7 +72,7 @@ export class CompileMethod {
addStmts(stmts: o.Statement[]) {
this._updateDebugContextIfNeeded();
ListWrapper.addAll(this._bodyStatements, stmts);
this._bodyStatements.push(...stmts);
}
finish(): o.Statement[] { return this._bodyStatements; }

View File

@ -9,7 +9,7 @@
import {AnimationEntryCompileResult} from '../animation/animation_compiler';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompilePipeMetadata} from '../compile_metadata';
import {CompilerConfig} from '../config';
import {ListWrapper, MapWrapper} from '../facade/collection';
import {MapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {Identifiers, resolveIdentifier} from '../identifiers';
import * as o from '../output/output_ast';
@ -102,7 +102,7 @@ export class CompileView implements NameResolver {
var viewQueries = new Map<any, CompileQuery[]>();
if (this.viewType === ViewType.COMPONENT) {
var directiveInstance = o.THIS_EXPR.prop('context');
ListWrapper.forEachWithIndex(this.component.viewQueries, (queryMeta, queryIndex) => {
this.component.viewQueries.forEach((queryMeta, queryIndex) => {
var propName = `_viewQuery_${queryMeta.selectors[0].name}_${queryIndex}`;
var queryList = createQueryList(queryMeta, directiveInstance, propName, this);
var query = new CompileQuery(queryMeta, queryList, directiveInstance, this);

View File

@ -9,7 +9,6 @@
import {ViewEncapsulation} from '@angular/core';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileTokenMetadata} from '../compile_metadata';
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {Identifiers, identifierToken, resolveIdentifier} from '../identifiers';
import * as o from '../output/output_ast';
@ -362,8 +361,7 @@ function mapToKeyValueArray(data: {[key: string]: string}): string[][] {
Object.keys(data).forEach(name => { entryArray.push([name, data[name]]); });
// We need to sort to get a defined output order
// for tests and for caching generated artifacts...
ListWrapper.sort(entryArray);
return entryArray;
return entryArray.sort();
}
function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statement[]) {
@ -567,8 +565,8 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
view.updateViewQueriesMethod.isEmpty() && view.afterViewLifecycleCallbacksMethod.isEmpty()) {
return stmts;
}
ListWrapper.addAll(stmts, view.animationBindingsMethod.finish());
ListWrapper.addAll(stmts, view.detectChangesInInputsMethod.finish());
stmts.push(...view.animationBindingsMethod.finish());
stmts.push(...view.detectChangesInInputsMethod.finish());
stmts.push(
o.THIS_EXPR.callMethod('detectContentChildrenChanges', [DetectChangesVars.throwOnChange])
.toStmt());
@ -577,7 +575,7 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
if (afterContentStmts.length > 0) {
stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterContentStmts));
}
ListWrapper.addAll(stmts, view.detectChangesRenderPropertiesMethod.finish());
stmts.push(...view.detectChangesRenderPropertiesMethod.finish());
stmts.push(o.THIS_EXPR.callMethod('detectViewChildrenChanges', [DetectChangesVars.throwOnChange])
.toStmt());
var afterViewStmts =

View File

@ -8,7 +8,7 @@
import {ResourceLoader} from '@angular/compiler';
import {ListWrapper} from './facade/collection';
import {isBlank, normalizeBlank} from './facade/lang';
import {isBlank} from './facade/lang';
/**
* A mock implementation of {@link ResourceLoader} that allows outgoing requests to be mocked
@ -20,7 +20,7 @@ export class MockResourceLoader extends ResourceLoader {
private _requests: _PendingRequest[] = [];
get(url: string): Promise<string> {
var request = new _PendingRequest(url);
const request = new _PendingRequest(url);
this._requests.push(request);
return request.getPromise();
}
@ -33,7 +33,7 @@ export class MockResourceLoader extends ResourceLoader {
* The response given will be returned if the expectation matches.
*/
expect(url: string, response: string) {
var expectation = new _Expectation(url, response);
const expectation = new _Expectation(url, response);
this._expectations.push(expectation);
}
@ -90,7 +90,7 @@ export class MockResourceLoader extends ResourceLoader {
if (this._definitions.has(url)) {
var response = this._definitions.get(url);
request.complete(normalizeBlank(response));
request.complete(response == null ? null : response);
return;
}

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {StringMapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {FILL_STYLE_FLAG} from './animation_constants';
@ -57,7 +57,7 @@ export function balanceAnimationKeyframes(
// phase 2: normalize the final keyframe
var finalKeyframe = keyframes[limit];
ListWrapper.insert(finalKeyframe.styles.styles, 0, finalStateStyles);
finalKeyframe.styles.styles.unshift(finalStateStyles);
var flatenedFinalKeyframeStyles = flattenStyles(finalKeyframe.styles.styles);
var extraFinalKeyframeStyles: {[key: string]: string} = {};

View File

@ -7,7 +7,6 @@
*/
import {Optional, Provider, SkipSelf} from '../../di';
import {ListWrapper} from '../../facade/collection';
import {getTypeNameForDebugging, isPresent} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
@ -51,7 +50,7 @@ export class IterableDiffers {
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers {
if (isPresent(parent)) {
var copied = ListWrapper.clone(parent.factories);
var copied = parent.factories.slice();
factories = factories.concat(copied);
return new IterableDiffers(factories);
} else {

View File

@ -41,7 +41,7 @@ export class KeyValueDiffers {
static create(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers {
if (isPresent(parent)) {
var copied = ListWrapper.clone(parent.factories);
var copied = parent.factories.slice();
factories = factories.concat(copied);
return new KeyValueDiffers(factories);
} else {

View File

@ -7,7 +7,7 @@
*/
import {Injector} from '../di';
import {ListWrapper, MapWrapper, Predicate} from '../facade/collection';
import {MapWrapper, Predicate} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {RenderDebugInfo} from '../render/api';
@ -92,8 +92,7 @@ export class DebugElement extends DebugNode {
if (siblingIndex !== -1) {
var previousChildren = this.childNodes.slice(0, siblingIndex + 1);
var nextChildren = this.childNodes.slice(siblingIndex + 1);
this.childNodes =
ListWrapper.concat(ListWrapper.concat(previousChildren, newChildren), nextChildren);
this.childNodes = previousChildren.concat(newChildren, nextChildren);
for (var i = 0; i < newChildren.length; ++i) {
var newChild = newChildren[i];
if (isPresent(newChild.parent)) {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {BaseError, WrappedError} from '../facade/errors';
import {stringify} from '../facade/lang';
import {Type} from '../type';
@ -17,7 +16,7 @@ import {ReflectiveKey} from './reflective_key';
function findFirstClosedCycle(keys: any[]): any[] {
var res: any[] = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
if (res.indexOf(keys[i]) > -1) {
res.push(keys[i]);
return res;
}
@ -28,8 +27,8 @@ function findFirstClosedCycle(keys: any[]): any[] {
function constructResolvingPath(keys: any[]): string {
if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = reversed.map(k => stringify(k.token));
const reversed = findFirstClosedCycle(keys.slice().reverse());
const tokenStrs = reversed.map(k => stringify(k.token));
return ' (' + tokenStrs.join(' -> ') + ')';
}
@ -88,7 +87,7 @@ export class AbstractProviderError extends BaseError {
export class NoProviderError extends AbstractProviderError {
constructor(injector: ReflectiveInjector, key: ReflectiveKey) {
super(injector, key, function(keys: any[]) {
var first = stringify(ListWrapper.first(keys).token);
const first = stringify(keys[0].token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
});
}
@ -167,7 +166,7 @@ export class InstantiationError extends WrappedError {
}
get message(): string {
var first = stringify(ListWrapper.first(this.keys).token);
var first = stringify(this.keys[0].token);
return `${this.originalError.message}: Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper} from '../facade/collection';
import {unimplemented} from '../facade/errors';
import {Type} from '../type';
@ -17,8 +16,6 @@ import {AbstractProviderError, CyclicDependencyError, InstantiationError, NoProv
import {ReflectiveKey} from './reflective_key';
import {ReflectiveDependency, ResolvedReflectiveFactory, ResolvedReflectiveProvider, resolveReflectiveProviders} from './reflective_provider';
var __unused: Type<any>; // avoid unused import when Type union types are erased
// Threshold for the dynamic version
const _MAX_CONSTRUCTION_COUNTER = 10;
const UNDEFINED = new Object();
@ -286,8 +283,7 @@ export class ReflectiveInjectorDynamicStrategy implements ReflectiveInjectorStra
constructor(
public protoStrategy: ReflectiveProtoInjectorDynamicStrategy,
public injector: ReflectiveInjector_) {
this.objs = new Array(protoStrategy.providers.length);
ListWrapper.fill(this.objs, UNDEFINED);
this.objs = new Array(protoStrategy.providers.length).fill(UNDEFINED);
}
resetConstructionCounter(): void { this.injector._constructionCounter = 0; }
@ -297,9 +293,9 @@ export class ReflectiveInjectorDynamicStrategy implements ReflectiveInjectorStra
}
getObjByKeyId(keyId: number): any {
var p = this.protoStrategy;
const p = this.protoStrategy;
for (var i = 0; i < p.keyIds.length; i++) {
for (let i = 0; i < p.keyIds.length; i++) {
if (p.keyIds[i] === keyId) {
if (this.objs[i] === UNDEFINED) {
this.objs[i] = this.injector._new(p.providers[i]);

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper, MapWrapper} from '../facade/collection';
import {MapWrapper} from '../facade/collection';
import {isBlank, isPresent} from '../facade/lang';
import {reflector} from '../reflection/reflection';
import {Type} from '../type';
@ -170,7 +170,7 @@ export function mergeResolvedReflectiveProviders(
var resolvedProvider: ResolvedReflectiveProvider;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(
provider.key, ListWrapper.clone(provider.resolvedFactories), provider.multiProvider);
provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
} else {
resolvedProvider = provider;
}

View File

@ -7,7 +7,6 @@
*/
import {Injector} from '../di/injector';
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {ElementRef} from './element_ref';
@ -69,8 +68,8 @@ export class AppElement {
nestedViews = [];
this.nestedViews = nestedViews;
}
ListWrapper.removeAt(nestedViews, previousIndex);
ListWrapper.insert(nestedViews, currentIndex, view);
nestedViews.splice(previousIndex, 1);
nestedViews.splice(currentIndex, 0, view);
var refRenderNode: any /** TODO #9100 */;
if (currentIndex > 0) {
var prevView = nestedViews[currentIndex - 1];
@ -93,7 +92,7 @@ export class AppElement {
nestedViews = [];
this.nestedViews = nestedViews;
}
ListWrapper.insert(nestedViews, viewIndex, view);
nestedViews.splice(viewIndex, 0, view);
var refRenderNode: any /** TODO #9100 */;
if (viewIndex > 0) {
var prevView = nestedViews[viewIndex - 1];
@ -108,7 +107,7 @@ export class AppElement {
}
detachView(viewIndex: number): AppView<any> {
var view = ListWrapper.removeAt(this.nestedViews, viewIndex);
const view = this.nestedViews.splice(viewIndex, 1)[0];
if (view.type === ViewType.COMPONENT) {
throw new Error(`Component views can't be moved!`);
}

View File

@ -7,7 +7,6 @@
*/
import {Injector} from '../di/injector';
import {ListWrapper} from '../facade/collection';
import {unimplemented} from '../facade/errors';
import {isPresent} from '../facade/lang';
import {WtfScopeFn, wtfCreateScope, wtfLeave} from '../profile/profile';
@ -186,7 +185,7 @@ export class ViewContainerRef_ implements ViewContainerRef {
}
indexOf(viewRef: ViewRef): number {
return ListWrapper.indexOf(this._element.nestedViews, (<ViewRef_<any>>viewRef).internalView);
return this._element.nestedViews.indexOf((<ViewRef_<any>>viewRef).internalView);
}
/** @internal */
@ -194,9 +193,9 @@ export class ViewContainerRef_ implements ViewContainerRef {
// TODO(i): rename to destroy
remove(index: number = -1): void {
var s = this._removeScope();
const s = this._removeScope();
if (index == -1) index = this.length - 1;
var view = this._element.detachView(index);
const view = this._element.detachView(index);
view.destroy();
// view is intentionally not returned to the client.
wtfLeave(s);
@ -207,14 +206,14 @@ export class ViewContainerRef_ implements ViewContainerRef {
// TODO(i): refactor insert+remove into move
detach(index: number = -1): ViewRef {
var s = this._detachScope();
const s = this._detachScope();
if (index == -1) index = this.length - 1;
var view = this._element.detachView(index);
const view = this._element.detachView(index);
return wtfLeave(s, view.ref);
}
clear() {
for (var i = this.length - 1; i >= 0; i--) {
for (let i = this.length - 1; i >= 0; i--) {
this.remove(i);
}
}

View File

@ -9,7 +9,6 @@
import {DefaultIterableDiffer, DefaultIterableDifferFactory} from '@angular/core/src/change_detection/differs/default_iterable_differ';
import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';
import {ListWrapper} from '../../../src/facade/collection';
import {TestIterable} from '../../change_detection/iterable';
import {iterableChangesAsString} from '../../change_detection/util';
@ -110,7 +109,7 @@ export function main() {
let l = [1, 2];
differ.check(l);
ListWrapper.clear(l);
l.length = 0;
l.push(2);
l.push(1);
differ.check(l);
@ -125,8 +124,8 @@ export function main() {
let l = ['a', 'b', 'c'];
differ.check(l);
ListWrapper.removeAt(l, 1);
ListWrapper.insert(l, 0, 'b');
l.splice(1, 1);
l.splice(0, 0, 'b');
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['b[1->0]', 'a[0->1]', 'c'],
@ -134,7 +133,7 @@ export function main() {
moves: ['b[1->0]', 'a[0->1]']
}));
ListWrapper.removeAt(l, 1);
l.splice(1, 1);
l.push('a');
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
@ -170,7 +169,7 @@ export function main() {
additions: ['c[null->2]', 'd[null->3]']
}));
ListWrapper.removeAt(l, 2);
l.splice(2, 1);
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['a', 'b', 'd[3->2]'],
@ -179,7 +178,7 @@ export function main() {
removals: ['c[2->null]']
}));
ListWrapper.clear(l);
l.length = 0;
l.push('d');
l.push('c');
l.push('b');
@ -214,10 +213,10 @@ export function main() {
});
it('should detect [NaN] moves', () => {
let l = [NaN, NaN];
let l: any[] = [NaN, NaN];
differ.check(l);
ListWrapper.insert<any>(l, 0, 'foo');
l.unshift('foo');
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['foo[null->0]', 'NaN[0->1]', 'NaN[1->2]'],
@ -231,7 +230,7 @@ export function main() {
let l = ['a', 'b', 'c'];
differ.check(l);
ListWrapper.removeAt(l, 1);
l.splice(1, 1);
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['a', 'c[2->1]'],
@ -240,7 +239,7 @@ export function main() {
removals: ['b[1->null]']
}));
ListWrapper.insert(l, 1, 'b');
l.splice(1, 0, 'b');
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['a', 'b[null->1]', 'c[1->2]'],
@ -255,7 +254,7 @@ export function main() {
let l = ['a', 'a', 'a', 'b', 'b'];
differ.check(l);
ListWrapper.removeAt(l, 0);
l.splice(0, 1);
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['a', 'a', 'b[3->2]', 'b[4->3]'],
@ -269,7 +268,7 @@ export function main() {
let l = ['a', 'a', 'b', 'b'];
differ.check(l);
ListWrapper.insert(l, 0, 'b');
l.splice(0, 0, 'b');
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['b[2->0]', 'a[0->1]', 'a[1->2]', 'b', 'b[null->4]'],
@ -283,7 +282,7 @@ export function main() {
let l = ['a', 'b', 'c'];
differ.check(l);
ListWrapper.clear(l);
l.length = 0;
l.push('b');
l.push('a');
l.push('c');
@ -557,7 +556,7 @@ export function main() {
let l = buildItemList(['a', 'b', 'c']);
differ.check(l);
ListWrapper.removeAt(l, 2);
l.splice(2, 1);
differ.check(l);
expect(differ.toString()).toEqual(iterableChangesAsString({
collection: ['{id: a}', '{id: b}'],

View File

@ -641,8 +641,7 @@ class NeedsQueryAndProject {
@Component({
selector: 'needs-view-query',
template: '<div text="1"><div text="2"></div></div>' +
'<div text="3"></div><div text="4"></div>'
template: '<div text="1"><div text="2"></div></div><div text="3"></div><div text="4"></div>'
})
class NeedsViewQuery {
@ViewChildren(TextDirective) query: QueryList<TextDirective>;

View File

@ -85,78 +85,29 @@ export class StringMapWrapper {
export interface Predicate<T> { (value: T, index?: number, array?: T[]): boolean; }
export class ListWrapper {
// JS has no way to express a statically fixed size list, but dart does so we
// keep both methods.
static createFixedSize(size: number): any[] { return new Array(size); }
static createGrowableSize(size: number): any[] { return new Array(size); }
static clone<T>(array: T[]): T[] { return array.slice(0); }
static forEachWithIndex<T>(array: T[], fn: (t: T, n: number) => void) {
for (var i = 0; i < array.length; i++) {
fn(array[i], i);
}
}
static first<T>(array: T[]): T {
if (!array) return null;
return array[0];
}
static last<T>(array: T[]): T {
if (!array || array.length == 0) return null;
return array[array.length - 1];
}
static indexOf<T>(array: T[], value: T, startIndex: number = 0): number {
return array.indexOf(value, startIndex);
}
static contains<T>(list: T[], el: T): boolean { return list.indexOf(el) !== -1; }
static reversed<T>(array: T[]): T[] {
var a = ListWrapper.clone(array);
return a.reverse();
}
static concat(a: any[], b: any[]): any[] { return a.concat(b); }
static insert<T>(list: T[], index: number, value: T) { list.splice(index, 0, value); }
static removeAt<T>(list: T[], index: number): T {
var res = list[index];
list.splice(index, 1);
return res;
}
static removeAll<T>(list: T[], items: T[]) {
for (var i = 0; i < items.length; ++i) {
var index = list.indexOf(items[i]);
for (let i = 0; i < items.length; ++i) {
const index = list.indexOf(items[i]);
list.splice(index, 1);
}
}
static remove<T>(list: T[], el: T): boolean {
var index = list.indexOf(el);
const index = list.indexOf(el);
if (index > -1) {
list.splice(index, 1);
return true;
}
return false;
}
static clear(list: any[]) { list.length = 0; }
static isEmpty(list: any[]): boolean { return list.length == 0; }
static fill(list: any[], value: any, start: number = 0, end: number = null) {
list.fill(value, start, end === null ? list.length : end);
}
static equals(a: any[], b: any[]): boolean {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
static slice<T>(l: T[], from: number = 0, to: number = null): T[] {
return l.slice(from, to === null ? undefined : to);
}
static splice<T>(l: T[], from: number, length: number): T[] { return l.splice(from, length); }
static sort<T>(l: T[], compareFn?: (a: T, b: T) => number) {
if (isPresent(compareFn)) {
l.sort(compareFn);
} else {
l.sort();
}
}
static toString<T>(l: T[]): string { return l.toString(); }
static toJSON<T>(l: T[]): string { return JSON.stringify(l); }
static maximum<T>(list: T[], predicate: (t: T) => number): T {
if (list.length == 0) {
@ -166,7 +117,7 @@ export class ListWrapper {
var maxValue = -Infinity;
for (var index = 0; index < list.length; index++) {
var candidate = list[index];
if (isBlank(candidate)) {
if (candidate == null) {
continue;
}
var candidateValue = predicate(candidate);
@ -183,12 +134,6 @@ export class ListWrapper {
_flattenArray(list, target);
return target;
}
static addAll<T>(list: Array<T>, source: Array<T>): void {
for (var i = 0; i < source.length; i++) {
list.push(source[i]);
}
}
}
function _flattenArray(source: any[], target: any[]): any[] {

View File

@ -53,11 +53,10 @@ export function scheduleMicroTask(fn: Function) {
// Need to declare a new variable for global here since TypeScript
// exports the original value of the symbol.
var _global: BrowserNodeGlobal = globalScope;
const _global: BrowserNodeGlobal = globalScope;
export {_global as global};
export function getTypeNameForDebugging(type: any): string {
return type['name'] || typeof type;
}
@ -70,11 +69,11 @@ _global.assert = function assert(condition) {
};
export function isPresent(obj: any): boolean {
return obj !== undefined && obj !== null;
return obj != null;
}
export function isBlank(obj: any): boolean {
return obj === undefined || obj === null;
return obj == null;
}
const STRING_MAP_PROTO = Object.getPrototypeOf({});
@ -86,8 +85,6 @@ export function isDate(obj: any): obj is Date {
return obj instanceof Date && !isNaN(obj.valueOf());
}
export function noop() {}
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
@ -144,14 +141,6 @@ export function looseIdentical(a: any, b: any): boolean {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
export function normalizeBlank(obj: Object): any {
return isBlank(obj) ? null : obj;
}
export function normalizeBool(obj: boolean): boolean {
return isBlank(obj) ? false : obj;
}
export function isJsObject(o: any): boolean {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
@ -182,17 +171,17 @@ export function setValueOnPath(global: any, path: string, value: any) {
}
// When Symbol.iterator doesn't exist, retrieves the key used in es6-shim
declare var Symbol: any;
var _symbolIterator: any = null;
declare let Symbol: any;
let _symbolIterator: any = null;
export function getSymbolIterator(): string|symbol {
if (isBlank(_symbolIterator)) {
if (isPresent((<any>globalScope).Symbol) && isPresent(Symbol.iterator)) {
if (!_symbolIterator) {
if ((<any>globalScope).Symbol && Symbol.iterator) {
_symbolIterator = Symbol.iterator;
} else {
// es6-shim specific logic
var keys = Object.getOwnPropertyNames(Map.prototype);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
const keys = Object.getOwnPropertyNames(Map.prototype);
for (let i = 0; i < keys.length; ++i) {
let key = keys[i];
if (key !== 'entries' && key !== 'size' &&
(Map as any).prototype[key] === Map.prototype['entries']) {
_symbolIterator = key;

View File

@ -10,81 +10,6 @@ import {ListWrapper, MapWrapper, StringMapWrapper} from '../src/collection';
export function main() {
describe('ListWrapper', () => {
var l: number[];
describe('splice', () => {
it('should remove sublist of given length and return it', () => {
var list = [1, 2, 3, 4, 5, 6];
expect(ListWrapper.splice(list, 1, 3)).toEqual([2, 3, 4]);
expect(list).toEqual([1, 5, 6]);
});
it('should support negative start', () => {
var list = [1, 2, 3, 4, 5, 6];
expect(ListWrapper.splice(list, -5, 3)).toEqual([2, 3, 4]);
expect(list).toEqual([1, 5, 6]);
});
});
describe('fill', () => {
beforeEach(() => { l = [1, 2, 3, 4]; });
it('should fill the whole list if neither start nor end are specified', () => {
ListWrapper.fill(l, 9);
expect(l).toEqual([9, 9, 9, 9]);
});
it('should fill up to the end if end is not specified', () => {
ListWrapper.fill(l, 9, 1);
expect(l).toEqual([1, 9, 9, 9]);
});
it('should support negative start', () => {
ListWrapper.fill(l, 9, -1);
expect(l).toEqual([1, 2, 3, 9]);
});
it('should support negative end', () => {
ListWrapper.fill(l, 9, -2, -1);
expect(l).toEqual([1, 2, 9, 4]);
});
});
describe('slice', () => {
beforeEach(() => { l = [1, 2, 3, 4]; });
it('should return the whole list if neither start nor end are specified', () => {
expect(ListWrapper.slice(l)).toEqual([1, 2, 3, 4]);
});
it('should return up to the end if end is not specified', () => {
expect(ListWrapper.slice(l, 1)).toEqual([2, 3, 4]);
});
it('should support negative start', () => { expect(ListWrapper.slice(l, -1)).toEqual([4]); });
it('should support negative end', () => {
expect(ListWrapper.slice(l, -3, -1)).toEqual([2, 3]);
});
it('should return empty list if start is greater than end', () => {
expect(ListWrapper.slice(l, 4, 2)).toEqual([]);
expect(ListWrapper.slice(l, -2, -4)).toEqual([]);
});
});
describe('indexOf', () => {
beforeEach(() => { l = [1, 2, 3, 4]; });
it('should find values that exist', () => { expect(ListWrapper.indexOf(l, 1)).toEqual(0); });
it('should not find values that do not exist',
() => { expect(ListWrapper.indexOf(l, 9)).toEqual(-1); });
it('should respect the startIndex parameter',
() => { expect(ListWrapper.indexOf(l, 1, 1)).toEqual(-1); });
});
describe('maximum', () => {
it('should return the maximal element', () => {
expect(ListWrapper.maximum([1, 2, 3, 4], x => x)).toEqual(4);
@ -102,17 +27,6 @@ export function main() {
() => { expect(ListWrapper.maximum([], x => x)).toEqual(null); });
});
describe('forEachWithIndex', () => {
var l: any /** TODO #9100 */;
beforeEach(() => { l = ['a', 'b']; });
it('should iterate over an array passing values and indices', () => {
var record: any[] /** TODO #9100 */ = [];
ListWrapper.forEachWithIndex(l, (value, index) => record.push([value, index]));
expect(record).toEqual([['a', 0], ['b', 1]]);
});
});
});
describe('StringMapWrapper', () => {

View File

@ -9,7 +9,6 @@
import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter} from '../facade/async';
import {ListWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {AbstractControl, FormControl, FormGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
@ -156,6 +155,6 @@ export class NgForm extends ControlContainer implements Form {
/** @internal */
_findContainer(path: string[]): FormGroup {
path.pop();
return ListWrapper.isEmpty(path) ? this.form : <FormGroup>this.form.get(path);
return path.length ? <FormGroup>this.form.get(path) : this.form;
}
}

View File

@ -8,8 +8,6 @@
import {Directive, ElementRef, Injectable, Injector, Input, OnDestroy, OnInit, Renderer, forwardRef} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
@ -37,7 +35,7 @@ export class RadioControlRegistry {
indexToRemove = i;
}
}
ListWrapper.removeAt(this._accessors, indexToRemove);
this._accessors.splice(indexToRemove, 1);
}
select(accessor: RadioControlValueAccessor) {

View File

@ -11,7 +11,6 @@ import {fromPromise} from 'rxjs/observable/fromPromise';
import {composeAsyncValidators, composeValidators} from './directives/shared';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import {EventEmitter, Observable} from './facade/async';
import {isBlank, isPresent, normalizeBool} from './facade/lang';
import {isPromise} from './private_import_core';
@ -42,7 +41,7 @@ export function isControl(control: Object): boolean {
}
function _find(control: AbstractControl, path: Array<string|number>| string, delimiter: string) {
if (isBlank(path)) return null;
if (path == null) return null;
if (!(path instanceof Array)) {
path = (<string>path).split(delimiter);
@ -249,10 +248,9 @@ export abstract class AbstractControl {
* the model.
*/
markAsTouched({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = normalizeBool(onlySelf);
this._touched = true;
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent.markAsTouched({onlySelf});
}
}
@ -270,7 +268,7 @@ export abstract class AbstractControl {
this._forEachChild(
(control: AbstractControl) => { control.markAsUntouched({onlySelf: true}); });
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent._updateTouched({onlySelf});
}
}
@ -282,10 +280,9 @@ export abstract class AbstractControl {
* the model.
*/
markAsDirty({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = normalizeBool(onlySelf);
this._pristine = false;
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent.markAsDirty({onlySelf});
}
}
@ -302,7 +299,7 @@ export abstract class AbstractControl {
this._forEachChild((control: AbstractControl) => { control.markAsPristine({onlySelf: true}); });
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent._updatePristine({onlySelf});
}
}
@ -311,10 +308,9 @@ export abstract class AbstractControl {
* Marks the control as `pending`.
*/
markAsPending({onlySelf}: {onlySelf?: boolean} = {}): void {
onlySelf = normalizeBool(onlySelf);
this._status = PENDING;
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent.markAsPending({onlySelf});
}
}
@ -326,14 +322,12 @@ export abstract class AbstractControl {
* If the control has children, all children will be disabled to maintain the model.
*/
disable({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._status = DISABLED;
this._errors = null;
this._forEachChild((control: AbstractControl) => { control.disable({onlySelf: true}); });
this._updateValue();
if (emitEvent) {
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
@ -359,7 +353,7 @@ export abstract class AbstractControl {
}
private _updateAncestors(onlySelf: boolean) {
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity();
this._parent._updatePristine();
this._parent._updateTouched();
@ -390,9 +384,6 @@ export abstract class AbstractControl {
*/
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void {
onlySelf = normalizeBool(onlySelf);
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._setInitialStatus();
this._updateValue();
@ -405,12 +396,12 @@ export abstract class AbstractControl {
}
}
if (emitEvent) {
if (emitEvent !== false) {
this._valueChanges.emit(this._value);
this._statusChanges.emit(this._status);
}
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent.updateValueAndValidity({onlySelf, emitEvent});
}
}
@ -424,21 +415,21 @@ export abstract class AbstractControl {
private _setInitialStatus() { this._status = this._allControlsDisabled() ? DISABLED : VALID; }
private _runValidator(): {[key: string]: any} {
return isPresent(this.validator) ? this.validator(this) : null;
return this.validator ? this.validator(this) : null;
}
private _runAsyncValidator(emitEvent: boolean): void {
if (isPresent(this.asyncValidator)) {
if (this.asyncValidator) {
this._status = PENDING;
this._cancelExistingSubscription();
var obs = toObservable(this.asyncValidator(this));
const obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
obs.subscribe({next: (res: {[key: string]: any}) => this.setErrors(res, {emitEvent})});
}
}
private _cancelExistingSubscription(): void {
if (isPresent(this._asyncValidationSubscription)) {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
}
}
@ -467,10 +458,8 @@ export abstract class AbstractControl {
* ```
*/
setErrors(errors: {[key: string]: any}, {emitEvent}: {emitEvent?: boolean} = {}): void {
emitEvent = isPresent(emitEvent) ? emitEvent : true;
this._errors = errors;
this._updateControlsErrors(emitEvent);
this._updateControlsErrors(emitEvent !== false);
}
/**
@ -495,12 +484,8 @@ export abstract class AbstractControl {
* If no path is given, it checks for the error on the present control.
*/
getError(errorCode: string, path: string[] = null): any {
const control = isPresent(path) && (path.length > 0) ? this.get(path) : this;
if (isPresent(control) && isPresent(control._errors)) {
return control._errors[errorCode];
} else {
return null;
}
const control = path ? this.get(path) : this;
return control && control._errors ? control._errors[errorCode] : null;
}
/**
@ -510,7 +495,7 @@ export abstract class AbstractControl {
* If no path is given, it checks for the error on the present control.
*/
hasError(errorCode: string, path: string[] = null): boolean {
return isPresent(this.getError(errorCode, path));
return !!this.getError(errorCode, path);
}
/**
@ -519,7 +504,7 @@ export abstract class AbstractControl {
get root(): AbstractControl {
let x: AbstractControl = this;
while (isPresent(x._parent)) {
while (x._parent) {
x = x._parent;
}
@ -534,7 +519,7 @@ export abstract class AbstractControl {
this._statusChanges.emit(this._status);
}
if (isPresent(this._parent)) {
if (this._parent) {
this._parent._updateControlsErrors(emitEvent);
}
}
@ -548,7 +533,7 @@ export abstract class AbstractControl {
private _calculateStatus(): string {
if (this._allControlsDisabled()) return DISABLED;
if (isPresent(this._errors)) return INVALID;
if (this._errors) return INVALID;
if (this._anyControlsHaveStatus(PENDING)) return PENDING;
if (this._anyControlsHaveStatus(INVALID)) return INVALID;
return VALID;
@ -585,7 +570,7 @@ export abstract class AbstractControl {
_updatePristine({onlySelf}: {onlySelf?: boolean} = {}): void {
this._pristine = !this._anyControlsDirty();
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent._updatePristine({onlySelf});
}
}
@ -594,7 +579,7 @@ export abstract class AbstractControl {
_updateTouched({onlySelf}: {onlySelf?: boolean} = {}): void {
this._touched = this._anyControlsTouched();
if (isPresent(this._parent) && !onlySelf) {
if (this._parent && !onlySelf) {
this._parent._updateTouched({onlySelf});
}
}
@ -691,12 +676,9 @@ export class FormControl extends AbstractControl {
emitModelToViewChange?: boolean,
emitViewToModelChange?: boolean
} = {}): void {
emitModelToViewChange = isPresent(emitModelToViewChange) ? emitModelToViewChange : true;
emitViewToModelChange = isPresent(emitViewToModelChange) ? emitViewToModelChange : true;
this._value = value;
if (this._onChange.length && emitModelToViewChange) {
this._onChange.forEach((changeFn) => changeFn(this._value, emitViewToModelChange));
if (this._onChange.length && emitModelToViewChange !== false) {
this._onChange.forEach((changeFn) => changeFn(this._value, emitViewToModelChange !== false));
}
this.updateValueAndValidity({onlySelf, emitEvent});
}

View File

@ -13,8 +13,6 @@ import {By} from '@angular/platform-browser/src/dom/debug/by';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {dispatchEvent} from '@angular/platform-browser/testing/browser_util';
import {ListWrapper} from '../src/facade/collection';
export function main() {
describe('reactive forms integration tests', () => {
@ -1862,17 +1860,10 @@ class UniqLoginValidator implements Validator {
}
function sortedClassList(el: HTMLElement) {
var l = getDOM().classList(el);
ListWrapper.sort(l);
return l;
return getDOM().classList(el).sort();
}
@Component({
selector: 'form-control-comp',
template: `
<input type="text" [formControl]="control">
`
})
@Component({selector: 'form-control-comp', template: `<input type="text" [formControl]="control">`})
class FormControlComp {
control: FormControl;
}
@ -1882,8 +1873,7 @@ class FormControlComp {
template: `
<form [formGroup]="form" (ngSubmit)="event=$event">
<input type="text" formControlName="login">
</form>
`
</form>`
})
class FormGroupComp {
control: FormControl;
@ -1901,8 +1891,7 @@ class FormGroupComp {
<input formControlName="password">
</div>
<input *ngIf="form.contains('email')" formControlName="email">
</form>
`
</form>`
})
class NestedFormGroupComp {
form: FormGroup;
@ -1910,9 +1899,7 @@ class NestedFormGroupComp {
@Component({
selector: 'form-control-number-input',
template: `
<input type="number" [formControl]="control">
`
template: `<input type="number" [formControl]="control">`
})
class FormControlNumberInput {
control: FormControl;
@ -1920,9 +1907,7 @@ class FormControlNumberInput {
@Component({
selector: 'form-control-range-input',
template: `
<input type="range" [formControl]="control">
`
template: `<input type="range" [formControl]="control">`
})
class FormControlRangeInput {
control: FormControl;
@ -1938,8 +1923,7 @@ class FormControlRangeInput {
<input type="radio" formControlName="drink" value="sprite">
</form>
<input type="radio" [formControl]="showRadio" value="yes">
<input type="radio" [formControl]="showRadio" value="no">
`
<input type="radio" [formControl]="showRadio" value="no">`
})
class FormControlRadioButtons {
form: FormGroup;
@ -1955,8 +1939,7 @@ class FormControlRadioButtons {
<input [formControlName]="i">
</div>
</div>
</div>
`
</div>`
})
class FormArrayComp {
form: FormGroup;
@ -1973,8 +1956,7 @@ class FormArrayComp {
<input formControlName="state">
</div>
</div>
</div>
`
</div>`
})
class FormArrayNestedGroup {
form: FormGroup;
@ -1988,8 +1970,7 @@ class FormArrayNestedGroup {
<select formControlName="city">
<option *ngFor="let c of cities" [value]="c"></option>
</select>
</div>
`
</div>`
})
class FormControlNameSelect {
cities = ['SF', 'NY'];
@ -2001,8 +1982,7 @@ class FormControlNameSelect {
template: `
<div [formGroup]="form">
<input type="text" formControlName="login" wrapped-value>
</div>
`
</div>`
})
class WrappedValueForm {
form: FormGroup;
@ -2013,8 +1993,7 @@ class WrappedValueForm {
template: `
<div [formGroup]="form">
<my-input formControlName="login"></my-input>
</div>
`
</div>`
})
class MyInputForm {
form: FormGroup;
@ -2025,8 +2004,7 @@ class MyInputForm {
template: `
<div [formGroup]="form">
<input type="text" formControlName="login" [(ngModel)]="login">
</div>
`
</div>`
})
class FormGroupNgModel {
form: FormGroup;
@ -2035,9 +2013,7 @@ class FormGroupNgModel {
@Component({
selector: 'form-control-ng-model',
template: `
<input type="text" [formControl]="control" [(ngModel)]="login">
`
template: `<input type="text" [formControl]="control" [(ngModel)]="login">`
})
class FormControlNgModel {
control: FormControl;
@ -2052,8 +2028,7 @@ class FormControlNgModel {
<input type="text" formControlName="min" minlength="3">
<input type="text" formControlName="max" maxlength="3">
<input type="text" formControlName="pattern" pattern=".{3,}">
</div>
`
</div>`
})
class LoginIsEmptyWrapper {
form: FormGroup;
@ -2067,8 +2042,7 @@ class LoginIsEmptyWrapper {
<input name="minlength" type="text" formControlName="min" [minlength]="minLen">
<input name="maxlength" type="text" formControlName="max" [maxlength]="maxLen">
<input name="pattern" type="text" formControlName="pattern" [pattern]="pattern">
</div>
`
</div>`
})
class ValidationBindingsForm {
form: FormGroup;
@ -2083,8 +2057,7 @@ class ValidationBindingsForm {
template: `
<div [formGroup]="form">
<input type="text" formControlName="login" uniq-login-validator="expected">
</div>
`
</div>`
})
class UniqLoginWrapper {
form: FormGroup;

View File

@ -9,7 +9,6 @@
import {GetTestability, Testability, TestabilityRegistry, setTestabilityGetter} from '@angular/core';
import {getDOM} from '../dom/dom_adapter';
import {ListWrapper} from '../facade/collection';
import {global, isPresent} from '../facade/lang';
export class BrowserGetTestability implements GetTestability {
@ -45,7 +44,7 @@ export class BrowserGetTestability implements GetTestability {
};
if (!global['frameworkStabilizers']) {
global['frameworkStabilizers'] = ListWrapper.createGrowableSize(0);
global['frameworkStabilizers'] = [];
}
global['frameworkStabilizers'].push(whenAllStable);
}

View File

@ -58,7 +58,7 @@ export class KeyEventsPlugin extends EventManagerPlugin {
var fullKey = '';
modifierKeys.forEach(modifierName => {
if (ListWrapper.contains(parts, modifierName)) {
if (parts.indexOf(modifierName) > -1) {
ListWrapper.remove(parts, modifierName);
fullKey += modifierName + '.';
}

View File

@ -8,7 +8,7 @@
import {NgZone} from '@angular/core';
import {ListWrapper} from './facade/collection';
import {MapWrapper} from './facade/collection';
import {global, isPresent} from './facade/lang';
import {getDOM} from './private_import_platform-browser';
@ -18,7 +18,7 @@ export class BrowserDetection {
if (isPresent(this._overrideUa)) {
return this._overrideUa;
} else {
return isPresent(getDOM()) ? getDOM().getUserAgent() : '';
return getDOM() ? getDOM().getUserAgent() : '';
}
}
@ -102,9 +102,7 @@ export function stringifyElement(el: any /** TODO #9100 */): string {
// Attributes in an ordered way
var attributeMap = getDOM().attributeMap(el);
var keys: any[] /** TODO #9100 */ = [];
attributeMap.forEach((v, k) => keys.push(k));
ListWrapper.sort(keys);
var keys: string[] = MapWrapper.keys(attributeMap).sort();
for (let i = 0; i < keys.length; i++) {
var key = keys[i];
var attValue = attributeMap.get(key);
@ -124,7 +122,7 @@ export function stringifyElement(el: any /** TODO #9100 */): string {
}
// Closing tag
if (!ListWrapper.contains(_singleTagWhitelist, tagName)) {
if (_singleTagWhitelist.indexOf(tagName) == -1) {
result += `</${tagName}>`;
}
} else if (getDOM().isCommentNode(el)) {

View File

@ -382,7 +382,7 @@ export class Parse5DomAdapter extends DomAdapter {
}
}
hasClass(element: any, className: string): boolean {
return ListWrapper.contains(this.classList(element), className);
return this.classList(element).indexOf(className) > -1;
}
hasStyle(element: any, styleName: string, styleValue: string = null): boolean {
const value = this.getStyle(element, styleName) || '';

View File

@ -1,6 +1,5 @@
import {PromiseWrapper} from '@angular/facade/src/async';
import {ListWrapper, Map, MapWrapper} from '@angular/facade/src/collection';
import {Type, isPresent, print} from '@angular/facade/src/lang';
import {Type, print} from '@angular/facade/src/lang';
import {bootstrap} from '@angular/platform-browser';
import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';
import {DOM} from '@angular/platform-browser/src/dom/dom_adapter';
@ -68,7 +67,7 @@ class MultiplyDirectiveResolver extends DirectiveResolver {
_fillCache(component: Type) {
var view = super.resolve(component);
var multipliedTemplates = ListWrapper.createFixedSize(this._multiplyBy);
var multipliedTemplates = new Array(this._multiplyBy);
for (var i = 0; i < this._multiplyBy; ++i) {
multipliedTemplates[i] = view.template;
}

View File

@ -11,7 +11,7 @@ var testList = null;
export function main() {
var size = getIntParameter('size');
testList = ListWrapper.createFixedSize(size);
testList = new Array(size);
platformBrowserDynamic().bootstrapModule(AppModule).then((ref) => {
var injector = ref.injector;

View File

@ -1,6 +1,5 @@
import {NgFor} from '@angular/common';
import {Component, Directive} from '@angular/core';
import {ListWrapper, Map} from '@angular/facade/src/collection';
import {Account, Company, CustomDate, Offering, Opportunity, STATUS_LIST} from './common';
@ -81,17 +80,19 @@ export class StageButtonsComponent extends HasStyle {
_computeStageButtons() {
var disabled = true;
this.stages = ListWrapper.clone(STATUS_LIST.map((status) => {
var isCurrent = this._offering.status == status;
var stage = new Stage();
stage.name = status;
stage.isDisabled = disabled;
stage.backgroundColor = disabled ? '#DDD' : isCurrent ? '#DDF' : '#FDD';
if (isCurrent) {
disabled = false;
}
return stage;
}));
this.stages = STATUS_LIST
.map((status) => {
const isCurrent = this._offering.status == status;
const stage = new Stage();
stage.name = status;
stage.isDisabled = disabled;
stage.backgroundColor = disabled ? '#DDD' : isCurrent ? '#DDF' : '#FDD';
if (isCurrent) {
disabled = false;
}
return stage;
})
.slice();
}
}

View File

@ -1,4 +1,3 @@
import {ListWrapper, Map, MapWrapper} from '@angular/facade/src/collection';
import {Math} from '@angular/facade/src/math';
export var ITEMS = 1000;
@ -62,7 +61,7 @@ export class RawEntity {
return this._data[key];
}
var pieces = key.split('.');
var last = ListWrapper.last(pieces);
var last = pieces[pieces.length - 1];
pieces.length = pieces.length - 1;
var target = this._resolve(pieces, this);
if (target == null) {
@ -77,7 +76,7 @@ export class RawEntity {
return;
}
var pieces = key.split('.');
var last = ListWrapper.last(pieces);
var last = pieces[pieces.length - 1];
pieces.length = pieces.length - 1;
var target = this._resolve(pieces, this);
target[last] = value;
@ -88,7 +87,7 @@ export class RawEntity {
return this._data.delete(key);
}
var pieces = key.split('.');
var last = ListWrapper.last(pieces);
var last = pieces[pieces.length - 1];
pieces.length = pieces.length - 1;
var target = this._resolve(pieces, this);
return target.remove(last);

View File

@ -1,7 +1,5 @@
import {NgFor} from '@angular/common';
import {Component, Directive} from '@angular/core';
import {ListWrapper} from '@angular/facade/src/collection';
import {Math} from '@angular/facade/src/math';
import {HEIGHT, ITEMS, ITEM_HEIGHT, Offering, ROW_WIDTH, VIEW_PORT_HEIGHT, VISIBLE_ITEMS} from './common';
import {generateOfferings} from './random_data';
@ -63,6 +61,6 @@ export class ScrollAreaComponent {
if (this.paddingDiv != null) {
this.paddingDiv.style.setProperty('height', `${padding}px`);
}
this.visibleItems = ListWrapper.slice(this._fullList, iStart, iEnd);
this.visibleItems = this._fullList.slice(iStart, iEnd);
}
}

View File

@ -46,7 +46,7 @@ export class Store<T extends KeyModel> {
private _spliceOut(record: T) {
var i = this._indexFor(record);
if (i > -1) {
return ListWrapper.splice(this.list, i, 1)[0];
return this.list.splice(i, 1)[0];
}
return null;
}

View File

@ -50,7 +50,7 @@ export class Store {
private _spliceOut(record: KeyModel) {
var i = this._indexFor(record);
if (i > -1) {
return ListWrapper.splice(this.list, i, 1)[0];
return this.list.splice(i, 1)[0];
}
return null;
}