refactor: remove lang.ts (#14837)

This commit is contained in:
Miško Hevery 2017-03-02 09:37:01 -08:00 committed by Chuck Jazdzewski
parent 84a65cf788
commit 8343fb7740
139 changed files with 406 additions and 676 deletions

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -7,7 +7,6 @@
*/
import {Inject, Injectable, InjectionToken} from '@angular/core';
import {print} from '../facade/lang';
import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description';
@ -23,8 +22,13 @@ export class ConsoleReporter extends Reporter {
static PRINT = new InjectionToken('ConsoleReporter.print');
static COLUMN_WIDTH = new InjectionToken('ConsoleReporter.columnWidth');
static PROVIDERS = [
ConsoleReporter, {provide: ConsoleReporter.COLUMN_WIDTH, useValue: 18},
{provide: ConsoleReporter.PRINT, useValue: print}
ConsoleReporter, {provide: ConsoleReporter.COLUMN_WIDTH, useValue: 18}, {
provide: ConsoleReporter.PRINT,
useValue: function(v: any) {
// tslint:disable-next-line:no-console
console.log(v);
}
}
];
private static _lpad(value: string, columnWidth: number, fill = ' ') {

View File

@ -9,7 +9,6 @@
import {Provider, ReflectiveInjector} from '@angular/core';
import {Options} from './common_options';
import {isPresent} from './facade/lang';
import {Metric} from './metric';
import {MultiMetric} from './metric/multi_metric';
import {PerflogMetric} from './metric/perflog_metric';
@ -49,16 +48,16 @@ export class Runner {
_DEFAULT_PROVIDERS, this._defaultProviders, {provide: Options.SAMPLE_ID, useValue: id},
{provide: Options.EXECUTE, useValue: execute}
];
if (isPresent(prepare)) {
if (prepare != null) {
sampleProviders.push({provide: Options.PREPARE, useValue: prepare});
}
if (isPresent(microMetrics)) {
if (microMetrics != null) {
sampleProviders.push({provide: Options.MICRO_METRICS, useValue: microMetrics});
}
if (isPresent(userMetrics)) {
if (userMetrics != null) {
sampleProviders.push({provide: Options.USER_METRICS, useValue: userMetrics});
}
if (isPresent(providers)) {
if (providers != null) {
sampleProviders.push(providers);
}

View File

@ -9,7 +9,6 @@
import {Inject, Injectable} from '@angular/core';
import {Options} from './common_options';
import {isPresent} from './facade/lang';
import {MeasureValues} from './measure_values';
import {Metric} from './metric';
import {Reporter} from './reporter';
@ -38,7 +37,7 @@ export class Sampler {
sample(): Promise<SampleState> {
const loop = (lastState: SampleState): Promise<SampleState> => {
return this._iterate(lastState).then((newState) => {
if (isPresent(newState.validSample)) {
if (newState.validSample != null) {
return newState;
} else {
return loop(newState);
@ -68,7 +67,7 @@ export class Sampler {
const completeSample = state.completeSample.concat([measureValues]);
const validSample = this._validator.validate(completeSample);
let resultPromise = this._reporter.reportMeasureValues(measureValues);
if (isPresent(validSample)) {
if (validSample != null) {
resultPromise =
resultPromise.then((_) => this._reporter.reportSample(completeSample, validSample));
}

View File

@ -8,7 +8,6 @@
import {Injectable} from '@angular/core';
import {isPresent} from '../facade/lang';
import {WebDriverAdapter} from '../web_driver_adapter';
import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';
@ -35,7 +34,7 @@ export class FirefoxDriverExtension extends WebDriverExtension {
timeEnd(name: string, restartName: string = null): Promise<any> {
let script = 'window.markEnd("' + name + '");';
if (isPresent(restartName)) {
if (restartName != null) {
script += 'window.markStart("' + restartName + '");';
}
return this._driver.executeScript(script);

View File

@ -8,7 +8,6 @@
import {Injectable} from '@angular/core';
import {isBlank, isPresent} from '../facade/lang';
import {WebDriverAdapter} from '../web_driver_adapter';
import {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from '../web_driver_extension';
@ -26,7 +25,7 @@ export class IOsDriverExtension extends WebDriverExtension {
timeEnd(name: string, restartName: string = null): Promise<any> {
let script = `console.timeEnd('${name}');`;
if (isPresent(restartName)) {
if (restartName != null) {
script += `console.time('${restartName}');`;
}
return this._driver.executeScript(script);
@ -76,10 +75,10 @@ export class IOsDriverExtension extends WebDriverExtension {
endEvent = createEndEvent('render', endTime);
}
// Note: ios used to support GCEvent up until iOS 6 :-(
if (isPresent(record['children'])) {
if (record['children'] != null) {
this._convertPerfRecordsToEvents(record['children'], events);
}
if (isPresent(endEvent)) {
if (endEvent != null) {
events.push(endEvent);
}
});
@ -104,7 +103,7 @@ function createEvent(
// the perflog...
'pid': 'pid0'
};
if (isPresent(args)) {
if (args != null) {
result['args'] = args;
}
return result;

View File

@ -10,7 +10,6 @@ import {Provider} from '@angular/core';
import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Metric, Options, PerfLogEvent, PerfLogFeatures, PerflogMetric, ReflectiveInjector, WebDriverExtension} from '../../index';
import {isPresent} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory';
export function main() {
@ -48,16 +47,16 @@ export function main() {
useValue: new MockDriverExtension(perfLogs, commandLog, perfLogFeatures)
}
];
if (isPresent(forceGc)) {
if (forceGc != null) {
providers.push({provide: Options.FORCE_GC, useValue: forceGc});
}
if (isPresent(captureFrames)) {
if (captureFrames != null) {
providers.push({provide: Options.CAPTURE_FRAMES, useValue: captureFrames});
}
if (isPresent(receivedData)) {
if (receivedData != null) {
providers.push({provide: Options.RECEIVED_DATA, useValue: receivedData});
}
if (isPresent(requestCount)) {
if (requestCount != null) {
providers.push({provide: Options.REQUEST_COUNT, useValue: requestCount});
}
return ReflectiveInjector.resolveAndCreate(providers).get(PerflogMetric);

View File

@ -10,7 +10,6 @@ import {Provider} from '@angular/core';
import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {ConsoleReporter, MeasureValues, ReflectiveInjector, SampleDescription} from '../../index';
import {isBlank, isPresent} from '../../src/facade/lang';
export function main() {
describe('console reporter', () => {
@ -38,7 +37,7 @@ export function main() {
},
{provide: ConsoleReporter.PRINT, useValue: (line: string) => log.push(line)}
];
if (isPresent(columnWidth)) {
if (columnWidth != null) {
providers.push({provide: ConsoleReporter.COLUMN_WIDTH, useValue: columnWidth});
}
reporter = ReflectiveInjector.resolveAndCreate(providers).get(ConsoleReporter);

View File

@ -9,7 +9,6 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {JsonFileReporter, MeasureValues, Options, ReflectiveInjector, SampleDescription} from '../../index';
import {isPresent} from '../../src/facade/lang';
export function main() {
describe('file reporter', () => {
@ -50,7 +49,7 @@ export function main() {
[mv(0, 0, {'a': 3, 'b': 6})],
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
const regExp = /somePath\/someId_\d+\.json/;
expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true);
expect(loggedFile['filename'].match(regExp) != null).toBe(true);
const parsedContent = JSON.parse(loggedFile['content']);
expect(parsedContent).toEqual({
'description': {

View File

@ -9,7 +9,6 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {MeasureValues, Metric, Options, ReflectiveInjector, Reporter, Sampler, Validator, WebDriverAdapter} from '../index';
import {isBlank, isPresent} from '../src/facade/lang';
export function main() {
const EMPTY_EXECUTE = () => {};
@ -32,7 +31,7 @@ export function main() {
if (!reporter) {
reporter = new MockReporter([]);
}
if (isBlank(driver)) {
if (driver == null) {
driver = new MockDriverAdapter([]);
}
const providers = [
@ -41,7 +40,7 @@ export function main() {
{provide: Options.EXECUTE, useValue: execute}, {provide: Validator, useValue: validator},
{provide: Options.NOW, useValue: () => new Date(time++)}
];
if (isPresent(prepare)) {
if (prepare != null) {
providers.push({provide: Options.PREPARE, useValue: prepare});
}
@ -227,7 +226,7 @@ function createCountingMetric(log: any[] = []) {
class MockDriverAdapter extends WebDriverAdapter {
constructor(private _log: any[] = [], private _waitFor: Function = null) { super(); }
waitFor(callback: Function): Promise<any> {
if (isPresent(this._waitFor)) {
if (this._waitFor != null) {
return this._waitFor(callback);
} else {
return Promise.resolve(callback());
@ -239,8 +238,7 @@ class MockDriverAdapter extends WebDriverAdapter {
class MockValidator extends Validator {
constructor(private _log: any[] = [], private _validate: Function = null) { super(); }
validate(completeSample: MeasureValues[]): MeasureValues[] {
const stableSample =
isPresent(this._validate) ? this._validate(completeSample) : completeSample;
const stableSample = this._validate != null ? this._validate(completeSample) : completeSample;
this._log.push(['validate', completeSample, stableSample]);
return stableSample;
}
@ -253,7 +251,7 @@ class MockMetric extends Metric {
return Promise.resolve(null);
}
endMeasure(restart: boolean) {
const measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {};
const measureValues = this._endMeasure != null ? this._endMeasure() : {};
this._log.push(['endMeasure', restart, measureValues]);
return Promise.resolve(measureValues);
}

View File

@ -7,7 +7,6 @@
*/
import {PerfLogEvent} from '../index';
import {isPresent} from '../src/facade/lang';
export class TraceEventFactory {
constructor(private _cat: string, private _pid: string) {}
@ -15,7 +14,7 @@ export class TraceEventFactory {
create(ph: any, name: string, time: number, args: any = null) {
const res:
PerfLogEvent = {'name': name, 'cat': this._cat, 'ph': ph, 'ts': time, 'pid': this._pid};
if (isPresent(args)) {
if (args != null) {
res['args'] = args;
}
return res;

View File

@ -9,7 +9,6 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Options, ReflectiveInjector, WebDriverExtension} from '../index';
import {isPresent} from '../src/facade/lang';
export function main() {
function createExtension(ids: any[], caps: any) {
@ -41,7 +40,7 @@ export function main() {
it('should throw if there is no match',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
createExtension(['m1'], {'browser': 'm2'}).catch((err) => {
expect(isPresent(err)).toBe(true);
expect(err != null).toBe(true);
async.done();
});
}));

View File

@ -9,7 +9,6 @@
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {ChromeDriverExtension, Options, ReflectiveInjector, WebDriverAdapter, WebDriverExtension} from '../../index';
import {isBlank} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory';
export function main() {
@ -38,7 +37,7 @@ export function main() {
if (!perfRecords) {
perfRecords = [];
}
if (isBlank(userAgent)) {
if (userAgent == null) {
userAgent = CHROME45_USER_AGENT;
}
log = [];

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, DoCheck, ElementRef, Input, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer, ɵisListLikeIterable as isListLikeIterable} from '@angular/core';
import {stringify} from '../facade/lang';
import {Directive, DoCheck, ElementRef, Input, IterableChanges, IterableDiffer, IterableDiffers, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer, ɵisListLikeIterable as isListLikeIterable, ɵstringify as stringify} from '@angular/core';
/**
* @ngModule CommonModule

View File

@ -8,8 +8,6 @@
import {ChangeDetectorRef, Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, OnChanges, SimpleChanges, TemplateRef, TrackByFunction, ViewContainerRef, forwardRef, isDevMode} from '@angular/core';
import {getTypeNameForDebugging} from '../facade/lang';
export class NgForOfRow<T> {
constructor(public $implicit: T, public index: number, public count: number) {}
@ -195,3 +193,7 @@ export type NgFor = NgForOf<any>;
* @deprecated from v4.0.0 - Use NgForOf instead.
*/
export const NgFor = NgForOf;
export function getTypeNameForDebugging(type: any): string {
return type['name'] || typeof type;
}

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -8,7 +8,6 @@
import {Inject, Injectable, Optional} from '@angular/core';
import {isPresent} from '../facade/lang';
import {Location} from './location';
import {APP_BASE_HREF, LocationStrategy} from './location_strategy';
@ -40,7 +39,7 @@ export class HashLocationStrategy extends LocationStrategy {
private _platformLocation: PlatformLocation,
@Optional() @Inject(APP_BASE_HREF) _baseHref?: string) {
super();
if (isPresent(_baseHref)) {
if (_baseHref != null) {
this._baseHref = _baseHref;
}
}
@ -56,7 +55,7 @@ export class HashLocationStrategy extends LocationStrategy {
// the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty
let path = this._platformLocation.hash;
if (!isPresent(path)) path = '#';
if (path == null) path = '#';
return path.length > 0 ? path.substring(1) : path;
}

View File

@ -8,7 +8,6 @@
import {Inject, Injectable, Optional} from '@angular/core';
import {isBlank} from '../facade/lang';
import {Location} from './location';
import {APP_BASE_HREF, LocationStrategy} from './location_strategy';
@ -51,11 +50,11 @@ export class PathLocationStrategy extends LocationStrategy {
@Optional() @Inject(APP_BASE_HREF) href?: string) {
super();
if (isBlank(href)) {
if (href == null) {
href = this._platformLocation.getBaseHrefFromDOM();
}
if (isBlank(href)) {
if (href == null) {
throw new Error(
`No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.`);
}

View File

@ -7,9 +7,9 @@
*/
import {Inject, LOCALE_ID, Pipe, PipeTransform} from '@angular/core';
import {NumberWrapper} from '../facade/lang';
import {DateFormatter} from './intl';
import {invalidPipeArgumentError} from './invalid_pipe_argument_error';
import {isNumeric} from './number_pipe';
const ISO8601_DATE_REGEX =
/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
@ -111,7 +111,7 @@ export class DatePipe implements PipeTransform {
if (isDate(value)) {
date = value;
} else if (NumberWrapper.isNumeric(value)) {
} else if (isNumeric(value)) {
date = new Date(parseFloat(value));
} else if (typeof value === 'string' && /^(\d{4}-\d{1,2}-\d{1,2})$/.test(value)) {
/**

View File

@ -6,9 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Type} from '@angular/core';
import {stringify} from '../facade/lang';
import {Type, ɵstringify as stringify} from '@angular/core';
export function invalidPipeArgumentError(type: Type<any>, value: Object) {
return Error(`InvalidPipeArgument: '${value}' for pipe '${stringify(type)}'`);

View File

@ -7,9 +7,6 @@
*/
import {Inject, LOCALE_ID, Pipe, PipeTransform, Type} from '@angular/core';
import {NumberWrapper} from '../facade/lang';
import {NumberFormatStyle, NumberFormatter} from './intl';
import {invalidPipeArgumentError} from './invalid_pipe_argument_error';
@ -21,7 +18,7 @@ function formatNumber(
if (value == null) return null;
// Convert strings to numbers
value = typeof value === 'string' && NumberWrapper.isNumeric(value) ? +value : value;
value = typeof value === 'string' && isNumeric(value) ? +value : value;
if (typeof value !== 'number') {
throw invalidPipeArgumentError(pipe, value);
}
@ -42,13 +39,13 @@ function formatNumber(
throw new Error(`${digits} is not a valid digit info for number pipes`);
}
if (parts[1] != null) { // min integer digits
minInt = NumberWrapper.parseIntAutoRadix(parts[1]);
minInt = parseIntAutoRadix(parts[1]);
}
if (parts[3] != null) { // min fraction digits
minFraction = NumberWrapper.parseIntAutoRadix(parts[3]);
minFraction = parseIntAutoRadix(parts[3]);
}
if (parts[5] != null) { // max fraction digits
maxFraction = NumberWrapper.parseIntAutoRadix(parts[5]);
maxFraction = parseIntAutoRadix(parts[5]);
}
}
@ -162,3 +159,15 @@ export class CurrencyPipe implements PipeTransform {
symbolDisplay);
}
}
function parseIntAutoRadix(text: string): number {
const result: number = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}

View File

@ -7,6 +7,7 @@
*/
import {CurrencyPipe, DecimalPipe, PercentPipe} from '@angular/common';
import {isNumeric} from '@angular/common/src/pipes/number_pipe';
import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
@ -80,6 +81,26 @@ export function main() {
() => { expect(() => pipe.transform(new Object())).toThrowError(); });
});
});
describe('isNumeric', () => {
it('should return true when passing correct numeric string',
() => { expect(isNumeric('2')).toBe(true); });
it('should return true when passing correct double string',
() => { expect(isNumeric('1.123')).toBe(true); });
it('should return true when passing correct negative string',
() => { expect(isNumeric('-2')).toBe(true); });
it('should return true when passing correct scientific notation string',
() => { expect(isNumeric('1e5')).toBe(true); });
it('should return false when passing incorrect numeric',
() => { expect(isNumeric('a')).toBe(false); });
it('should return false when passing parseable but non numeric',
() => { expect(isNumeric('2a')).toBe(false); });
});
});
}

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -8,10 +8,9 @@
import {isDevMode} from '@angular/core';
import {isBlank, isPresent} from '../src/facade/lang';
export function assertArrayOfStrings(identifier: string, value: any) {
if (!isDevMode() || isBlank(value)) {
if (!isDevMode() || value == null) {
return;
}
if (!Array.isArray(value)) {
@ -33,9 +32,9 @@ const INTERPOLATION_BLACKLIST_REGEXPS = [
];
export function assertInterpolationSymbols(identifier: string, value: any): void {
if (isPresent(value) && !(Array.isArray(value) && value.length == 2)) {
if (value != null && !(Array.isArray(value) && value.length == 2)) {
throw new Error(`Expected '${identifier}' to be an array, [start, end].`);
} else if (isDevMode() && !isBlank(value)) {
} else if (isDevMode() && value != null) {
const start = value[0] as string;
const end = value[1] as string;
// black list checking

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ChangeDetectionStrategy, ComponentFactory, RendererTypeV2, SchemaMetadata, Type, ViewEncapsulation, ɵLifecycleHooks, ɵreflector} from '@angular/core';
import {ChangeDetectionStrategy, ComponentFactory, RendererTypeV2, SchemaMetadata, Type, ViewEncapsulation, ɵLifecycleHooks, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {StaticSymbol} from './aot/static_symbol';
import {isPresent, stringify} from './facade/lang';
import {CssSelector} from './selector';
import {splitAtColon} from './util';
@ -179,12 +178,11 @@ export interface CompileFactoryMetadata extends CompileIdentifierMetadata {
}
export function tokenName(token: CompileTokenMetadata) {
return isPresent(token.value) ? _sanitizeIdentifier(token.value) :
identifierName(token.identifier);
return token.value != null ? _sanitizeIdentifier(token.value) : identifierName(token.identifier);
}
export function tokenReference(token: CompileTokenMetadata) {
if (isPresent(token.identifier)) {
if (token.identifier != null) {
return token.identifier.reference;
} else {
return token.value;
@ -346,21 +344,21 @@ export class CompileDirectiveMetadata {
const hostListeners: {[key: string]: string} = {};
const hostProperties: {[key: string]: string} = {};
const hostAttributes: {[key: string]: string} = {};
if (isPresent(host)) {
if (host != null) {
Object.keys(host).forEach(key => {
const value = host[key];
const matches = key.match(HOST_REG_EXP);
if (matches === null) {
hostAttributes[key] = value;
} else if (isPresent(matches[1])) {
} else if (matches[1] != null) {
hostProperties[matches[1]] = value;
} else if (isPresent(matches[2])) {
} else if (matches[2] != null) {
hostListeners[matches[2]] = value;
}
});
}
const inputsMap: {[key: string]: string} = {};
if (isPresent(inputs)) {
if (inputs != null) {
inputs.forEach((bindConfig: string) => {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp
@ -369,7 +367,7 @@ export class CompileDirectiveMetadata {
});
}
const outputsMap: {[key: string]: string} = {};
if (isPresent(outputs)) {
if (outputs != null) {
outputs.forEach((bindConfig: string) => {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp

View File

@ -8,7 +8,6 @@
import * as cdAst from '../expression_parser/ast';
import {isBlank} from '../facade/lang';
import {Identifiers, createIdentifier} from '../identifiers';
import * as o from '../output/output_ast';
@ -338,7 +337,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
result = varExpr.callFn(args);
}
}
if (isBlank(result)) {
if (result == null) {
result = receiver.callMethod(ast.name, args);
}
return convertToStatementIfNeeded(mode, result);
@ -359,7 +358,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
if (receiver === this._implicitReceiver) {
result = this._getLocal(ast.name);
}
if (isBlank(result)) {
if (result == null) {
result = receiver.prop(ast.name);
}
return convertToStatementIfNeeded(mode, result);
@ -607,4 +606,4 @@ class BuiltinFunctionCall extends cdAst.FunctionCall {
constructor(span: cdAst.ParseSpan, public args: cdAst.AST[], public converter: BuiltinConverter) {
super(span, null, args);
}
}
}

View File

@ -8,7 +8,6 @@
import * as chars from '../chars';
import {isPresent} from '../facade/lang';
export enum CssTokenType {
EOF,
@ -200,9 +199,9 @@ export class CssScanner {
let next: CssToken;
const output = this.scan();
if (isPresent(output)) {
if (output != null) {
// just incase the inner scan method returned an error
if (isPresent(output.error)) {
if (output.error != null) {
this.setMode(mode);
return output;
}
@ -210,7 +209,7 @@ export class CssScanner {
next = output.token;
}
if (!isPresent(next)) {
if (next == null) {
next = new CssToken(this.index, this.column, this.line, CssTokenType.EOF, 'end of file');
}
@ -227,11 +226,11 @@ export class CssScanner {
this.setMode(mode);
let error: Error = null;
if (!isMatchingType || (isPresent(value) && value != next.strValue)) {
if (!isMatchingType || (value != null && value != next.strValue)) {
let errorMessage =
CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value';
if (isPresent(value)) {
if (value != null) {
errorMessage += ' ("' + next.strValue + '" should match "' + value + '")';
}

View File

@ -7,7 +7,6 @@
*/
import * as chars from '../chars';
import {isPresent} from '../facade/lang';
import {ParseError, ParseLocation, ParseSourceFile, ParseSourceSpan} from '../parse_util';
import {BlockType, CssAst, CssAtRulePredicateAst, CssBlockAst, CssBlockDefinitionRuleAst, CssBlockRuleAst, CssDefinitionAst, CssInlineRuleAst, CssKeyframeDefinitionAst, CssKeyframeRuleAst, CssMediaQueryRuleAst, CssPseudoSelectorAst, CssRuleAst, CssSelectorAst, CssSelectorRuleAst, CssSimpleSelectorAst, CssStyleSheetAst, CssStyleValueAst, CssStylesBlockAst, CssUnknownRuleAst, CssUnknownTokenListAst, mergeTokens} from './css_ast';
@ -127,7 +126,7 @@ export class CssParser {
}
/** @internal */
_getSourceContent(): string { return isPresent(this._scanner) ? this._scanner.input : ''; }
_getSourceContent(): string { return this._scanner != null ? this._scanner.input : ''; }
/** @internal */
_extractSourceContent(start: number, end: number): string {
@ -141,7 +140,7 @@ export class CssParser {
startLoc = start.location.start;
} else {
let token = start;
if (!isPresent(token)) {
if (token == null) {
// the data here is invalid, however, if and when this does
// occur, any other errors associated with this will be collected
token = this._lastToken;
@ -149,7 +148,7 @@ export class CssParser {
startLoc = new ParseLocation(this._file, token.index, token.line, token.column);
}
if (!isPresent(end)) {
if (end == null) {
end = this._lastToken;
}
@ -329,7 +328,7 @@ export class CssParser {
let ruleAst: CssRuleAst;
let span: ParseSourceSpan;
const startSelector = selectors[0];
if (isPresent(block)) {
if (block != null) {
span = this._generateSourceSpan(startSelector, block);
ruleAst = new CssSelectorRuleAst(span, selectors, block);
} else {
@ -377,7 +376,7 @@ export class CssParser {
const output = this._scanner.scan();
const token = output.token;
const error = output.error;
if (isPresent(error)) {
if (error != null) {
this._error(getRawMessage(error), token);
}
this._lastToken = token;
@ -392,7 +391,7 @@ export class CssParser {
const output = this._scanner.consume(type, value);
const token = output.token;
const error = output.error;
if (isPresent(error)) {
if (error != null) {
this._error(getRawMessage(error), token);
}
this._lastToken = token;
@ -601,7 +600,7 @@ export class CssParser {
let index = lastOperatorToken.index;
let line = lastOperatorToken.line;
let column = lastOperatorToken.column;
if (isPresent(deepToken) && deepToken.strValue.toLowerCase() == 'deep' &&
if (deepToken != null && deepToken.strValue.toLowerCase() == 'deep' &&
deepSlash.strValue == SLASH_CHARACTER) {
token = new CssToken(
lastOperatorToken.index, lastOperatorToken.column, lastOperatorToken.line,
@ -636,7 +635,7 @@ export class CssParser {
// so long as there is an operator then we can have an
// ending value that is beyond the selector value ...
// otherwise it's just a bunch of trailing whitespace
if (isPresent(operator)) {
if (operator != null) {
end = operator.index;
}
}
@ -664,7 +663,7 @@ export class CssParser {
startTokenOrAst = startTokenOrAst || pseudoSelectors[0];
endTokenOrAst = pseudoSelectors[pseudoSelectors.length - 1];
}
if (isPresent(operator)) {
if (operator != null) {
startTokenOrAst = startTokenOrAst || operator;
endTokenOrAst = operator;
}
@ -702,7 +701,7 @@ export class CssParser {
let previous: CssToken;
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
let token: CssToken;
if (isPresent(previous) && previous.type == CssTokenType.Identifier &&
if (previous != null && previous.type == CssTokenType.Identifier &&
this._scanner.peek == chars.$LPAREN) {
token = this._consume(CssTokenType.Character, '(');
tokens.push(token);
@ -753,7 +752,7 @@ export class CssParser {
_collectUntilDelim(delimiters: number, assertType: CssTokenType = null): CssToken[] {
const tokens: CssToken[] = [];
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
const val = isPresent(assertType) ? this._consume(assertType) : this._scan();
const val = assertType != null ? this._consume(assertType) : this._scan();
tokens.push(val);
}
return tokens;

View File

@ -6,11 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ViewEncapsulation} from '@angular/core';
import {ViewEncapsulation, ɵstringify as stringify} from '@angular/core';
import {CompileAnimationEntryMetadata, CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata} from './compile_metadata';
import {CompilerConfig} from './config';
import {stringify} from './facade/lang';
import {CompilerInjectable} from './injectable';
import * as html from './ml_parser/ast';
import {HtmlParser} from './ml_parser/html_parser';

View File

@ -6,9 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Directive, HostBinding, HostListener, Input, Output, Query, Type, resolveForwardRef, ɵReflectorReader, ɵmerge as merge, ɵreflector} from '@angular/core';
import {stringify} from './facade/lang';
import {Component, Directive, HostBinding, HostListener, Input, Output, Query, Type, resolveForwardRef, ɵReflectorReader, ɵmerge as merge, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {CompilerInjectable} from './injectable';
import {splitAtColon} from './util';

View File

@ -7,7 +7,6 @@
*/
import {isBlank} from '../facade/lang';
export class ParserError {
public message: string;
@ -196,7 +195,7 @@ export class ASTWithSource extends AST {
constructor(
public ast: AST, public source: string, public location: string,
public errors: ParserError[]) {
super(new ParseSpan(0, isBlank(source) ? 0 : source.length));
super(new ParseSpan(0, source == null ? 0 : source.length));
}
visit(visitor: AstVisitor, context: any = null): any { return this.ast.visit(visitor, context); }
toString(): string { return `${this.source} in ${this.location}`; }

View File

@ -7,7 +7,6 @@
*/
import * as chars from '../chars';
import {NumberWrapper} from '../facade/lang';
import {CompilerInjectable} from '../injectable';
export enum TokenType {
@ -276,7 +275,7 @@ class _Scanner {
this.advance();
}
const str: string = this.input.substring(start, this.index);
const value: number = simple ? NumberWrapper.parseIntAutoRadix(str) : parseFloat(str);
const value: number = simple ? parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, value);
}
@ -383,3 +382,11 @@ function unescape(code: number): number {
return code;
}
}
function parseIntAutoRadix(text: string): number {
const result: number = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}

View File

@ -7,10 +7,9 @@
*/
import * as chars from '../chars';
import {escapeRegExp, isBlank, isPresent} from '../facade/lang';
import {CompilerInjectable} from '../injectable';
import {DEFAULT_INTERPOLATION_CONFIG, InterpolationConfig} from '../ml_parser/interpolation_config';
import {escapeRegExp} from '../util';
import {AST, ASTWithSource, AstVisitor, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, ParseSpan, ParserError, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead, TemplateBinding} from './ast';
import {EOF, Lexer, Token, TokenType, isIdentifier, isQuote} from './lexer';
@ -78,7 +77,7 @@ export class Parser {
// our lexer or parser for that, so we check for that ahead of time.
const quote = this._parseQuote(input, location);
if (isPresent(quote)) {
if (quote != null) {
return quote;
}
@ -92,7 +91,7 @@ export class Parser {
}
private _parseQuote(input: string, location: any): AST {
if (isBlank(input)) return null;
if (input == null) return null;
const prefixSeparatorIndex = input.indexOf(':');
if (prefixSeparatorIndex == -1) return null;
const prefix = input.substring(0, prefixSeparatorIndex).trim();
@ -137,7 +136,7 @@ export class Parser {
return new ASTWithSource(
new Interpolation(
new ParseSpan(0, isBlank(input) ? 0 : input.length), split.strings, expressions),
new ParseSpan(0, input == null ? 0 : input.length), split.strings, expressions),
input, location, this.errors);
}
@ -178,13 +177,13 @@ export class Parser {
wrapLiteralPrimitive(input: string, location: any): ASTWithSource {
return new ASTWithSource(
new LiteralPrimitive(new ParseSpan(0, isBlank(input) ? 0 : input.length), input), input,
new LiteralPrimitive(new ParseSpan(0, input == null ? 0 : input.length), input), input,
location, this.errors);
}
private _stripComments(input: string): string {
const i = this._commentStart(input);
return isPresent(i) ? input.substring(0, i).trim() : input;
return i != null ? input.substring(0, i).trim() : input;
}
private _commentStart(input: string): number {
@ -193,11 +192,11 @@ export class Parser {
const char = input.charCodeAt(i);
const nextChar = input.charCodeAt(i + 1);
if (char === chars.$SLASH && nextChar == chars.$SLASH && isBlank(outerQuote)) return i;
if (char === chars.$SLASH && nextChar == chars.$SLASH && outerQuote == null) return i;
if (outerQuote === char) {
outerQuote = null;
} else if (isBlank(outerQuote) && isQuote(char)) {
} else if (outerQuote == null && isQuote(char)) {
outerQuote = char;
}
}
@ -728,7 +727,7 @@ export class _ParseAST {
}
private locationText(index: number = null) {
if (isBlank(index)) index = this.index;
if (index == null) index = this.index;
return (index < this.tokens.length) ? `at column ${this.tokens[index].index + 1} in` :
`at the end of the expression`;
}

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -6,11 +6,10 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Compiler, ComponentFactory, Inject, Injector, ModuleWithComponentFactories, NgModuleFactory, Type, ɵgetComponentViewDefinitionFactory as getComponentViewDefinitionFactory} from '@angular/core';
import {Compiler, ComponentFactory, Inject, Injector, ModuleWithComponentFactories, NgModuleFactory, Type, ɵgetComponentViewDefinitionFactory as getComponentViewDefinitionFactory, ɵstringify as stringify} from '@angular/core';
import {CompileDirectiveMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, ProviderMeta, ProxyClass, createHostComponentMeta, identifierName} from '../compile_metadata';
import {CompilerConfig} from '../config';
import {stringify} from '../facade/lang';
import {CompilerInjectable} from '../injectable';
import {CompileMetadataResolver} from '../metadata_resolver';
import {NgModuleCompiler} from '../ng_module_compiler';

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, InjectionToken, ModuleWithProviders, Optional, Provider, Query, RendererTypeV2, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef, ɵERROR_COMPONENT_TYPE, ɵLIFECYCLE_HOOKS_VALUES, ɵReflectorReader, ɵccf as createComponentFactory, ɵreflector} from '@angular/core';
import {Attribute, ChangeDetectionStrategy, Component, ComponentFactory, Directive, Host, Inject, Injectable, InjectionToken, ModuleWithProviders, Optional, Provider, Query, RendererTypeV2, SchemaMetadata, Self, SkipSelf, Type, resolveForwardRef, ɵERROR_COMPONENT_TYPE, ɵLIFECYCLE_HOOKS_VALUES, ɵReflectorReader, ɵccf as createComponentFactory, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {StaticSymbol, StaticSymbolCache} from './aot/static_symbol';
import {ngfactoryFilePath} from './aot/util';
import {assertArrayOfStrings, assertInterpolationSymbols} from './assertions';
@ -15,7 +14,6 @@ import * as cpl from './compile_metadata';
import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer';
import {DirectiveResolver} from './directive_resolver';
import {stringify} from './facade/lang';
import {Identifiers, resolveIdentifier} from './identifiers';
import {CompilerInjectable} from './injectable';
import {hasLifecycleHook} from './lifecycle_reflector';

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isBlank, isPresent} from '../facade/lang';
import {ParseError, ParseSourceSpan} from '../parse_util';
import * as html from './ast';
@ -109,7 +108,7 @@ class _TreeBuilder {
private _consumeComment(token: lex.Token) {
const text = this._advanceIf(lex.TokenType.RAW_TEXT);
this._advanceIf(lex.TokenType.COMMENT_END);
const value = isPresent(text) ? text.parts[0].trim() : null;
const value = text != null ? text.parts[0].trim() : null;
this._addToParent(new html.Comment(value, token.sourceSpan));
}
@ -217,7 +216,7 @@ class _TreeBuilder {
let text = token.parts[0];
if (text.length > 0 && text[0] == '\n') {
const parent = this._getParentElement();
if (isPresent(parent) && parent.children.length == 0 &&
if (parent != null && parent.children.length == 0 &&
this.getTagDefinition(parent.name).ignoreFirstLf) {
text = text.substring(1);
}
@ -365,7 +364,7 @@ class _TreeBuilder {
private _addToParent(node: html.Node) {
const parent = this._getParentElement();
if (isPresent(parent)) {
if (parent != null) {
parent.children.push(node);
} else {
this._rootNodes.push(node);
@ -399,9 +398,9 @@ class _TreeBuilder {
private _getElementFullName(prefix: string, localName: string, parentElement: html.Element):
string {
if (isBlank(prefix)) {
if (prefix == null) {
prefix = this.getTagDefinition(localName).implicitNamespacePrefix;
if (isBlank(prefix) && isPresent(parentElement)) {
if (prefix == null && parentElement != null) {
prefix = getNsPrefix(parentElement.name);
}
}

View File

@ -9,7 +9,6 @@
import {ɵLifecycleHooks} from '@angular/core';
import {CompileDiDependencyMetadata, CompileIdentifierMetadata, CompileNgModuleMetadata, CompileProviderMetadata, CompileTokenMetadata, identifierModuleUrl, identifierName, tokenName, tokenReference} from './compile_metadata';
import {isPresent} from './facade/lang';
import {Identifiers, createIdentifier, resolveIdentifier} from './identifiers';
import {CompilerInjectable} from './injectable';
import {ClassBuilder, createClassStmt} from './output/class_builder';
@ -39,7 +38,7 @@ export class NgModuleCompiler {
compile(ngModuleMeta: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[]):
NgModuleCompileResult {
const moduleUrl = identifierModuleUrl(ngModuleMeta.type);
const sourceFileName = isPresent(moduleUrl) ?
const sourceFileName = moduleUrl != null ?
`in NgModule ${identifierName(ngModuleMeta.type)} in ${moduleUrl}` :
`in NgModule ${identifierName(ngModuleMeta.type)}`;
const sourceFile = new ParseSourceFile('', sourceFileName);
@ -161,13 +160,13 @@ class _InjectorBuilder implements ClassBuilder {
private _getProviderValue(provider: CompileProviderMetadata): o.Expression {
let result: o.Expression;
if (isPresent(provider.useExisting)) {
if (provider.useExisting != null) {
result = this._getDependency({token: provider.useExisting});
} else if (isPresent(provider.useFactory)) {
} else if (provider.useFactory != null) {
const deps = provider.deps || provider.useFactory.diDeps;
const depsExpr = deps.map((dep) => this._getDependency(dep));
result = o.importExpr(provider.useFactory).callFn(depsExpr);
} else if (isPresent(provider.useClass)) {
} else if (provider.useClass != null) {
const deps = provider.deps || provider.useClass.diDeps;
const depsExpr = deps.map((dep) => this._getDependency(dep));
result =
@ -239,7 +238,7 @@ class _InjectorBuilder implements ClassBuilder {
}
function createDiTokenExpression(token: CompileTokenMetadata): o.Expression {
if (isPresent(token.value)) {
if (token.value != null) {
return o.literal(token.value);
} else {
return o.importExpr(token.identifier);

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule, Type, ɵReflectorReader, ɵreflector} from '@angular/core';
import {NgModule, Type, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {findLast} from './directive_resolver';
import {stringify} from './facade/lang';
import {CompilerInjectable} from './injectable';
function _isNgModuleMetadata(obj: any): obj is NgModule {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isBlank, isPresent} from '../facade/lang';
import {ParseSourceSpan} from '../parse_util';
import * as o from './output_ast';
@ -164,7 +163,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
ctx.print(stmt, `if (`);
stmt.condition.visitExpression(this, ctx);
ctx.print(stmt, `) {`);
const hasElseCase = isPresent(stmt.falseCase) && stmt.falseCase.length > 0;
const hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
if (stmt.trueCase.length <= 1 && !hasElseCase) {
ctx.print(stmt, ` `);
this.visitAllStatements(stmt.trueCase, ctx);
@ -244,9 +243,9 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: EmitterVisitorContext): any {
expr.receiver.visitExpression(this, ctx);
let name = expr.name;
if (isPresent(expr.builtin)) {
if (expr.builtin != null) {
name = this.getBuiltinMethodName(expr.builtin);
if (isBlank(name)) {
if (name == null) {
// some builtins just mean to skip the call.
return null;
}
@ -268,7 +267,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
}
visitReadVarExpr(ast: o.ReadVarExpr, ctx: EmitterVisitorContext): any {
let varName = ast.name;
if (isPresent(ast.builtin)) {
if (ast.builtin != null) {
switch (ast.builtin) {
case o.BuiltinVar.Super:
varName = 'super';
@ -450,7 +449,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
export function escapeIdentifier(
input: string, escapeDollar: boolean, alwaysQuote: boolean = true): any {
if (isBlank(input)) {
if (input == null) {
return null;
}
const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => {

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isPresent} from '../facade/lang';
import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext} from './abstract_emitter';
import * as o from './output_ast';
@ -17,7 +16,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
ctx.pushClass(stmt);
this._visitClassConstructor(stmt, ctx);
if (isPresent(stmt.parent)) {
if (stmt.parent != null) {
ctx.print(stmt, `${stmt.name}.prototype = Object.create(`);
stmt.parent.visitExpression(this, ctx);
ctx.println(stmt, `.prototype);`);
@ -30,12 +29,12 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
private _visitClassConstructor(stmt: o.ClassStmt, ctx: EmitterVisitorContext) {
ctx.print(stmt, `function ${stmt.name}(`);
if (isPresent(stmt.constructorMethod)) {
if (stmt.constructorMethod != null) {
this._visitParams(stmt.constructorMethod.params, ctx);
}
ctx.println(stmt, `) {`);
ctx.incIndent();
if (isPresent(stmt.constructorMethod)) {
if (stmt.constructorMethod != null) {
if (stmt.constructorMethod.body.length > 0) {
ctx.println(stmt, `var self = this;`);
this.visitAllStatements(stmt.constructorMethod.body, ctx);

View File

@ -9,7 +9,6 @@
import {StaticSymbol} from '../aot/static_symbol';
import {CompileIdentifierMetadata} from '../compile_metadata';
import {isBlank} from '../facade/lang';
import {EmitterVisitorContext, OutputEmitter} from './abstract_emitter';
import {AbstractJsEmitterVisitor} from './abstract_js_emitter';
@ -61,7 +60,7 @@ class JsEmitterVisitor extends AbstractJsEmitterVisitor {
const {name, filePath} = this._resolveStaticSymbol(ast.value);
if (filePath != this._genFilePath) {
let prefix = this.importsWithPrefixes.get(filePath);
if (isBlank(prefix)) {
if (prefix == null) {
prefix = `import${this.importsWithPrefixes.size}`;
this.importsWithPrefixes.set(filePath, prefix);
}

View File

@ -8,7 +8,6 @@
import {CompileIdentifierMetadata} from '../compile_metadata';
import {isPresent} from '../facade/lang';
import {ParseSourceSpan} from '../parse_util';
//// Types
@ -954,12 +953,12 @@ export function importExpr(
export function importType(
id: CompileIdentifierMetadata, typeParams: Type[] = null,
typeModifiers: TypeModifier[] = null): ExpressionType {
return isPresent(id) ? expressionType(importExpr(id, typeParams), typeModifiers) : null;
return id != null ? expressionType(importExpr(id, typeParams), typeModifiers) : null;
}
export function expressionType(
expr: Expression, typeModifiers: TypeModifier[] = null): ExpressionType {
return isPresent(expr) ? new ExpressionType(expr, typeModifiers) : null;
return expr != null ? new ExpressionType(expr, typeModifiers) : null;
}
export function literalArr(

View File

@ -7,7 +7,6 @@
*/
import {isPresent} from '../facade/lang';
import * as o from './output_ast';
import {debugOutputAstAsTypeScript} from './ts_emitter';
@ -18,7 +17,7 @@ export function interpretStatements(statements: o.Statement[], resultVars: strin
const ctx = new _ExecutionContext(null, null, null, new Map<string, any>());
const visitor = new StatementInterpreter();
const result = visitor.visitAllStatements(stmtsWithReturn, ctx);
return isPresent(result) ? result.value : null;
return result != null ? result.value : null;
}
function _executeFunctionStatements(
@ -107,7 +106,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
}
visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any {
let varName = ast.name;
if (isPresent(ast.builtin)) {
if (ast.builtin != null) {
switch (ast.builtin) {
case o.BuiltinVar.Super:
return ctx.instance.__proto__;
@ -150,7 +149,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
const receiver = expr.receiver.visitExpression(this, ctx);
const args = this.visitAllExpressions(expr.args, ctx);
let result: any;
if (isPresent(expr.builtin)) {
if (expr.builtin != null) {
switch (expr.builtin) {
case o.BuiltinMethod.ConcatArray:
result = receiver.concat(...args);
@ -195,7 +194,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
const condition = stmt.condition.visitExpression(this, ctx);
if (condition) {
return this.visitAllStatements(stmt.trueCase, ctx);
} else if (isPresent(stmt.falseCase)) {
} else if (stmt.falseCase != null) {
return this.visitAllStatements(stmt.falseCase, ctx);
}
return null;
@ -226,7 +225,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
visitConditionalExpr(ast: o.ConditionalExpr, ctx: _ExecutionContext): any {
if (ast.condition.visitExpression(this, ctx)) {
return ast.trueCase.visitExpression(this, ctx);
} else if (isPresent(ast.falseCase)) {
} else if (ast.falseCase != null) {
return ast.falseCase.visitExpression(this, ctx);
}
return null;

View File

@ -9,7 +9,6 @@
import {StaticSymbol} from '../aot/static_symbol';
import {CompileIdentifierMetadata} from '../compile_metadata';
import {isBlank, isPresent} from '../facade/lang';
import {AbstractEmitterVisitor, CATCH_ERROR_VAR, CATCH_STACK_VAR, EmitterVisitorContext, OutputEmitter} from './abstract_emitter';
import * as o from './output_ast';
@ -91,7 +90,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
reexports = new Map<string, {name: string, as: string}[]>();
visitType(t: o.Type, ctx: EmitterVisitorContext, defaultType: string = 'any') {
if (isPresent(t)) {
if (t != null) {
this.typeExpression++;
t.visitType(this, ctx);
this.typeExpression--;
@ -102,7 +101,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
visitLiteralExpr(ast: o.LiteralExpr, ctx: EmitterVisitorContext): any {
const value = ast.value;
if (isBlank(value) && ast.type != o.INFERRED_TYPE) {
if (value == null && ast.type != o.INFERRED_TYPE) {
ctx.print(ast, `(${value} as any)`);
return null;
}
@ -186,7 +185,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
ctx.print(stmt, `export `);
}
ctx.print(stmt, `class ${stmt.name}`);
if (isPresent(stmt.parent)) {
if (stmt.parent != null) {
ctx.print(stmt, ` extends `);
this.typeExpression++;
stmt.parent.visitExpression(this, ctx);
@ -195,7 +194,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
ctx.println(stmt, ` {`);
ctx.incIndent();
stmt.fields.forEach((field) => this._visitClassField(field, ctx));
if (isPresent(stmt.constructorMethod)) {
if (stmt.constructorMethod != null) {
this._visitClassConstructor(stmt, ctx);
}
stmt.getters.forEach((getter) => this._visitClassGetter(getter, ctx));
@ -391,7 +390,7 @@ class _TsEmitterVisitor extends AbstractEmitterVisitor implements o.TypeVisitor
const {name, filePath, members, arity} = this._resolveStaticSymbol(value);
if (filePath != this._genFilePath) {
let prefix = this.importsWithPrefixes.get(filePath);
if (isBlank(prefix)) {
if (prefix == null) {
prefix = `import${this.importsWithPrefixes.size}`;
this.importsWithPrefixes.set(filePath, prefix);
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import * as chars from './chars';
import {isPresent} from './facade/lang';
export class ParseLocation {
constructor(
@ -14,7 +13,7 @@ export class ParseLocation {
public col: number) {}
toString(): string {
return isPresent(this.offset) ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
}
moveBy(delta: number): ParseLocation {
@ -55,7 +54,7 @@ export class ParseLocation {
const content = this.file.content;
let startOffset = this.offset;
if (isPresent(startOffset)) {
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {Pipe, Type, resolveForwardRef, ɵReflectorReader, ɵreflector} from '@angular/core';
import {Pipe, Type, resolveForwardRef, ɵReflectorReader, ɵreflector, ɵstringify as stringify} from '@angular/core';
import {findLast} from './directive_resolver';
import {stringify} from './facade/lang';
import {CompilerInjectable} from './injectable';
function _isPipeMetadata(type: any): boolean {

View File

@ -8,7 +8,6 @@
import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenName, tokenReference} from './compile_metadata';
import {isBlank, isPresent} from './facade/lang';
import {Identifiers, createIdentifierToken, resolveIdentifier} from './identifiers';
import {ParseError, ParseSourceSpan} from './parse_util';
import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, QueryMatch, ReferenceAst} from './template_parser/template_ast';
@ -37,7 +36,7 @@ export class ProviderViewContext {
this.viewQueries = _getViewQueries(component);
this.viewProviders = new Map<any, boolean>();
component.viewProviders.forEach((provider) => {
if (isBlank(this.viewProviders.get(tokenReference(provider.token)))) {
if (this.viewProviders.get(tokenReference(provider.token)) == null) {
this.viewProviders.set(tokenReference(provider.token), true);
}
});
@ -171,7 +170,7 @@ export class ProviderElementContext {
if (transformedProviderAst) {
return transformedProviderAst;
}
if (isPresent(this._seenProviders.get(tokenReference(token)))) {
if (this._seenProviders.get(tokenReference(token)) != null) {
this.viewContext.errors.push(new ProviderError(
`Cannot instantiate cyclic dependency! ${tokenName(token)}`, this._sourceSpan));
return null;
@ -181,10 +180,10 @@ export class ProviderElementContext {
let transformedUseValue = provider.useValue;
let transformedUseExisting = provider.useExisting;
let transformedDeps: CompileDiDependencyMetadata[];
if (isPresent(provider.useExisting)) {
if (provider.useExisting != null) {
const existingDiDep = this._getDependency(
resolvedProvider.providerType, {token: provider.useExisting}, eager);
if (isPresent(existingDiDep.token)) {
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
} else {
transformedUseExisting = null;
@ -219,7 +218,7 @@ export class ProviderElementContext {
return {isValue: true, value: attrValue == null ? null : attrValue};
}
if (isPresent(dep.token)) {
if (dep.token != null) {
// access builtints
if ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.Component)) {
@ -238,7 +237,7 @@ export class ProviderElementContext {
return dep;
}
// access providers
if (isPresent(this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager))) {
if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
return dep;
}
}
@ -272,7 +271,7 @@ export class ProviderElementContext {
if (!result) {
if (!dep.isHost || this.viewContext.component.isHost ||
this.viewContext.component.type.reference === tokenReference(dep.token) ||
isPresent(this.viewContext.viewProviders.get(tokenReference(dep.token)))) {
this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
result = dep;
} else {
result = dep.isOptional ? result = {isValue: true, value: null} : null;
@ -329,7 +328,7 @@ export class NgModuleProviderAnalyzer {
if (transformedProviderAst) {
return transformedProviderAst;
}
if (isPresent(this._seenProviders.get(tokenReference(token)))) {
if (this._seenProviders.get(tokenReference(token)) != null) {
this._errors.push(new ProviderError(
`Cannot instantiate cyclic dependency! ${tokenName(token)}`,
resolvedProvider.sourceSpan));
@ -340,10 +339,10 @@ export class NgModuleProviderAnalyzer {
let transformedUseValue = provider.useValue;
let transformedUseExisting = provider.useExisting;
let transformedDeps: CompileDiDependencyMetadata[];
if (isPresent(provider.useExisting)) {
if (provider.useExisting != null) {
const existingDiDep =
this._getDependency({token: provider.useExisting}, eager, resolvedProvider.sourceSpan);
if (isPresent(existingDiDep.token)) {
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
} else {
transformedUseExisting = null;
@ -374,13 +373,13 @@ export class NgModuleProviderAnalyzer {
dep: CompileDiDependencyMetadata, eager: boolean = null,
requestorSourceSpan: ParseSourceSpan): CompileDiDependencyMetadata {
let foundLocal = false;
if (!dep.isSkipSelf && isPresent(dep.token)) {
if (!dep.isSkipSelf && dep.token != null) {
// access the injector
if (tokenReference(dep.token) === resolveIdentifier(Identifiers.Injector) ||
tokenReference(dep.token) === resolveIdentifier(Identifiers.ComponentFactoryResolver)) {
foundLocal = true;
// access providers
} else if (isPresent(this._getOrCreateLocalProvider(dep.token, eager))) {
} else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
foundLocal = true;
}
}
@ -453,7 +452,7 @@ function _resolveProviders(
targetProvidersByToken: Map<any, ProviderAst>) {
providers.forEach((provider) => {
let resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
if (isPresent(resolvedProvider) && !!resolvedProvider.multiProvider !== !!provider.multi) {
if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
targetErrors.push(new ProviderError(
`Mixing multi and non multi provider is not possible for token ${tokenName(resolvedProvider.token)}`,
sourceSpan));

View File

@ -11,7 +11,6 @@ import {CompileDirectiveMetadata, CompileDirectiveSummary, CompilePipeSummary, C
import {CompilerConfig} from '../config';
import {AST, ASTWithSource, EmptyExpr} from '../expression_parser/ast';
import {Parser} from '../expression_parser/parser';
import {isPresent} from '../facade/lang';
import {I18NHtmlParser} from '../i18n/i18n_html_parser';
import {Identifiers, createIdentifierToken, identifierToken} from '../identifiers';
import {CompilerInjectable} from '../injectable';
@ -295,7 +294,7 @@ class TemplateParseVisitor implements html.Visitor {
prefixToken = normalizedName.substring(TEMPLATE_ATTR_PREFIX.length) + ':';
}
const hasTemplateBinding = isPresent(templateBindingsSource);
const hasTemplateBinding = templateBindingsSource != null;
if (hasTemplateBinding) {
if (hasInlineTemplates) {
this._reportError(
@ -338,7 +337,7 @@ class TemplateParseVisitor implements html.Visitor {
isTemplateElement ? parent.providerContext : providerContext));
providerContext.afterElement();
// Override the actual selector when the `ngProjectAs` attribute is provided
const projectionSelector = isPresent(preparsedElement.projectAs) ?
const projectionSelector = preparsedElement.projectAs != null ?
CssSelector.parse(preparsedElement.projectAs)[0] :
elementCssSelector;
const ngContentIndex = parent.findNgContentIndex(projectionSelector);
@ -415,7 +414,7 @@ class TemplateParseVisitor implements html.Visitor {
if (bindParts !== null) {
hasBinding = true;
if (isPresent(bindParts[KW_BIND_IDX])) {
if (bindParts[KW_BIND_IDX] != null) {
this._bindingParser.parsePropertyBinding(
bindParts[IDENT_KW_IDX], value, false, srcSpan, targetMatchableAttrs, targetProps);
@ -698,7 +697,7 @@ class TemplateParseVisitor implements html.Visitor {
});
events.forEach(event => {
if (isPresent(event.target) || !allDirectiveEvents.has(event.name)) {
if (event.target != null || !allDirectiveEvents.has(event.name)) {
this._reportError(
`Event binding ${event.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "@NgModule.declarations".`,
event.sourceSpan);
@ -811,7 +810,7 @@ class ElementContext {
this._ngContentIndexMatcher.match(
selector, (selector, ngContentIndex) => { ngContentIndices.push(ngContentIndex); });
ngContentIndices.sort();
if (isPresent(this._wildcardNgContentIndex)) {
if (this._wildcardNgContentIndex != null) {
ngContentIndices.push(this._wildcardNgContentIndex);
}
return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
@ -882,4 +881,4 @@ function isTemplate(
return false;
}
}
}

View File

@ -8,7 +8,6 @@
import {Inject, InjectionToken, PACKAGE_ROOT_URL} from '@angular/core';
import {isBlank, isPresent} from './facade/lang';
import {CompilerInjectable} from './injectable';
@ -62,12 +61,12 @@ export class UrlResolver {
*/
resolve(baseUrl: string, url: string): string {
let resolvedUrl = url;
if (isPresent(baseUrl) && baseUrl.length > 0) {
if (baseUrl != null && baseUrl.length > 0) {
resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
}
const resolvedParts = _split(resolvedUrl);
let prefix = this._packagePrefix;
if (isPresent(prefix) && isPresent(resolvedParts) &&
if (prefix != null && resolvedParts != null &&
resolvedParts[_ComponentIndex.Scheme] == 'package') {
let path = resolvedParts[_ComponentIndex.Path];
prefix = prefix.replace(/\/+$/, '');
@ -111,33 +110,33 @@ function _buildFromEncodedParts(
opt_path?: string, opt_queryData?: string, opt_fragment?: string): string {
const out: string[] = [];
if (isPresent(opt_scheme)) {
if (opt_scheme != null) {
out.push(opt_scheme + ':');
}
if (isPresent(opt_domain)) {
if (opt_domain != null) {
out.push('//');
if (isPresent(opt_userInfo)) {
if (opt_userInfo != null) {
out.push(opt_userInfo + '@');
}
out.push(opt_domain);
if (isPresent(opt_port)) {
if (opt_port != null) {
out.push(':' + opt_port);
}
}
if (isPresent(opt_path)) {
if (opt_path != null) {
out.push(opt_path);
}
if (isPresent(opt_queryData)) {
if (opt_queryData != null) {
out.push('?' + opt_queryData);
}
if (isPresent(opt_fragment)) {
if (opt_fragment != null) {
out.push('#' + opt_fragment);
}
@ -309,7 +308,7 @@ function _removeDotSegments(path: string): string {
*/
function _joinAndCanonicalizePath(parts: any[]): string {
let path = parts[_ComponentIndex.Path];
path = isBlank(path) ? '' : _removeDotSegments(path);
path = path == null ? '' : _removeDotSegments(path);
parts[_ComponentIndex.Path] = path;
return _buildFromEncodedParts(
@ -327,14 +326,14 @@ function _resolveUrl(base: string, url: string): string {
const parts = _split(encodeURI(url));
const baseParts = _split(base);
if (isPresent(parts[_ComponentIndex.Scheme])) {
if (parts[_ComponentIndex.Scheme] != null) {
return _joinAndCanonicalizePath(parts);
} else {
parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
}
for (let i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
if (isBlank(parts[i])) {
if (parts[i] == null) {
parts[i] = baseParts[i];
}
}
@ -344,7 +343,7 @@ function _resolveUrl(base: string, url: string): string {
}
let path = baseParts[_ComponentIndex.Path];
if (isBlank(path)) path = '/';
if (path == null) path = '/';
const index = path.lastIndexOf('/');
path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
parts[_ComponentIndex.Path] = path;

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isPrimitive, isStrictStringMap} from './facade/lang';
export const MODULE_SUFFIX = '';
const CAMEL_CASE_REGEXP = /([A-Z])/g;
@ -43,7 +42,8 @@ export function visitValue(value: any, visitor: ValueVisitor, context: any): any
return visitor.visitStringMap(<{[key: string]: any}>value, context);
}
if (value == null || isPrimitive(value)) {
if (value == null || typeof value == 'string' || typeof value == 'number' ||
typeof value == 'boolean') {
return visitor.visitPrimitive(value, context);
}
@ -89,3 +89,12 @@ const ERROR_SYNTAX_ERROR = 'ngSyntaxError';
export function isSyntaxError(error: Error): boolean {
return (error as any)[ERROR_SYNTAX_ERROR];
}
export function escapeRegExp(s: string): string {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
const STRING_MAP_PROTO = Object.getPrototypeOf({});
function isStrictStringMap(obj: any): boolean {
return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
}

View File

@ -8,7 +8,6 @@
import {describe, expect, it} from '../../../core/testing/testing_internal';
import {CssLexer, CssLexerMode, CssToken, CssTokenType, cssScannerError, getRawMessage, getToken} from '../../src/css_parser/css_lexer';
import {isPresent} from '../../src/facade/lang';
export function main() {
function tokenize(
@ -21,7 +20,7 @@ export function main() {
let output = scanner.scan();
while (output != null) {
const error = output.error;
if (isPresent(error)) {
if (error != null) {
throw cssScannerError(getToken(error), getRawMessage(error));
}
tokens.push(output.token);

View File

@ -10,7 +10,6 @@
import {beforeEach, describe, expect, it} from '../../../core/testing/testing_internal';
import {CssAst, CssAstVisitor, CssAtRulePredicateAst, CssBlockAst, CssDefinitionAst, CssInlineRuleAst, CssKeyframeDefinitionAst, CssKeyframeRuleAst, CssMediaQueryRuleAst, CssPseudoSelectorAst, CssRuleAst, CssSelectorAst, CssSelectorRuleAst, CssSimpleSelectorAst, CssStyleSheetAst, CssStyleValueAst, CssStylesBlockAst, CssUnknownRuleAst, CssUnknownTokenListAst} from '../../src/css_parser/css_ast';
import {BlockType, CssParseError, CssParser, CssToken} from '../../src/css_parser/css_parser';
import {isPresent} from '../../src/facade/lang';
function _assertTokens(tokens: CssToken[], valuesArr: string[]): void {
expect(tokens.length).toEqual(valuesArr.length);

View File

@ -11,7 +11,6 @@ import {Lexer} from '@angular/compiler/src/expression_parser/lexer';
import {Parser, SplitInterpolation, TemplateBindingParseResult} from '@angular/compiler/src/expression_parser/parser';
import {expect} from '@angular/platform-browser/testing/matchers';
import {isBlank, isPresent} from '../../src/facade/lang';
import {unparse} from './unparser';
import {validate} from './validator';
@ -50,21 +49,21 @@ export function main() {
function checkInterpolation(exp: string, expected?: string) {
const ast = parseInterpolation(exp);
if (isBlank(expected)) expected = exp;
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
function checkBinding(exp: string, expected?: string) {
const ast = parseBinding(exp);
if (isBlank(expected)) expected = exp;
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
function checkAction(exp: string, expected?: string) {
const ast = parseAction(exp);
if (isBlank(expected)) expected = exp;
if (expected == null) expected = exp;
expect(unparse(ast)).toEqual(expected);
validate(ast);
}
@ -321,9 +320,9 @@ export function main() {
function keyValues(templateBindings: any[]) {
return templateBindings.map(binding => {
if (binding.keyIsVar) {
return 'let ' + binding.key + (isBlank(binding.name) ? '=null' : '=' + binding.name);
return 'let ' + binding.key + (binding.name == null ? '=null' : '=' + binding.name);
} else {
return binding.key + (isBlank(binding.expression) ? '' : `=${binding.expression}`);
return binding.key + (binding.expression == null ? '' : `=${binding.expression}`);
}
});
}
@ -335,7 +334,7 @@ export function main() {
function exprSources(templateBindings: any[]) {
return templateBindings.map(
binding => isPresent(binding.expression) ? binding.expression.source : null);
binding => binding.expression != null ? binding.expression.source : null);
}
it('should parse an empty string', () => { expect(parseTemplateBindings('')).toEqual([]); });

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {escapeRegExp} from '@angular/core/src/facade/lang';
import {escapeRegExp} from '@angular/compiler/src/util';
import {serializeNodes} from '../../../src/i18n/digest';
import {MessageBundle} from '../../../src/i18n/message_bundle';

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {escapeRegExp} from '@angular/core/src/facade/lang';
import {escapeRegExp} from '@angular/compiler/src/util';
import {serializeNodes} from '../../../src/i18n/digest';
import * as i18n from '../../../src/i18n/i18n_ast';
import {Xtb} from '../../../src/i18n/serializers/xtb';

View File

@ -7,12 +7,10 @@
*/
import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/testing/test_bindings';
import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, NgModule, OnChanges, OnDestroy, OnInit, Pipe, SimpleChanges, ViewEncapsulation} from '@angular/core';
import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, Directive, DoCheck, Injectable, NgModule, OnChanges, OnDestroy, OnInit, Pipe, SimpleChanges, ViewEncapsulation, ɵstringify as stringify} from '@angular/core';
import {LIFECYCLE_HOOKS_VALUES} from '@angular/core/src/metadata/lifecycle_hooks';
import {TestBed, async, inject} from '@angular/core/testing';
import {identifierName} from '../src/compile_metadata';
import {stringify} from '../src/facade/lang';
import {CompileMetadataResolver} from '../src/metadata_resolver';
import {ResourceLoader} from '../src/resource_loader';
import {MockResourceLoader} from '../testing/resource_loader_mock';

View File

@ -7,8 +7,8 @@
*/
import {NgModuleResolver} from '@angular/compiler/src/ng_module_resolver';
import {ɵstringify as stringify} from '@angular/core';
import {NgModule} from '@angular/core/src/metadata';
import {stringify} from '../src/facade/lang';
class SomeClass1 {}
class SomeClass2 {}

View File

@ -7,8 +7,8 @@
*/
import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {ɵstringify as stringify} from '@angular/core';
import {Pipe} from '@angular/core/src/metadata';
import {stringify} from '../src/facade/lang';
@Pipe({name: 'somePipe', pure: true})
class SomePipe {

View File

@ -8,7 +8,6 @@
import {MockResourceLoader} from '@angular/compiler/testing/resource_loader_mock';
import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {isPresent} from '../src/facade/lang';
export function main() {
describe('MockResourceLoader', () => {
@ -23,7 +22,7 @@ export function main() {
throw `Unexpected response ${url} -> ${text}`;
} else {
expect(text).toEqual(response);
if (isPresent(done)) done();
if (done != null) done();
}
return text;
}
@ -33,7 +32,7 @@ export function main() {
throw `Unexpected error ${url}`;
} else {
expect(error).toEqual(`Failed to load ${url}`);
if (isPresent(done)) done();
if (done != null) done();
}
return error;
}

View File

@ -7,11 +7,9 @@
*/
import {DirectiveResolver, ResourceLoader} from '@angular/compiler';
import {Compiler, Component, Injector, NgModule, NgModuleFactory, ɵViewMetadata as ViewMetadata} from '@angular/core';
import {Compiler, Component, Injector, NgModule, NgModuleFactory, ɵViewMetadata as ViewMetadata, ɵstringify as stringify} from '@angular/core';
import {TestBed, async, fakeAsync, inject, tick} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {stringify} from '../src/facade/lang';
import {MockDirectiveResolver} from '../testing/index';
import {SpyResourceLoader} from './spies';

View File

@ -9,7 +9,7 @@
import {fakeAsync} from '@angular/core/testing/fake_async';
import {describe, expect, it} from '@angular/core/testing/testing_internal';
import {SyncAsyncResult, splitAtColon} from '../src/util';
import {SyncAsyncResult, escapeRegExp, splitAtColon} from '../src/util';
export function main() {
describe('util', () => {
@ -36,5 +36,14 @@ export function main() {
expect(splitAtColon('ab', ['c', 'd'])).toEqual(['c', 'd']);
});
});
describe('RegExp', () => {
it('should escape regexp', () => {
expect(new RegExp(escapeRegExp('b')).exec('abc')).toBeTruthy();
expect(new RegExp(escapeRegExp('b')).exec('adc')).toBeFalsy();
expect(new RegExp(escapeRegExp('a.b')).exec('a.b')).toBeTruthy();
expect(new RegExp(escapeRegExp('a.b')).exec('axb')).toBeFalsy();
});
});
});
}

View File

@ -7,7 +7,6 @@
*/
import {DirectiveResolver} from '@angular/compiler';
import {Compiler, Component, Directive, Injectable, Injector, Provider, Type, resolveForwardRef, ɵViewMetadata as ViewMetadata} from '@angular/core';
import {isPresent} from './facade/lang';
@ -42,14 +41,14 @@ export class MockDirectiveResolver extends DirectiveResolver {
const viewProviderOverrides = this._viewProviderOverrides.get(type);
let providers = metadata.providers;
if (isPresent(providerOverrides)) {
if (providerOverrides != null) {
const originalViewProviders: Provider[] = metadata.providers || [];
providers = originalViewProviders.concat(providerOverrides);
}
if (metadata instanceof Component) {
let viewProviders = metadata.viewProviders;
if (isPresent(viewProviderOverrides)) {
if (viewProviderOverrides != null) {
const originalViewProviders: Provider[] = metadata.viewProviders || [];
viewProviders = originalViewProviders.concat(viewProviderOverrides);
}
@ -63,7 +62,7 @@ export class MockDirectiveResolver extends DirectiveResolver {
let templateUrl = view.templateUrl;
let inlineTemplate = this._inlineTemplates.get(type);
if (isPresent(inlineTemplate)) {
if (inlineTemplate != null) {
templateUrl = null;
} else {
inlineTemplate = view.template;
@ -137,7 +136,7 @@ export class MockDirectiveResolver extends DirectiveResolver {
}
function flattenArray(tree: any[], out: Array<Type<any>|any[]>): void {
if (!isPresent(tree)) return;
if (tree == null) return;
for (let i = 0; i < tree.length; i++) {
const item = resolveForwardRef(tree[i]);
if (Array.isArray(item)) {

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -6,8 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ɵstringify as stringify} from '@angular/core';
import {MetadataOverride} from '@angular/core/testing';
import {stringify} from './facade/lang';
type StringMap = {
[key: string]: any

View File

@ -7,7 +7,6 @@
*/
import {ResourceLoader} from '@angular/compiler';
import {isBlank} from './facade/lang';
/**
* A mock implementation of {@link ResourceLoader} that allows outgoing requests to be mocked
@ -110,7 +109,7 @@ class _PendingRequest {
}
complete(response: string) {
if (isBlank(response)) {
if (response == null) {
this.reject(`Failed to load ${this.url}`);
} else {
this.resolve(response);

View File

@ -12,12 +12,9 @@ import {Subject} from 'rxjs/Subject';
import {Subscription} from 'rxjs/Subscription';
import {merge} from 'rxjs/observable/merge';
import {share} from 'rxjs/operator/share';
import {ErrorHandler} from '../src/error_handler';
import {stringify} from '../src/facade/lang';
import {scheduleMicroTask} from '../src/util';
import {scheduleMicroTask, stringify} from '../src/util';
import {isPromise} from '../src/util/lang';
import {ApplicationInitStatus} from './application_init';
import {APP_BOOTSTRAP_LISTENER, PLATFORM_INITIALIZER} from './application_tokens';
import {Console} from './console';

View File

@ -12,7 +12,7 @@ import {IterableDifferFactory, IterableDiffers} from './differs/iterable_differs
import {KeyValueDifferFactory, KeyValueDiffers} from './differs/keyvalue_differs';
export {SimpleChanges} from '../metadata/lifecycle_hooks';
export {SimpleChange, ValueUnwrapper, WrappedValue, devModeEqual, looseIdentical} from './change_detection_util';
export {SimpleChange, ValueUnwrapper, WrappedValue, devModeEqual} from './change_detection_util';
export {ChangeDetectorRef} from './change_detector_ref';
export {ChangeDetectionStrategy, ChangeDetectorStatus, isDefaultChangeDetectionStrategy} from './constants';
export {DefaultIterableDifferFactory} from './differs/default_iterable_differ';

View File

@ -6,21 +6,21 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isJsObject, isPrimitive, looseIdentical} from '../facade/lang';
import {getSymbolIterator} from '../util';
export {looseIdentical} from '../facade/lang';
import {getSymbolIterator, looseIdentical} from '../util';
export function devModeEqual(a: any, b: any): boolean {
if (isListLikeIterable(a) && isListLikeIterable(b)) {
const isListLikeIterableA = isListLikeIterable(a);
const isListLikeIterableB = isListLikeIterable(b);
if (isListLikeIterableA && isListLikeIterableB) {
return areIterablesEqual(a, b, devModeEqual);
} else if (
!isListLikeIterable(a) && !isPrimitive(a) && !isListLikeIterable(b) && !isPrimitive(b)) {
return true;
} else {
return looseIdentical(a, b);
const isAObject = a && (typeof a === 'object' || typeof a === 'function');
const isBObject = b && (typeof b === 'object' || typeof b === 'function');
if (!isListLikeIterableA && isAObject && !isListLikeIterableB && isBObject) {
return true;
} else {
return looseIdentical(a, b);
}
}
}
@ -113,3 +113,7 @@ export function iterateListLike(obj: any, fn: (p: any) => any) {
}
}
}
export function isJsObject(o: any): boolean {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}

View File

@ -6,7 +6,6 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isBlank} from '../facade/lang';
/**
* Describes within the change detector which strategy will be used the next time change
@ -68,6 +67,6 @@ export enum ChangeDetectorStatus {
export function isDefaultChangeDetectionStrategy(changeDetectionStrategy: ChangeDetectionStrategy):
boolean {
return isBlank(changeDetectionStrategy) ||
return changeDetectionStrategy == null ||
changeDetectionStrategy === ChangeDetectionStrategy.Default;
}

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isBlank, looseIdentical, stringify} from '../../facade/lang';
import {looseIdentical, stringify} from '../../util';
import {isListLikeIterable, iterateListLike} from '../change_detection_util';
import {ChangeDetectorRef} from '../change_detector_ref';
@ -155,7 +155,7 @@ export class DefaultIterableDiffer<V> implements IterableDiffer<V>, IterableChan
}
diff(collection: NgIterable<V>): DefaultIterableDiffer<V> {
if (isBlank(collection)) collection = [];
if (collection == null) collection = [];
if (!isListLikeIterable(collection)) {
throw new Error(`Error trying to diff '${collection}'`);
}

View File

@ -6,7 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isJsObject, looseIdentical, stringify} from '../../facade/lang';
import {looseIdentical, stringify} from '../../util';
import {isJsObject} from '../change_detection_util';
import {ChangeDetectorRef} from '../change_detector_ref';
import {KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFactory} from './keyvalue_differs';

View File

@ -7,7 +7,6 @@
*/
import {Optional, Provider, SkipSelf} from '../../di';
import {getTypeNameForDebugging, isPresent} from '../../facade/lang';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
@ -158,7 +157,7 @@ export class IterableDiffers {
constructor(factories: IterableDifferFactory[]) { this.factories = factories; }
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers {
if (isPresent(parent)) {
if (parent != null) {
const copied = parent.factories.slice();
factories = factories.concat(copied);
return new IterableDiffers(factories);
@ -205,7 +204,7 @@ export class IterableDiffers {
find(iterable: any): IterableDifferFactory {
const factory = this.factories.find(f => f.supports(iterable));
if (isPresent(factory)) {
if (factory != null) {
return factory;
} else {
throw new Error(
@ -213,3 +212,7 @@ export class IterableDiffers {
}
}
}
export function getTypeNameForDebugging(type: any): string {
return type['name'] || typeof type;
}

View File

@ -7,11 +7,16 @@
*/
import {Injectable} from './di';
import {print, warn} from './facade/lang';
@Injectable()
export class Console {
log(message: string): void { print(message); }
log(message: string): void {
// tslint:disable-next-line:no-console
console.log(message);
}
// Note: for reporting errors use `DOM.logError()` as it is platform specific
warn(message: string): void { warn(message); }
warn(message: string): void {
// tslint:disable-next-line:no-console
console.warn(message);
}
}

View File

@ -23,6 +23,6 @@ export {ReflectionCapabilities as ɵReflectionCapabilities} from './reflection/r
export {ReflectorReader as ɵReflectorReader} from './reflection/reflector_reader';
export {GetterFn as ɵGetterFn, MethodFn as ɵMethodFn, SetterFn as ɵSetterFn} from './reflection/types';
export {DirectRenderer as ɵDirectRenderer, RenderDebugInfo as ɵRenderDebugInfo} from './render/api';
export {global as ɵglobal} from './util';
export {global as ɵglobal, looseIdentical as ɵlooseIdentical, stringify as ɵstringify} from './util';
export {makeDecorator as ɵmakeDecorator} from './util/decorators';
export {isObservable as ɵisObservable, isPromise as ɵisPromise, merge as ɵmerge} from './util/lang';

View File

@ -6,8 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {stringify} from '../util';
/**

View File

@ -6,8 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {stringify} from '../util';
import {InjectionToken} from './injection_token';

View File

@ -8,8 +8,8 @@
import {wrappedError} from '../error_handler';
import {ERROR_ORIGINAL_ERROR, getOriginalError} from '../errors';
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {stringify} from '../util';
import {ReflectiveInjector} from './reflective_injector';
import {ReflectiveKey} from './reflective_key';

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {stringify} from '../facade/lang';
import {stringify} from '../util';
import {resolveForwardRef} from './forward_ref';

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -6,8 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {stringify} from '../util';
import {ComponentFactory} from './component_factory';

View File

@ -7,8 +7,9 @@
*/
import {Injector, THROW_IF_NOT_FOUND} from '../di/injector';
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {stringify} from '../util';
import {ComponentFactory} from './component_factory';
import {CodegenComponentFactoryResolver, ComponentFactoryResolver} from './component_factory_resolver';

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {isPresent, stringify} from '../facade/lang';
import {Type, isType} from '../type';
import {global} from '../util';
import {global, stringify} from '../util';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
import {GetterFn, MethodFn, SetterFn} from './types';
@ -48,7 +47,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
} else {
result[i] = [];
}
if (paramAnnotations && isPresent(paramAnnotations[i])) {
if (paramAnnotations && paramAnnotations[i] != null) {
result[i] = result[i].concat(paramAnnotations[i]);
}
}
@ -87,7 +86,7 @@ export class ReflectionCapabilities implements PlatformReflectionCapabilities {
}
// API for metadata created by invoking the decorators.
if (isPresent(this._reflect) && isPresent(this._reflect.getOwnMetadata)) {
if (this._reflect != null && this._reflect.getOwnMetadata != null) {
const paramAnnotations = this._reflect.getOwnMetadata('parameters', type);
const paramTypes = this._reflect.getOwnMetadata('design:paramtypes', type);
if (paramTypes || paramAnnotations) {

View File

@ -24,7 +24,7 @@ declare const Symbol: any;
let _symbolIterator: any = null;
export function getSymbolIterator(): string|symbol {
if (!_symbolIterator) {
var Symbol = _global['Symbol'];
const Symbol = _global['Symbol'];
if (Symbol && Symbol.iterator) {
_symbolIterator = Symbol.iterator;
} else {
@ -45,3 +45,30 @@ export function getSymbolIterator(): string|symbol {
export function scheduleMicroTask(fn: Function) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
// JS has NaN !== NaN
export function looseIdentical(a: any, b: any): boolean {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}

View File

@ -6,9 +6,8 @@
* found in the LICENSE file at https://angular.io/license
*/
import {stringify} from '../facade/lang';
import {Type} from '../type';
import {global} from '../util';
import {global, stringify} from '../util';
let _nextClassId = 0;
const Reflect = global['Reflect'];

View File

@ -7,7 +7,7 @@
*/
import {isDevMode} from '../application_ref';
import {looseIdentical} from '../facade/lang';
import {looseIdentical} from '../util';
import {BindingDef, BindingType, DebugContext, NodeData, NodeDef, NodeFlags, RootData, Services, TextData, ViewData, ViewFlags, asElementData, asTextData} from './types';
import {checkAndUpdateBinding, getParentRenderElement, sliceErrorStack} from './util';

View File

@ -10,12 +10,12 @@ import {isDevMode} from '../application_ref';
import {WrappedValue, devModeEqual} from '../change_detection/change_detection';
import {SimpleChange} from '../change_detection/change_detection_util';
import {Injector} from '../di';
import {looseIdentical, stringify} from '../facade/lang';
import {TemplateRef} from '../linker/template_ref';
import {ViewContainerRef} from '../linker/view_container_ref';
import {ViewRef} from '../linker/view_ref';
import {ViewEncapsulation} from '../metadata/view';
import {Renderer, RendererTypeV2} from '../render/api';
import {looseIdentical, stringify} from '../util';
import {expressionChangedAfterItHasBeenCheckedError, isViewDebugError, viewDestroyedError, viewWrappedDebugError} from './errors';
import {DebugContext, ElementData, NodeData, NodeDef, NodeFlags, QueryValueType, Services, ViewData, ViewDefinition, ViewDefinitionFactory, ViewFlags, ViewState, asElementData, asProviderData, asTextData} from './types';
@ -389,4 +389,4 @@ function _toStringWithNull(v: any): string {
}
export const EMPTY_ARRAY: any[] = [];
export const EMPTY_MAP: {[key: string]: any} = {};
export const EMPTY_MAP: {[key: string]: any} = {};

View File

@ -11,8 +11,7 @@ import {ReflectiveInjector_} from '@angular/core/src/di/reflective_injector';
import {ResolvedReflectiveProvider_} from '@angular/core/src/di/reflective_provider';
import {getOriginalError} from '@angular/core/src/errors';
import {expect} from '@angular/platform-browser/testing/matchers';
import {isPresent, stringify} from '../../src/facade/lang';
import {stringify} from '../../src/util';
class Engine {}
@ -82,7 +81,7 @@ export function main() {
function createInjector(
providers: Provider[], parent: ReflectiveInjector = null): ReflectiveInjector_ {
const resolvedProviders = ReflectiveInjector.resolve(providers.concat(dynamicProviders));
if (isPresent(parent)) {
if (parent != null) {
return <ReflectiveInjector_>parent.createChildFromResolved(resolvedProviders);
} else {
return <ReflectiveInjector_>ReflectiveInjector.fromResolvedProviders(resolvedProviders);

View File

@ -1,63 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/testing/testing_internal';
import {Observable} from 'rxjs/Observable';
export function main() {
describe('Observable', () => {
describe('#core', () => {
it('should call next with values',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const o = new Observable((sink: any /** TODO #9100 */) => { sink.next(1); });
o.subscribe(v => {
expect(v).toEqual(1);
async.done();
});
}));
it('should call next and then complete',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const o = new Observable((sink: any /** TODO #9100 */) => {
sink.next(1);
sink.complete();
});
let nexted = false;
o.subscribe(
v => { nexted = true; }, null,
() => {
expect(nexted).toBe(true);
async.done();
});
}));
it('should call error with errors',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const o = new Observable((sink: any /** TODO #9100 */) => { sink.error('oh noes!'); });
o.subscribe(
v => {
},
(err) => {
expect(err).toEqual('oh noes!');
async.done();
});
}));
});
});
}

View File

@ -22,8 +22,7 @@ import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {DOCUMENT} from '@angular/platform-browser/src/dom/dom_tokens';
import {dispatchEvent, el} from '@angular/platform-browser/testing/browser_util';
import {expect} from '@angular/platform-browser/testing/matchers';
import {stringify} from '../../src/facade/lang';
import {stringify} from '../../src/util';
const ANCHOR_ELEMENT = new InjectionToken('AnchorElement');

View File

@ -11,9 +11,9 @@ import {Console} from '@angular/core/src/console';
import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {stringify} from '../../src/facade/lang';
import {NgModuleInjector} from '../../src/linker/ng_module_factory';
import {clearModulesForTest} from '../../src/linker/ng_module_factory_loader';
import {stringify} from '../../src/util';
class Engine {}

View File

@ -10,7 +10,7 @@ import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit,
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/matchers';
import {stringify} from '../../src/facade/lang';
import {stringify} from '../../src/util';
export function main() {
describe('Query API', () => {

View File

@ -10,7 +10,6 @@ import {NgZone} from '@angular/core/src/zone/ng_zone';
import {async, fakeAsync, flushMicrotasks} from '@angular/core/testing';
import {AsyncTestCompleter, Log, beforeEach, describe, expect, inject, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing/browser_util';
import {isPresent} from '../../src/facade/lang';
import {scheduleMicroTask} from '../../src/util';
const needsLongerTimers = browserDetection.isSlow || browserDetection.isEdge;
@ -159,7 +158,7 @@ export function main() {
promise.then((_) => {
expect(_traces.length).toBe(1);
if (isPresent(_traces[0])) {
if (_traces[0] != null) {
// some browsers don't have stack traces.
expect(_traces[0].indexOf('---')).toEqual(-1);
}

View File

@ -1 +0,0 @@
../../facade/src

View File

@ -6,10 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
import {CompilerOptions, Component, Directive, InjectionToken, Injector, ModuleWithComponentFactories, NgModule, NgModuleRef, NgZone, Pipe, PlatformRef, Provider, ReflectiveInjector, SchemaMetadata, Type, ɵERROR_COMPONENT_TYPE} from '@angular/core';
import {CompilerOptions, Component, Directive, InjectionToken, Injector, ModuleWithComponentFactories, NgModule, NgModuleRef, NgZone, Pipe, PlatformRef, Provider, ReflectiveInjector, SchemaMetadata, Type, ɵERROR_COMPONENT_TYPE, ɵstringify as stringify} from '@angular/core';
import {AsyncTestCompleter} from './async_test_completer';
import {ComponentFixture} from './component_fixture';
import {stringify} from './facade/lang';
import {MetadataOverride} from './metadata_override';
import {TestingCompiler, TestingCompilerFactory} from './test_compiler';

View File

@ -1,19 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
// #docregion Observable
import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber';
const obs = new Observable<number>((obs: Subscriber<number>) => {
let i = 0;
setInterval(() => { obs.next(++i); }, 1000);
});
obs.subscribe(i => console.log(`${i} seconds elapsed`));
// #enddocregion

View File

@ -1,21 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
// #docregion Observable
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber';
const obs = new Observable<number>((obs: Subscriber<any>) => {
let i = 0;
setInterval(() => obs.next(++i), 1000);
});
obs.map((i: number) => `${i} seconds elapsed`).subscribe(msg => console.log(msg));
// #enddocregion

View File

@ -1,20 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* tslint:disable:no-console */
// #docregion Observable
import {Observable} from 'rxjs/Observable';
import {Subscriber} from 'rxjs/Subscriber';
import {map} from 'rxjs/operator/map';
const obs = new Observable<number>((sub: Subscriber<number>) => {
let i = 0;
setInterval(() => sub.next(++i), 1000);
});
map.call(obs, (i: number) => `${i} seconds elapsed`).subscribe((msg: string) => console.log(msg));
// #enddocregion

View File

@ -1,102 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export function getTypeNameForDebugging(type: any): string {
return type['name'] || typeof type;
}
export function isPresent(obj: any): boolean {
return obj != null;
}
export function isBlank(obj: any): boolean {
return obj == null;
}
const STRING_MAP_PROTO = Object.getPrototypeOf({});
export function isStrictStringMap(obj: any): boolean {
return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
}
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
const res = token.toString();
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
export class NumberWrapper {
static parseIntAutoRadix(text: string): number {
const result: number = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
static isNumeric(value: any): boolean { return !isNaN(value - parseFloat(value)); }
}
// JS has NaN !== NaN
export function looseIdentical(a: any, b: any): boolean {
return a === b || typeof a === 'number' && typeof b === 'number' && isNaN(a) && isNaN(b);
}
export function isJsObject(o: any): boolean {
return o !== null && (typeof o === 'function' || typeof o === 'object');
}
export function print(obj: Error | Object) {
// tslint:disable-next-line:no-console
console.log(obj);
}
export function warn(obj: Error | Object) {
console.warn(obj);
}
export function setValueOnPath(global: any, path: string, value: any) {
const parts = path.split('.');
let obj: any = global;
while (parts.length > 1) {
const name = parts.shift();
if (obj.hasOwnProperty(name) && obj[name] != null) {
obj = obj[name];
} else {
obj = obj[name] = {};
}
}
if (obj === undefined || obj === null) {
obj = {};
}
obj[parts.shift()] = value;
}
export function isPrimitive(obj: any): boolean {
return !isJsObject(obj);
}
export function escapeRegExp(s: string): string {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}

View File

@ -1,43 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NumberWrapper, escapeRegExp} from '../src/lang';
export function main() {
describe('RegExp', () => {
it('should escape regexp', () => {
expect(new RegExp(escapeRegExp('b')).exec('abc')).toBeTruthy();
expect(new RegExp(escapeRegExp('b')).exec('adc')).toBeFalsy();
expect(new RegExp(escapeRegExp('a.b')).exec('a.b')).toBeTruthy();
expect(new RegExp(escapeRegExp('a.b')).exec('axb')).toBeFalsy();
});
});
describe('Number', () => {
describe('isNumeric', () => {
it('should return true when passing correct numeric string',
() => { expect(NumberWrapper.isNumeric('2')).toBe(true); });
it('should return true when passing correct double string',
() => { expect(NumberWrapper.isNumeric('1.123')).toBe(true); });
it('should return true when passing correct negative string',
() => { expect(NumberWrapper.isNumeric('-2')).toBe(true); });
it('should return true when passing correct scientific notation string',
() => { expect(NumberWrapper.isNumeric('1e5')).toBe(true); });
it('should return false when passing incorrect numeric',
() => { expect(NumberWrapper.isNumeric('a')).toBe(false); });
it('should return false when passing parseable but non numeric',
() => { expect(NumberWrapper.isNumeric('2a')).toBe(false); });
});
});
}

Some files were not shown because too many files have changed in this diff Show More