refactor: misc cleanup (#11654)

This commit is contained in:
Victor Berchet 2016-09-19 17:15:57 -07:00 committed by Alex Eagle
parent 51d73d3e4e
commit 671f73448c
37 changed files with 112 additions and 196 deletions

View File

@ -6,18 +6,15 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Map} from './facade/collection';
import {Date, DateWrapper} from './facade/lang';
export class MeasureValues {
constructor(
public runIndex: number, public timeStamp: Date, public values: {[key: string]: any}) {}
toJson() {
return {
'timeStamp': DateWrapper.toJson(this.timeStamp),
'timeStamp': this.timeStamp.toJSON(),
'runIndex': this.runIndex,
'values': this.values
'values': this.values,
};
}
}

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable, OpaqueToken, Provider} from '@angular/core';
import {Inject, Injectable} from '@angular/core';
import {Options} from '../common_options';
import {StringMapWrapper} from '../facade/collection';
@ -48,9 +48,9 @@ export class UserMetric extends Metric {
if (values.every(isNumber)) {
Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`)))
.then((_: any[]) => {
let map = StringMapWrapper.create();
let map: {[k: string]: any} = {};
for (let i = 0, n = names.length; i < n; i++) {
StringMapWrapper.set(map, names[i], values[i]);
map[names[i]] = values[i];
}
resolve(map);
}, reject);

View File

@ -33,7 +33,7 @@ export function main() {
new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true});
}
if (isBlank(microMetrics)) {
microMetrics = StringMapWrapper.create();
microMetrics = {};
}
var providers: Provider[] = [
Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS,

View File

@ -24,7 +24,7 @@ export function main() {
new PerfLogFeatures({render: true, gc: true, frameCapture: true, userTiming: true});
}
if (isBlank(userMetrics)) {
userMetrics = StringMapWrapper.create();
userMetrics = {};
}
wdAdapter = new MockDriverAdapter();
var providers: Provider[] = [

View File

@ -376,7 +376,7 @@ export class AstTransformer implements AstVisitor {
}
visitAll(asts: any[]): any[] {
var res = ListWrapper.createFixedSize(asts.length);
var res = new Array(asts.length);
for (var i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this);
}

View File

@ -117,7 +117,7 @@ export class CompileElement extends CompileNode {
setComponentView(compViewExpr: o.Expression) {
this._compViewExpr = compViewExpr;
this.contentNodesByNgContentIndex =
ListWrapper.createFixedSize(this.component.template.ngContentSelectors.length);
new Array(this.component.template.ngContentSelectors.length);
for (var i = 0; i < this.contentNodesByNgContentIndex.length; i++) {
this.contentNodesByNgContentIndex[i] = [];
}

View File

@ -8,8 +8,7 @@
import {DirectiveResolver} from '@angular/compiler';
import {AnimationEntryMetadata, Compiler, Component, Directive, Injectable, Injector, Provider, Type, resolveForwardRef} from '@angular/core';
import {Map} from './facade/collection';
import {isArray, isPresent} from './facade/lang';
import {isPresent} from './facade/lang';
import {ViewMetadata} from './private_import_core';
@ -156,7 +155,7 @@ function flattenArray(tree: any[], out: Array<Type<any>|any[]>): void {
if (!isPresent(tree)) return;
for (var i = 0; i < tree.length; i++) {
var item = resolveForwardRef(tree[i]);
if (isArray(item)) {
if (Array.isArray(item)) {
flattenArray(item, out);
} else {
out.push(item);

View File

@ -9,18 +9,12 @@
import {NgModuleResolver} from '@angular/compiler';
import {Compiler, Injectable, Injector, NgModule, Type} from '@angular/core';
import {Map} from './facade/collection';
@Injectable()
export class MockNgModuleResolver extends NgModuleResolver {
private _ngModules = new Map<Type<any>, NgModule>();
constructor(private _injector: Injector) { super(); }
private get _compiler(): Compiler { return this._injector.get(Compiler); }
private _clearCacheFor(component: Type<any>) { this._compiler.clearCacheFor(component); }
/**
* Overrides the {@link NgModule} for a module.
*/
@ -36,10 +30,10 @@ export class MockNgModuleResolver extends NgModuleResolver {
* `NgModuleResolver`, see `setNgModule`.
*/
resolve(type: Type<any>, throwIfNotFound = true): NgModule {
var metadata = this._ngModules.get(type);
if (!metadata) {
metadata = super.resolve(type, throwIfNotFound);
}
return metadata;
return this._ngModules.get(type) || super.resolve(type, throwIfNotFound);
}
private get _compiler(): Compiler { return this._injector.get(Compiler); }
private _clearCacheFor(component: Type<any>) { this._compiler.clearCacheFor(component); }
}

View File

@ -9,8 +9,6 @@
import {PipeResolver} from '@angular/compiler';
import {Compiler, Injectable, Injector, Pipe, Type} from '@angular/core';
import {Map} from './facade/collection';
@Injectable()
export class MockPipeResolver extends PipeResolver {
private _pipes = new Map<Type<any>, Pipe>();

View File

@ -7,11 +7,9 @@
*/
import {ResourceLoader} from '@angular/compiler';
import {ListWrapper, Map} from './facade/collection';
import {ListWrapper} from './facade/collection';
import {isBlank, normalizeBlank} from './facade/lang';
/**
* A mock implementation of {@link ResourceLoader} that allows outgoing requests to be mocked
* and responded to within a single test, without going to the network.

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper, Map, StringMapWrapper} from '../facade/collection';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {AnimationPlayer} from './animation_player';
@ -47,12 +47,12 @@ export class ViewAnimationMap {
getAllPlayers(): AnimationPlayer[] { return this._allPlayers; }
remove(element: any, animationName: string): void {
var playersByAnimation = this._map.get(element);
if (isPresent(playersByAnimation)) {
var player = playersByAnimation[animationName];
const playersByAnimation = this._map.get(element);
if (playersByAnimation) {
const player = playersByAnimation[animationName];
delete playersByAnimation[animationName];
var index = this._allPlayers.indexOf(player);
ListWrapper.removeAt(this._allPlayers, index);
const index = this._allPlayers.indexOf(player);
this._allPlayers.splice(index, 1);
if (StringMapWrapper.isEmpty(playersByAnimation)) {
this._map.delete(element);

View File

@ -121,7 +121,7 @@ export class ReflectiveProtoInjectorDynamicStrategy implements ReflectiveProtoIn
constructor(protoInj: ReflectiveProtoInjector, public providers: ResolvedReflectiveProvider[]) {
var len = providers.length;
this.keyIds = ListWrapper.createFixedSize(len);
this.keyIds = new Array(len);
for (var i = 0; i < len; i++) {
this.keyIds[i] = providers[i].key.id;
@ -286,7 +286,7 @@ export class ReflectiveInjectorDynamicStrategy implements ReflectiveInjectorStra
constructor(
public protoStrategy: ReflectiveProtoInjectorDynamicStrategy,
public injector: ReflectiveInjector_) {
this.objs = ListWrapper.createFixedSize(protoStrategy.providers.length);
this.objs = new Array(protoStrategy.providers.length);
ListWrapper.fill(this.objs, UNDEFINED);
}
@ -648,7 +648,7 @@ export class ReflectiveInjector_ implements ReflectiveInjector {
private _instantiateProvider(provider: ResolvedReflectiveProvider): any {
if (provider.multiProvider) {
var res = ListWrapper.createFixedSize(provider.resolvedFactories.length);
var res = new Array(provider.resolvedFactories.length);
for (var i = 0; i < provider.resolvedFactories.length; ++i) {
res[i] = this._instantiate(provider, provider.resolvedFactories[i]);
}

View File

@ -77,7 +77,7 @@ export function ensureSlotCount(projectableNodes: any[][], expectedSlotCount: nu
res = EMPTY_ARR;
} else if (projectableNodes.length < expectedSlotCount) {
var givenSlotCount = projectableNodes.length;
res = ListWrapper.createFixedSize(expectedSlotCount);
res = new Array(expectedSlotCount);
for (var i = 0; i < expectedSlotCount; i++) {
res[i] = (i < givenSlotCount) ? projectableNodes[i] : EMPTY_ARR;
}

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Map, MapWrapper, Set, SetWrapper, StringMapWrapper} from '../facade/collection';
import {MapWrapper, SetWrapper, StringMapWrapper} from '../facade/collection';
import {isPresent} from '../facade/lang';
import {Type} from '../type';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
@ -40,14 +40,9 @@ export class Reflector extends ReflectorReader {
/** @internal */
_methods = new Map<string, MethodFn>();
/** @internal */
_usedKeys: Set<any>;
reflectionCapabilities: PlatformReflectionCapabilities;
_usedKeys: Set<any> = null;
constructor(reflectionCapabilities: PlatformReflectionCapabilities) {
super();
this._usedKeys = null;
this.reflectionCapabilities = reflectionCapabilities;
}
constructor(public reflectionCapabilities: PlatformReflectionCapabilities) { super(); }
updateCapabilities(caps: PlatformReflectionCapabilities) { this.reflectionCapabilities = caps; }

View File

@ -7,7 +7,7 @@
*/
import {Injectable} from '../di';
import {Map, MapWrapper} from '../facade/collection';
import {MapWrapper} from '../facade/collection';
import {scheduleMicroTask} from '../facade/lang';
import {NgZone} from '../zone/ng_zone';
@ -110,6 +110,7 @@ export class Testability implements PublicTestability {
getPendingRequestCount(): number { return this._pendingCount; }
/** @deprecated use findProviders */
findBindings(using: any, provider: string, exactMatch: boolean): any[] {
// TODO(juliemr): implement.
return [];

View File

@ -8,12 +8,9 @@
import {getSymbolIterator, global, isArray, isBlank, isJsObject, isPresent} from './lang';
export var Map = global.Map;
export var Set = global.Set;
// Safari and Internet Explorer do not support the iterable parameter to the
// Map constructor. We work around that by manually adding the items.
var createMapFromPairs: {(pairs: any[]): Map<any, any>} = (function() {
const createMapFromPairs: {(pairs: any[]): Map<any, any>} = (function() {
try {
if (new Map(<any>[[1, 2]]).size === 1) {
return function createMapFromPairs(pairs: any[]): Map<any, any> { return new Map(pairs); };
@ -29,7 +26,7 @@ var createMapFromPairs: {(pairs: any[]): Map<any, any>} = (function() {
return map;
};
})();
var createMapFromMap: {(m: Map<any, any>): Map<any, any>} = (function() {
const createMapFromMap: {(m: Map<any, any>): Map<any, any>} = (function() {
try {
if (new Map(<any>new Map())) {
return function createMapFromMap(m: Map<any, any>): Map<any, any> { return new Map(<any>m); };
@ -42,7 +39,7 @@ var createMapFromMap: {(m: Map<any, any>): Map<any, any>} = (function() {
return map;
};
})();
var _clearValues: {(m: Map<any, any>): void} = (function() {
const _clearValues: {(m: Map<any, any>): void} = (function() {
if ((<any>(new Map()).keys()).next) {
return function _clearValues(m: Map<any, any>) {
var keyIterator = m.keys();
@ -69,7 +66,7 @@ var _arrayFromMap: {(m: Map<any, any>, getValues: boolean): any[]} = (function()
} catch (e) {
}
return function createArrayFromMapWithForeach(m: Map<any, any>, getValues: boolean): any[] {
var res = ListWrapper.createFixedSize(m.size), i = 0;
var res = new Array(m.size), i = 0;
m.forEach((v, k) => {
res[i] = getValues ? v : k;
i++;
@ -79,7 +76,6 @@ var _arrayFromMap: {(m: Map<any, any>, getValues: boolean): any[]} = (function()
})();
export class MapWrapper {
static clone<K, V>(m: Map<K, V>): Map<K, V> { return createMapFromMap(m); }
static createFromStringMap<T>(stringMap: {[key: string]: T}): Map<string, T> {
var result = new Map<string, T>();
for (var prop in stringMap) {
@ -93,7 +89,6 @@ export class MapWrapper {
return r;
}
static createFromPairs(pairs: any[]): Map<any, any> { return createMapFromPairs(pairs); }
static clearValues(m: Map<any, any>) { _clearValues(m); }
static iterable<T>(m: T): T { return m; }
static keys<K>(m: Map<K, any>): K[] { return _arrayFromMap(m, false); }
static values<V>(m: Map<any, V>): V[] { return _arrayFromMap(m, true); }
@ -103,15 +98,6 @@ export class MapWrapper {
* Wraps Javascript Objects
*/
export class StringMapWrapper {
static create(): {[k: /*any*/ string]: any} {
// Note: We are not using Object.create(null) here due to
// performance!
// http://jsperf.com/ng2-object-create-null
return {};
}
static contains(map: {[key: string]: any}, key: string): boolean {
return map.hasOwnProperty(key);
}
static get<V>(map: {[key: string]: V}, key: string): V {
return map.hasOwnProperty(key) ? map[key] : undefined;
}
@ -127,7 +113,6 @@ export class StringMapWrapper {
}
return true;
}
static delete (map: {[key: string]: any}, key: string) { delete map[key]; }
static forEach<K, V>(map: {[key: string]: V}, callback: (v: V, K: string) => void) {
for (let k of Object.keys(map)) {
callback(map[k], k);

View File

@ -9,7 +9,6 @@
import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection';
import {FormControl} from '../../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../../validators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '../control_value_accessor';
@ -117,6 +116,6 @@ export class FormControlDirective extends NgControl implements OnChanges {
}
private _isControlChanged(changes: {[key: string]: any}): boolean {
return StringMapWrapper.contains(changes, 'form');
return changes.hasOwnProperty('form');
}
}

View File

@ -9,7 +9,7 @@
import {Directive, Inject, Input, OnChanges, Optional, Output, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {ListWrapper} from '../../facade/collection';
import {isBlank} from '../../facade/lang';
import {FormArray, FormControl, FormGroup} from '../../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from '../../validators';
@ -80,7 +80,7 @@ export class FormGroupDirective extends ControlContainer implements Form,
ngOnChanges(changes: SimpleChanges): void {
this._checkFormPresent();
if (StringMapWrapper.contains(changes, 'form')) {
if (changes.hasOwnProperty('form')) {
this._updateValidators();
this._updateDomValue();
this._updateRegistrations();

View File

@ -7,7 +7,7 @@
*/
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {ListWrapper} from '../facade/collection';
import {hasConstructor, isBlank, isPresent, looseIdentical} from '../facade/lang';
import {FormArray, FormControl, FormGroup} from '../model';
import {Validators} from '../validators';
@ -120,8 +120,8 @@ export function composeAsyncValidators(validators: /* Array<Validator|Function>
}
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {
if (!StringMapWrapper.contains(changes, 'model')) return false;
var change = changes['model'];
if (!changes.hasOwnProperty('model')) return false;
const change = changes['model'];
if (change.isFirstChange()) return true;
return !looseIdentical(viewModel, change.currentValue);

View File

@ -16,7 +16,6 @@ import {isBlank, isPresent, isStringMap, normalizeBool} from './facade/lang';
import {isPromise} from './private_import_core';
/**
* Indicates that a FormControl is valid, i.e. that no errors exist in the input value.
*/
@ -886,7 +885,7 @@ export class FormGroup extends AbstractControl {
*/
removeControl(name: string): void {
if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
StringMapWrapper.delete(this.controls, name);
delete (this.controls[name]);
this.updateValueAndValidity();
this._onCollectionChange();
}
@ -896,7 +895,7 @@ export class FormGroup extends AbstractControl {
*/
setControl(name: string, control: AbstractControl): void {
if (this.controls[name]) this.controls[name]._registerOnCollectionChange(() => {});
StringMapWrapper.delete(this.controls, name);
delete (this.controls[name]);
if (control) this.registerControl(name, control);
this.updateValueAndValidity();
this._onCollectionChange();

View File

@ -7,7 +7,7 @@
*/
import {ListWrapper, Map, MapWrapper, StringMapWrapper, isListLikeIterable, iterateListLike} from '../src/facade/collection';
import {ListWrapper, MapWrapper, StringMapWrapper, isListLikeIterable, iterateListLike} from '../src/facade/collection';
import {isBlank} from '../src/facade/lang';

View File

@ -6,9 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ListWrapper, Map, isListLikeIterable} from '../src/facade/collection';
import {isPresent} from '../src/facade/lang';
function paramParser(rawParams: string = ''): Map<string, string[]> {
const map = new Map<string, string[]>();
if (rawParams.length > 0) {
@ -97,23 +94,16 @@ export class URLSearchParams {
has(param: string): boolean { return this.paramsMap.has(param); }
get(param: string): string {
var storedParam = this.paramsMap.get(param);
if (isListLikeIterable(storedParam)) {
return ListWrapper.first(storedParam);
} else {
return null;
}
const storedParam = this.paramsMap.get(param);
return Array.isArray(storedParam) ? storedParam[0] : null;
}
getAll(param: string): string[] {
var mapParam = this.paramsMap.get(param);
return isPresent(mapParam) ? mapParam : [];
}
getAll(param: string): string[] { return this.paramsMap.get(param) || []; }
set(param: string, val: string) {
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
ListWrapper.clear(list);
const list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(val);
this.paramsMap.set(param, list);
}
@ -126,17 +116,15 @@ export class URLSearchParams {
// TODO(@caitp): document this better
setAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
ListWrapper.clear(list);
const list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(value[0]);
this.paramsMap.set(param, list);
});
}
append(param: string, val: string): void {
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
const list = this.paramsMap.get(param) || [];
list.push(val);
this.paramsMap.set(param, list);
}
@ -150,9 +138,8 @@ export class URLSearchParams {
// TODO(@caitp): document this better
appendAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
for (var i = 0; i < value.length; ++i) {
const list = this.paramsMap.get(param) || [];
for (let i = 0; i < value.length; ++i) {
list.push(value[i]);
}
this.paramsMap.set(param, list);
@ -169,9 +156,8 @@ export class URLSearchParams {
// TODO(@caitp): document this better
replaceAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
var mapParam = this.paramsMap.get(param);
var list = isPresent(mapParam) ? mapParam : [];
ListWrapper.clear(list);
const list = this.paramsMap.get(param) || [];
list.length = 0;
for (var i = 0; i < value.length; ++i) {
list.push(value[i]);
}
@ -180,7 +166,7 @@ export class URLSearchParams {
}
toString(): string {
var paramsList: string[] = [];
const paramsList: string[] = [];
this.paramsMap.forEach((values, k) => {
values.forEach(
v => paramsList.push(

View File

@ -9,19 +9,16 @@
import {ReflectiveInjector} from '@angular/core';
import {AsyncTestCompleter, SpyObject, afterEach, beforeEach, ddescribe, describe, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing/matchers';
import {BrowserJsonp} from '../../src/backends/browser_jsonp';
import {JSONPBackend, JSONPBackend_, JSONPConnection, JSONPConnection_} from '../../src/backends/jsonp_backend';
import {BaseRequestOptions, RequestOptions} from '../../src/base_request_options';
import {BaseResponseOptions, ResponseOptions} from '../../src/base_response_options';
import {ReadyState, RequestMethod, ResponseType} from '../../src/enums';
import {Map} from '../../src/facade/collection';
import {isPresent} from '../../src/facade/lang';
import {Request} from '../../src/static_request';
import {Response} from '../../src/static_response';
var existingScripts: MockBrowserJsonp[] = [];
var unused: Response;
class MockBrowserJsonp extends BrowserJsonp {
src: string;

View File

@ -15,7 +15,6 @@ import {CookieXSRFStrategy, XHRBackend, XHRConnection} from '../../src/backends/
import {BaseRequestOptions, RequestOptions} from '../../src/base_request_options';
import {BaseResponseOptions, ResponseOptions} from '../../src/base_response_options';
import {ResponseContentType, ResponseType} from '../../src/enums';
import {Map} from '../../src/facade/collection';
import {Json} from '../../src/facade/lang';
import {Headers} from '../../src/headers';
import {XSRFStrategy} from '../../src/interfaces';
@ -27,9 +26,7 @@ var abortSpy: any;
var sendSpy: any;
var openSpy: any;
var setRequestHeaderSpy: any;
var addEventListenerSpy: any;
var existingXHRs: MockBrowserXHR[] = [];
var unused: Response;
class MockBrowserXHR extends BrowserXhr {
abort: any;

View File

@ -7,8 +7,6 @@
*/
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {Map, StringMapWrapper} from '../src/facade/collection';
import {Json} from '../src/facade/lang';
import {Headers} from '../src/headers';
@ -24,21 +22,20 @@ export function main() {
// Spec at https://tools.ietf.org/html/rfc2616
expect(firstHeaders.get('content-type')).toBe('image/jpeg');
expect(firstHeaders.get('content-Type')).toBe('image/jpeg');
var httpHeaders = StringMapWrapper.create();
StringMapWrapper.set(httpHeaders, 'Content-Type', 'image/jpeg');
StringMapWrapper.set(httpHeaders, 'Accept-Charset', 'utf-8');
StringMapWrapper.set(httpHeaders, 'X-My-Custom-Header', 'Zeke are cool');
var secondHeaders = new Headers(httpHeaders);
var secondHeadersObj = new Headers(secondHeaders);
const httpHeaders = {
'Content-Type': 'image/jpeg',
'Accept-Charset': 'utf-8',
'X-My-Custom-Header': 'Zeke are cool',
};
const secondHeaders = new Headers(httpHeaders);
const secondHeadersObj = new Headers(secondHeaders);
expect(secondHeadersObj.get('Content-Type')).toBe('image/jpeg');
});
describe('initialization', () => {
it('should merge values in provided dictionary', () => {
var map = StringMapWrapper.create();
StringMapWrapper.set(map, 'foo', 'bar');
var headers = new Headers(map);
var headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toBe('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
});
@ -55,9 +52,7 @@ export function main() {
describe('.set()', () => {
it('should clear all values and re-set for the provided key', () => {
var map = StringMapWrapper.create();
StringMapWrapper.set(map, 'foo', 'bar');
var headers = new Headers(map);
var headers = new Headers({'foo': 'bar'});
expect(headers.get('foo')).toBe('bar');
expect(headers.getAll('foo')).toEqual(['bar']);
headers.set('foo', 'baz');

View File

@ -164,7 +164,7 @@ export class BrowserDomAdapter extends GenericBrowserDomAdapter {
childNodes(el: any /** TODO #9100 */): Node[] { return el.childNodes; }
childNodesAsList(el: any /** TODO #9100 */): any[] {
var childNodes = el.childNodes;
var res = ListWrapper.createFixedSize(childNodes.length);
var res = new Array(childNodes.length);
for (var i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}

View File

@ -6,8 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {StringMapWrapper} from '../../facade/collection';
import {EventManagerPlugin} from './event_manager';
var _eventNames = {
@ -53,7 +51,6 @@ export class HammerGesturesPluginCommon extends EventManagerPlugin {
constructor() { super(); }
supports(eventName: string): boolean {
eventName = eventName.toLowerCase();
return StringMapWrapper.contains(_eventNames, eventName);
return _eventNames.hasOwnProperty(eventName.toLowerCase());
}
}

View File

@ -72,7 +72,7 @@ export class KeyEventsPlugin extends EventManagerPlugin {
// returning null instead of throwing to let another plugin process the event
return null;
}
var result = StringMapWrapper.create();
var result = {};
StringMapWrapper.set(result, 'domEventName', domEventName);
StringMapWrapper.set(result, 'fullKey', fullKey);
return result;

View File

@ -11,12 +11,10 @@ import {beforeEach, ddescribe, describe, expect, iit, it, xdescribe, xit} from '
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DomEventsPlugin} from '@angular/platform-browser/src/dom/events/dom_events';
import {EventManager, EventManagerPlugin} from '@angular/platform-browser/src/dom/events/event_manager';
import {ListWrapper, Map} from '../../../src/facade/collection';
import {el} from '../../../testing/browser_util';
export function main() {
var domEventPlugin: any /** TODO #9100 */;
var domEventPlugin: DomEventsPlugin;
describe('EventManager', () => {
@ -29,7 +27,7 @@ export function main() {
var plugin = new FakeEventManagerPlugin(['click']);
var manager = new EventManager([domEventPlugin, plugin], new FakeNgZone());
manager.addEventListener(element, 'click', handler);
expect(plugin._eventHandler.get('click')).toBe(handler);
expect(plugin.eventHandler['click']).toBe(handler);
});
it('should delegate event bindings to the first plugin supporting the event', () => {
@ -41,10 +39,8 @@ export function main() {
var manager = new EventManager([plugin2, plugin1], new FakeNgZone());
manager.addEventListener(element, 'click', clickHandler);
manager.addEventListener(element, 'dblclick', dblClickHandler);
expect(plugin1._eventHandler.has('click')).toBe(false);
expect(plugin2._eventHandler.get('click')).toBe(clickHandler);
expect(plugin2._eventHandler.has('dblclick')).toBe(false);
expect(plugin1._eventHandler.get('dblclick')).toBe(dblClickHandler);
expect(plugin2.eventHandler['click']).toBe(clickHandler);
expect(plugin1.eventHandler['dblclick']).toBe(dblClickHandler);
});
it('should throw when no plugin can handle the event', () => {
@ -91,22 +87,23 @@ export function main() {
});
}
class FakeEventManagerPlugin extends EventManagerPlugin {
/** @internal */
_eventHandler = new Map<string, Function>();
constructor(public _supports: string[]) { super(); }
class FakeEventManagerPlugin extends EventManagerPlugin {
eventHandler: {[event: string]: Function} = {};
supports(eventName: string): boolean { return ListWrapper.contains(this._supports, eventName); }
constructor(public supportedEvents: string[]) { super(); }
addEventListener(element: any /** TODO #9100 */, eventName: string, handler: Function) {
this._eventHandler.set(eventName, handler);
return () => { this._eventHandler.delete(eventName); };
supports(eventName: string): boolean { return this.supportedEvents.indexOf(eventName) > -1; }
addEventListener(element: any, eventName: string, handler: Function) {
this.eventHandler[eventName] = handler;
return () => { delete (this.eventHandler[eventName]); };
}
}
class FakeNgZone extends NgZone {
constructor() { super({enableLongStackTrace: false}); }
run(fn: any /** TODO #9100 */) { fn(); }
run(fn: Function) { fn(); }
runOutsideAngular(fn: any /** TODO #9100 */) { return fn(); }
runOutsideAngular(fn: Function) { return fn(); }
}

View File

@ -12,8 +12,6 @@ import {ListWrapper, StringMapWrapper} from '../src/facade/collection';
import {DomAdapter, setRootDomAdapter} from './private_import_platform-browser';
import {isPresent, isBlank, global, setValueOnPath, DateWrapper} from '../src/facade/lang';
import {SelectorMatcher, CssSelector} from './private_import_compiler';
import {Type} from '@angular/core';
import {ResourceLoader} from '@angular/compiler';
var parser: any /** TODO #9100 */ = null;
var serializer: any /** TODO #9100 */ = null;
@ -136,17 +134,13 @@ export class Parse5DomAdapter extends DomAdapter {
return result;
}
on(el: any /** TODO #9100 */, evt: any /** TODO #9100 */, listener: any /** TODO #9100 */) {
var listenersMap: {[k: /*any*/ string]: any} = el._eventListenersMap;
var listenersMap: {[k: string]: any} = el._eventListenersMap;
if (isBlank(listenersMap)) {
var listenersMap: {[k: /*any*/ string]: any} = StringMapWrapper.create();
var listenersMap: {[k: string]: any} = {};
el._eventListenersMap = listenersMap;
}
var listeners = StringMapWrapper.get(listenersMap, evt);
if (isBlank(listeners)) {
listeners = [];
}
listeners.push(listener);
StringMapWrapper.set(listenersMap, evt, listeners);
const listeners = listenersMap[evt] || [];
listenersMap[evt] = [...listeners, listener];
}
onAndCancel(
el: any /** TODO #9100 */, evt: any /** TODO #9100 */,
@ -209,7 +203,7 @@ export class Parse5DomAdapter extends DomAdapter {
childNodes(el: any /** TODO #9100 */): Node[] { return el.childNodes; }
childNodesAsList(el: any /** TODO #9100 */): any[] {
var childNodes = el.childNodes;
var res = ListWrapper.createFixedSize(childNodes.length);
var res = new Array(childNodes.length);
for (var i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}
@ -489,7 +483,7 @@ export class Parse5DomAdapter extends DomAdapter {
}
removeAttribute(element: any /** TODO #9100 */, attribute: string) {
if (attribute) {
StringMapWrapper.delete(element.attribs, attribute);
delete element.attribs[attribute];
}
}
removeAttributeNS(element: any /** TODO #9100 */, ns: string, name: string) {
@ -507,7 +501,7 @@ export class Parse5DomAdapter extends DomAdapter {
this.appendChild(newDoc, body);
StringMapWrapper.set(newDoc, 'head', head);
StringMapWrapper.set(newDoc, 'body', body);
StringMapWrapper.set(newDoc, '_window', StringMapWrapper.create());
StringMapWrapper.set(newDoc, '_window', {});
return newDoc;
}
defaultDoc(): Document {
@ -546,7 +540,7 @@ export class Parse5DomAdapter extends DomAdapter {
var rules: any[] /** TODO #9100 */ = [];
for (var i = 0; i < parsedRules.length; i++) {
var parsedRule = parsedRules[i];
var rule: {[key: string]: any} = StringMapWrapper.create();
var rule: {[key: string]: any} = {};
StringMapWrapper.set(rule, 'cssText', css);
StringMapWrapper.set(rule, 'style', {content: '', cssText: ''});
if (parsedRule.type == 'rule') {

View File

@ -156,15 +156,11 @@ class MessageData {
}
/**
* Returns the value from the StringMap if present. Otherwise returns null
* Returns the value if present, otherwise returns null
* @internal
*/
_getValueIfPresent(data: {[key: string]: any}, key: string) {
if (StringMapWrapper.contains(data, key)) {
return StringMapWrapper.get(data, key);
} else {
return null;
}
return data.hasOwnProperty(key) ? data[key] : null;
}
}

View File

@ -9,7 +9,6 @@
import {Injectable, NgZone} from '@angular/core';
import {EventEmitter} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection';
import {MessageBus, MessageBusSink, MessageBusSource} from './message_bus';
@ -22,7 +21,7 @@ export interface PostMessageTarget {
export class PostMessageBusSink implements MessageBusSink {
private _zone: NgZone;
private _channels: {[key: string]: _Channel} = StringMapWrapper.create();
private _channels: {[key: string]: _Channel} = {};
private _messageBuffer: Array<Object> = [];
constructor(private _postMessageTarget: PostMessageTarget) {}
@ -34,7 +33,7 @@ export class PostMessageBusSink implements MessageBusSink {
}
initChannel(channel: string, runInZone: boolean = true): void {
if (StringMapWrapper.contains(this._channels, channel)) {
if (this._channels.hasOwnProperty(channel)) {
throw new Error(`${channel} has already been initialized`);
}
@ -52,7 +51,7 @@ export class PostMessageBusSink implements MessageBusSink {
}
to(channel: string): EventEmitter<any> {
if (StringMapWrapper.contains(this._channels, channel)) {
if (this._channels.hasOwnProperty(channel)) {
return this._channels[channel].emitter;
} else {
throw new Error(`${channel} is not set up. Did you forget to call initChannel?`);
@ -71,7 +70,7 @@ export class PostMessageBusSink implements MessageBusSink {
export class PostMessageBusSource implements MessageBusSource {
private _zone: NgZone;
private _channels: {[key: string]: _Channel} = StringMapWrapper.create();
private _channels: {[key: string]: _Channel} = {};
constructor(eventTarget?: EventTarget) {
if (eventTarget) {
@ -86,7 +85,7 @@ export class PostMessageBusSource implements MessageBusSource {
attachToZone(zone: NgZone) { this._zone = zone; }
initChannel(channel: string, runInZone: boolean = true) {
if (StringMapWrapper.contains(this._channels, channel)) {
if (this._channels.hasOwnProperty(channel)) {
throw new Error(`${channel} has already been initialized`);
}
@ -96,7 +95,7 @@ export class PostMessageBusSource implements MessageBusSource {
}
from(channel: string): EventEmitter<any> {
if (StringMapWrapper.contains(this._channels, channel)) {
if (this._channels.hasOwnProperty(channel)) {
return this._channels[channel].emitter;
} else {
throw new Error(`${channel} is not set up. Did you forget to call initChannel?`);
@ -112,7 +111,7 @@ export class PostMessageBusSource implements MessageBusSource {
private _handleMessage(data: any): void {
var channel = data.channel;
if (StringMapWrapper.contains(this._channels, channel)) {
if (this._channels.hasOwnProperty(channel)) {
var channelInfo = this._channels[channel];
if (channelInfo.runInZone) {
this._zone.run(() => { channelInfo.emitter.emit(data.message); });

View File

@ -9,7 +9,6 @@
import {Injectable, Type} from '@angular/core';
import {EventEmitter} from '../../facade/async';
import {ListWrapper, Map} from '../../facade/collection';
import {FunctionWrapper, isPresent} from '../../facade/lang';
import {MessageBus} from '../shared/message_bus';
import {Serializer} from '../shared/serializer';
@ -72,7 +71,7 @@ export class ServiceMessageBroker_ extends ServiceMessageBroker {
this._methods.set(methodName, (message: ReceivedMessage) => {
var serializedArgs = message.args;
let numArgs = signature === null ? 0 : signature.length;
var deserializedArgs: any[] = ListWrapper.createFixedSize(numArgs);
var deserializedArgs: any[] = new Array(numArgs);
for (var i = 0; i < numArgs; i++) {
var serializedArg = serializedArgs[i];
deserializedArgs[i] = this._serializer.deserialize(serializedArg, signature[i]);

View File

@ -6,9 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Set} from '../../facade/collection';
import {isPresent} from '../../facade/lang';
const MOUSE_EVENT_PROPERTIES = [
'altKey', 'button', 'clientX', 'clientY', 'metaKey', 'movementX', 'movementY', 'offsetX',
'offsetY', 'region', 'screenX', 'screenY', 'shiftKey'
@ -56,7 +53,7 @@ function addTarget(e: Event, serializedEvent: {[key: string]: any}): {[key: stri
if (NODES_WITH_VALUE.has((<HTMLElement>e.target).tagName.toLowerCase())) {
var target = <HTMLInputElement>e.target;
serializedEvent['target'] = {'value': target.value};
if (isPresent(target.files)) {
if (target.files) {
serializedEvent['target']['files'] = target.files;
}
}

View File

@ -10,7 +10,6 @@ import {LocationChangeListener, PlatformLocation} from '@angular/common';
import {Injectable} from '@angular/core';
import {EventEmitter} from '../../facade/async';
import {StringMapWrapper} from '../../facade/collection';
import {StringWrapper} from '../../facade/lang';
import {ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments} from '../shared/client_message_broker';
import {MessageBus} from '../shared/message_bus';
@ -37,7 +36,7 @@ export class WebWorkerPlatformLocation extends PlatformLocation {
this._channelSource.subscribe({
next: (msg: {[key: string]: any}) => {
var listeners: Array<Function> = null;
if (StringMapWrapper.contains(msg, 'event')) {
if (msg.hasOwnProperty('event')) {
let type: string = msg['event']['type'];
if (StringWrapper.equals(type, 'popstate')) {
listeners = this._popStateListeners;

View File

@ -16,8 +16,6 @@ import {SpyMessageBroker} from '../worker/spies';
import {MockEventEmitter} from './mock_event_emitter';
var __unused: Promise<any>; // avoid unused import when Promise union types are erased
/**
* Returns two MessageBus instances that are attached to each other.
* Such that whatever goes into one's sink comes out the others source.
@ -49,9 +47,9 @@ export function expectBrokerCall(
expect(args.method).toEqual(methodName);
if (isPresent(vals)) {
expect(args.args.length).toEqual(vals.length);
ListWrapper.forEachWithIndex(vals, (v, i) => { expect(v).toEqual(args.args[i].value); });
vals.forEach((v, i) => { expect(v).toEqual(args.args[i].value); });
}
var promise: any /** TODO #9100 */ = null;
var promise: Promise<any>|void = null;
if (isPresent(handler)) {
let givenValues = args.args.map((arg) => arg.value);
if (givenValues.length > 0) {
@ -81,13 +79,13 @@ export class MockMessageBusSource implements MessageBusSource {
constructor(private _channels: {[key: string]: MockEventEmitter<any>}) {}
initChannel(channel: string, runInZone = true) {
if (!StringMapWrapper.contains(this._channels, channel)) {
if (!this._channels.hasOwnProperty(channel)) {
this._channels[channel] = new MockEventEmitter();
}
}
from(channel: string): MockEventEmitter<any> {
if (!StringMapWrapper.contains(this._channels, channel)) {
if (!this._channels.hasOwnProperty(channel)) {
throw new Error(`${channel} is not set up. Did you forget to call initChannel?`);
}
return this._channels[channel];
@ -100,13 +98,13 @@ export class MockMessageBusSink implements MessageBusSink {
constructor(private _channels: {[key: string]: MockEventEmitter<any>}) {}
initChannel(channel: string, runInZone = true) {
if (!StringMapWrapper.contains(this._channels, channel)) {
if (!this._channels.hasOwnProperty(channel)) {
this._channels[channel] = new MockEventEmitter();
}
}
to(channel: string): MockEventEmitter<any> {
if (!StringMapWrapper.contains(this._channels, channel)) {
if (!this._channels.hasOwnProperty(channel)) {
this._channels[channel] = new MockEventEmitter();
}
return this._channels[channel];

View File

@ -880,7 +880,7 @@ export declare abstract class TemplateRef<C> {
export declare class Testability implements PublicTestability {
constructor(_ngZone: NgZone);
decreasePendingRequestCount(): number;
findBindings(using: any, provider: string, exactMatch: boolean): any[];
/** @deprecated */ findBindings(using: any, provider: string, exactMatch: boolean): any[];
findProviders(using: any, provider: string, exactMatch: boolean): any[];
getPendingRequestCount(): number;
increasePendingRequestCount(): number;