refactor(ListWrapper): get ride of ListWrapper.map

This commit is contained in:
Victor Berchet 2015-10-06 18:00:42 -07:00
parent b6537ad609
commit aaa215514b
24 changed files with 79 additions and 104 deletions

View File

@ -67,7 +67,7 @@ function _sameDirIndex(a: ProtoRecord, b: ProtoRecord): boolean {
} }
function _replaceIndices(r: ProtoRecord, selfIndex: number, indexMap: Map<any, any>) { function _replaceIndices(r: ProtoRecord, selfIndex: number, indexMap: Map<any, any>) {
var args = ListWrapper.map(r.args, (a) => _map(indexMap, a)); var args = r.args.map(a => _map(indexMap, a));
var contextIndex = _map(indexMap, r.contextIndex); var contextIndex = _map(indexMap, r.contextIndex);
return new ProtoRecord(r.mode, r.name, r.funcOrValue, args, r.fixedArgs, contextIndex, return new ProtoRecord(r.mode, r.name, r.funcOrValue, args, r.fixedArgs, contextIndex,
r.directiveIndex, selfIndex, r.bindingRecord, r.lastInBinding, r.directiveIndex, selfIndex, r.bindingRecord, r.lastInBinding,

View File

@ -1,4 +1,3 @@
import {ListWrapper} from 'angular2/src/core/facade/collection';
import {Json, StringWrapper, isPresent, isBlank} from 'angular2/src/core/facade/lang'; import {Json, StringWrapper, isPresent, isBlank} from 'angular2/src/core/facade/lang';
import {CodegenNameUtil} from './codegen_name_util'; import {CodegenNameUtil} from './codegen_name_util';
import {codify, combineGeneratedStrings, rawString} from './codegen_facade'; import {codify, combineGeneratedStrings, rawString} from './codegen_facade';
@ -38,7 +37,7 @@ export class CodegenLogicUtil {
var context = (protoRec.contextIndex == -1) ? var context = (protoRec.contextIndex == -1) ?
this._names.getDirectiveName(protoRec.directiveIndex) : this._names.getDirectiveName(protoRec.directiveIndex) :
getLocalName(protoRec.contextIndex); getLocalName(protoRec.contextIndex);
var argString = ListWrapper.map(protoRec.args, (arg) => getLocalName(arg)).join(", "); var argString = protoRec.args.map(arg => getLocalName(arg)).join(", ");
var rhs: string; var rhs: string;
switch (protoRec.mode) { switch (protoRec.mode) {

View File

@ -434,19 +434,20 @@ export class ShadowCss {
for (var i = 0; i < splits.length; i++) { for (var i = 0; i < splits.length; i++) {
var sep = splits[i]; var sep = splits[i];
var parts = scoped.split(sep); var parts = scoped.split(sep);
scoped = ListWrapper.map(parts, function(p) { scoped = parts.map(p => {
// remove :host since it should be unnecessary // remove :host since it should be unnecessary
var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, ''); var t = StringWrapper.replaceAll(p.trim(), _polyfillHostRe, '');
if (t.length > 0 && !ListWrapper.contains(splits, t) && if (t.length > 0 && !ListWrapper.contains(splits, t) &&
!StringWrapper.contains(t, attrName)) { !StringWrapper.contains(t, attrName)) {
var re = /([^:]*)(:*)(.*)/g; var re = /([^:]*)(:*)(.*)/g;
var m = RegExpWrapper.firstMatch(re, t); var m = RegExpWrapper.firstMatch(re, t);
if (isPresent(m)) { if (isPresent(m)) {
p = m[1] + attrName + m[2] + m[3]; p = m[1] + attrName + m[2] + m[3];
} }
} }
return p; return p;
}).join(sep); })
.join(sep);
} }
return scoped; return scoped;
} }

View File

@ -27,8 +27,7 @@ function _setElementId(element, indices: number[]) {
function _getElementId(element): number[] { function _getElementId(element): number[] {
var elId = DOM.getData(element, NG_ID_PROPERTY); var elId = DOM.getData(element, NG_ID_PROPERTY);
if (isPresent(elId)) { if (isPresent(elId)) {
return ListWrapper.map(elId.split(NG_ID_SEPARATOR), return elId.split(NG_ID_SEPARATOR).map(partStr => NumberWrapper.parseInt(partStr, 10));
(partStr) => NumberWrapper.parseInt(partStr, 10));
} else { } else {
return null; return null;
} }

View File

@ -556,8 +556,8 @@ function _constructDependencies(factoryFunction: Function, dependencies: any[]):
if (isBlank(dependencies)) { if (isBlank(dependencies)) {
return _dependenciesFor(factoryFunction); return _dependenciesFor(factoryFunction);
} else { } else {
var params: any[][] = ListWrapper.map(dependencies, (t) => [t]); var params: any[][] = dependencies.map(t => [t]);
return ListWrapper.map(dependencies, (t) => _extractToken(factoryFunction, t, params)); return dependencies.map(t => _extractToken(factoryFunction, t, params));
} }
} }
@ -567,7 +567,7 @@ function _dependenciesFor(typeOrFunc): Dependency[] {
if (ListWrapper.any(params, (p) => isBlank(p))) { if (ListWrapper.any(params, (p) => isBlank(p))) {
throw new NoAnnotationError(typeOrFunc, params); throw new NoAnnotationError(typeOrFunc, params);
} }
return ListWrapper.map(params, (p: any[]) => _extractToken(typeOrFunc, p, params)); return params.map((p: any[]) => _extractToken(typeOrFunc, p, params));
} }
function _extractToken(typeOrFunc, metadata /*any[] | any*/, params: any[][]): Dependency { function _extractToken(typeOrFunc, metadata /*any[] | any*/, params: any[][]): Dependency {

View File

@ -20,7 +20,7 @@ function findFirstClosedCycle(keys: any[]): any[] {
function constructResolvingPath(keys: any[]): string { function constructResolvingPath(keys: any[]): string {
if (keys.length > 1) { if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = ListWrapper.map(reversed, (k) => stringify(k.token)); var tokenStrs = reversed.map(k => stringify(k.token));
return " (" + tokenStrs.join(' -> ') + ")"; return " (" + tokenStrs.join(' -> ') + ")";
} else { } else {
return ""; return "";
@ -220,7 +220,7 @@ export class NoAnnotationError extends BaseException {
if (isBlank(parameter) || parameter.length == 0) { if (isBlank(parameter) || parameter.length == 0) {
signature.push('?'); signature.push('?');
} else { } else {
signature.push(ListWrapper.map(parameter, stringify).join(' ')); signature.push(parameter.map(stringify).join(' '));
} }
} }
return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +

View File

@ -117,7 +117,6 @@ class ListWrapper {
new List.generate(size, (_) => null, growable: true); new List.generate(size, (_) => null, growable: true);
static bool contains(List m, k) => m.contains(k); static bool contains(List m, k) => m.contains(k);
static List map(list, fn(item)) => list.map(fn).toList();
static List filter(List list, bool fn(item)) => list.where(fn).toList(); static List filter(List list, bool fn(item)) => list.where(fn).toList();
static int indexOf(List list, value, [int startIndex = 0]) => static int indexOf(List list, value, [int startIndex = 0]) =>
list.indexOf(value, startIndex); list.indexOf(value, startIndex);

View File

@ -177,7 +177,6 @@ export class ListWrapper {
static createFixedSize(size: number): any[] { return new Array(size); } static createFixedSize(size: number): any[] { return new Array(size); }
static createGrowableSize(size: number): any[] { return new Array(size); } static createGrowableSize(size: number): any[] { return new Array(size); }
static clone<T>(array: T[]): T[] { return array.slice(0); } static clone<T>(array: T[]): T[] { return array.slice(0); }
static map<T, V>(array: T[], fn: (T) => V): V[] { return array.map(fn); }
static forEach<T>(array: T[], fn: (T) => void) { static forEach<T>(array: T[], fn: (T) => void) {
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
fn(array[i]); fn(array[i]);

View File

@ -1,5 +1,5 @@
import {Injectable} from 'angular2/src/core/di'; import {Injectable} from 'angular2/src/core/di';
import {StringMapWrapper, ListWrapper} from 'angular2/src/core/facade/collection'; import {StringMapWrapper} from 'angular2/src/core/facade/collection';
import {isPresent, isArray} from 'angular2/src/core/facade/lang'; import {isPresent, isArray} from 'angular2/src/core/facade/lang';
import * as modelModule from './model'; import * as modelModule from './model';
@ -88,7 +88,7 @@ export class FormBuilder {
} }
array(controlsConfig: any[], validator: Function = null): modelModule.ControlArray { array(controlsConfig: any[], validator: Function = null): modelModule.ControlArray {
var controls = ListWrapper.map(controlsConfig, (c) => this._createControl(c)); var controls = controlsConfig.map(c => this._createControl(c));
if (isPresent(validator)) { if (isPresent(validator)) {
return new modelModule.ControlArray(controls, validator); return new modelModule.ControlArray(controls, validator);
} else { } else {

View File

@ -201,7 +201,7 @@ function _createEventEmitterAccessors(bwv: BindingWithVisibility): EventEmitterA
var binding = bwv.binding; var binding = bwv.binding;
if (!(binding instanceof DirectiveBinding)) return []; if (!(binding instanceof DirectiveBinding)) return [];
var db = <DirectiveBinding>binding; var db = <DirectiveBinding>binding;
return ListWrapper.map(db.eventEmitters, eventConfig => { return db.eventEmitters.map(eventConfig => {
var parsedEvent = EventConfig.parse(eventConfig); var parsedEvent = EventConfig.parse(eventConfig);
return new EventEmitterAccessor(parsedEvent.eventName, reflector.getter(parsedEvent.fieldName)); return new EventEmitterAccessor(parsedEvent.eventName, reflector.getter(parsedEvent.fieldName));
}); });

View File

@ -121,7 +121,7 @@ export class RouteRegistry {
var possibleMatches = componentRecognizer.recognize(parsedUrl); var possibleMatches = componentRecognizer.recognize(parsedUrl);
var matchPromises = var matchPromises =
ListWrapper.map(possibleMatches, (candidate) => this._completePrimaryRouteMatch(candidate)); possibleMatches.map(candidate => this._completePrimaryRouteMatch(candidate));
return PromiseWrapper.all(matchPromises).then(mostSpecific); return PromiseWrapper.all(matchPromises).then(mostSpecific);
} }

View File

@ -169,7 +169,7 @@ export class FunctionWithParamTokens {
* Returns the value of the executed function. * Returns the value of the executed function.
*/ */
execute(injector: Injector): any { execute(injector: Injector): any {
var params = ListWrapper.map(this._tokens, (t) => injector.get(t)); var params = this._tokens.map(t => injector.get(t));
return FunctionWrapper.apply(this._fn, params); return FunctionWrapper.apply(this._fn, params);
} }

View File

@ -120,12 +120,12 @@ export class RenderViewWithFragmentsStore {
if (this._onWebWorker) { if (this._onWebWorker) {
return { return {
'viewRef': (<WebWorkerRenderViewRef>view.viewRef).serialize(), 'viewRef': (<WebWorkerRenderViewRef>view.viewRef).serialize(),
'fragmentRefs': ListWrapper.map(view.fragmentRefs, (val) => val.serialize()) 'fragmentRefs': view.fragmentRefs.map(val => (<any>val).serialize())
}; };
} else { } else {
return { return {
'viewRef': this._lookupByView.get(view.viewRef), 'viewRef': this._lookupByView.get(view.viewRef),
'fragmentRefs': ListWrapper.map(view.fragmentRefs, (val) => this._lookupByView.get(val)) 'fragmentRefs': view.fragmentRefs.map(val => this._lookupByView.get(val))
}; };
} }
} }
@ -136,8 +136,7 @@ export class RenderViewWithFragmentsStore {
} }
var viewRef = this.deserializeRenderViewRef(obj['viewRef']); var viewRef = this.deserializeRenderViewRef(obj['viewRef']);
var fragments = var fragments = obj['fragmentRefs'].map(val => this.deserializeRenderFragmentRef(val));
ListWrapper.map(obj['fragmentRefs'], (val) => this.deserializeRenderFragmentRef(val));
return new RenderViewWithFragments(viewRef, fragments); return new RenderViewWithFragments(viewRef, fragments);
} }

View File

@ -156,7 +156,7 @@ export function getAllDefinitions(): TestDefinition[] {
"onPushObserveDirective", "onPushObserveDirective",
"updateElementProduction" "updateElementProduction"
]); ]);
return ListWrapper.map(allDefs, (id) => getDefinition(id)); return allDefs.map(getDefinition);
} }
class _ExpressionWithLocals { class _ExpressionWithLocals {

View File

@ -1,7 +1,7 @@
import {ddescribe, describe, it, xit, iit, expect, beforeEach} from 'angular2/test_lib'; import {ddescribe, describe, it, xit, iit, expect, beforeEach} from 'angular2/test_lib';
import {isBlank, isPresent} from 'angular2/src/core/facade/lang'; import {isBlank, isPresent} from 'angular2/src/core/facade/lang';
import {reflector} from 'angular2/src/core/reflection/reflection'; import {reflector} from 'angular2/src/core/reflection/reflection';
import {MapWrapper, ListWrapper} from 'angular2/src/core/facade/collection'; import {MapWrapper} from 'angular2/src/core/facade/collection';
import {Parser} from 'angular2/src/core/change_detection/parser/parser'; import {Parser} from 'angular2/src/core/change_detection/parser/parser';
import {Unparser} from './unparser'; import {Unparser} from './unparser';
import {Lexer} from 'angular2/src/core/change_detection/parser/lexer'; import {Lexer} from 'angular2/src/core/change_detection/parser/lexer';
@ -270,12 +270,10 @@ export function main() {
describe('parseTemplateBindings', () => { describe('parseTemplateBindings', () => {
function keys(templateBindings) { function keys(templateBindings) { return templateBindings.map(binding => binding.key); }
return ListWrapper.map(templateBindings, (binding) => binding.key);
}
function keyValues(templateBindings) { function keyValues(templateBindings) {
return ListWrapper.map(templateBindings, (binding) => { return templateBindings.map(binding => {
if (binding.keyIsVar) { if (binding.keyIsVar) {
return '#' + binding.key + (isBlank(binding.name) ? '=null' : '=' + binding.name); return '#' + binding.key + (isBlank(binding.name) ? '=null' : '=' + binding.name);
} else { } else {
@ -285,9 +283,8 @@ export function main() {
} }
function exprSources(templateBindings) { function exprSources(templateBindings) {
return ListWrapper.map(templateBindings, (binding) => isPresent(binding.expression) ? return templateBindings.map(
binding.expression.source : binding => isPresent(binding.expression) ? binding.expression.source : null);
null);
} }
it('should parse an empty string', () => { expect(parseTemplateBindings('')).toEqual([]); }); it('should parse an empty string', () => { expect(parseTemplateBindings('')).toEqual([]); });

View File

@ -235,8 +235,8 @@ export function main() {
dynamicBindings.push(bind(i).toValue(i)); dynamicBindings.push(bind(i).toValue(i));
} }
function createPei(parent, index, bindings, distance = 1, hasShadowRoot = false, dirVariableBindings = null) { function createPei(parent, index, bindings: any[], distance = 1, hasShadowRoot = false, dirVariableBindings = null) {
var directiveBinding = ListWrapper.map(bindings, b => { var directiveBinding = bindings.map(b => {
if (b instanceof DirectiveBinding) return b; if (b instanceof DirectiveBinding) return b;
if (b instanceof Binding) return DirectiveBinding.createFromBinding(b, null); if (b instanceof Binding) return DirectiveBinding.createFromBinding(b, null);
return DirectiveBinding.createFromType(b, null); return DirectiveBinding.createFromType(b, null);

View File

@ -5,12 +5,11 @@ import {Promise, PromiseWrapper} from 'angular2/src/core/facade/async';
import {Metric} from '../metric'; import {Metric} from '../metric';
export class MultiMetric extends Metric { export class MultiMetric extends Metric {
static createBindings(childTokens): Binding[] { static createBindings(childTokens: any[]): Binding[] {
return [ return [
bind(_CHILDREN) bind(_CHILDREN)
.toFactory( .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)),
(injector: Injector) => ListWrapper.map(childTokens, (token) => injector.get(token)), [Injector]),
[Injector]),
bind(MultiMetric).toFactory(children => new MultiMetric(children), [_CHILDREN]) bind(MultiMetric).toFactory(children => new MultiMetric(children), [_CHILDREN])
]; ];
} }
@ -21,7 +20,7 @@ export class MultiMetric extends Metric {
* Starts measuring * Starts measuring
*/ */
beginMeasure(): Promise<any> { beginMeasure(): Promise<any> {
return PromiseWrapper.all(ListWrapper.map(this._metrics, (metric) => metric.beginMeasure())); return PromiseWrapper.all(this._metrics.map(metric => metric.beginMeasure()));
} }
/** /**
@ -30,9 +29,8 @@ export class MultiMetric extends Metric {
* @param restart: Whether to restart right after this. * @param restart: Whether to restart right after this.
*/ */
endMeasure(restart: boolean): Promise<{[key: string]: any}> { endMeasure(restart: boolean): Promise<{[key: string]: any}> {
return PromiseWrapper.all( return PromiseWrapper.all(this._metrics.map(metric => metric.endMeasure(restart)))
ListWrapper.map(this._metrics, (metric) => metric.endMeasure(restart))) .then(values => mergeStringMaps(values));
.then((values) => { return mergeStringMaps(values); });
} }
/** /**

View File

@ -61,7 +61,7 @@ export class ConsoleReporter extends Reporter {
} }
reportMeasureValues(measureValues: MeasureValues): Promise<any> { reportMeasureValues(measureValues: MeasureValues): Promise<any> {
var formattedValues = ListWrapper.map(this._metricNames, (metricName) => { var formattedValues = this._metricNames.map(metricName => {
var value = measureValues.values[metricName]; var value = measureValues.values[metricName];
return ConsoleReporter._formatNum(value); return ConsoleReporter._formatNum(value);
}); });
@ -69,13 +69,12 @@ export class ConsoleReporter extends Reporter {
return PromiseWrapper.resolve(null); return PromiseWrapper.resolve(null);
} }
reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<any> { reportSample(completeSample: MeasureValues[], validSamples: MeasureValues[]): Promise<any> {
this._printStringRow(this._metricNames.map((_) => ''), '='); this._printStringRow(this._metricNames.map((_) => ''), '=');
this._printStringRow(ListWrapper.map(this._metricNames, (metricName) => { this._printStringRow(this._metricNames.map(metricName => {
var sample = var samples = validSamples.map(measureValues => measureValues.values[metricName]);
ListWrapper.map(validSample, (measureValues) => measureValues.values[metricName]); var mean = Statistic.calculateMean(samples);
var mean = Statistic.calculateMean(sample); var cv = Statistic.calculateCoefficientOfVariation(samples, mean);
var cv = Statistic.calculateCoefficientOfVariation(sample, mean);
var formattedMean = ConsoleReporter._formatNum(mean) var formattedMean = ConsoleReporter._formatNum(mean)
// Note: Don't use the unicode character for +- as it might cause // Note: Don't use the unicode character for +- as it might cause
// hickups for consoles... // hickups for consoles...
@ -87,10 +86,8 @@ export class ConsoleReporter extends Reporter {
} }
_printStringRow(parts, fill = ' ') { _printStringRow(parts, fill = ' ') {
this._print(ListWrapper.map(parts, (part) => { this._print(
var w = this._columnWidth; parts.map(part => ConsoleReporter._lpad(part, this._columnWidth, fill)).join(' | '));
return ConsoleReporter._lpad(part, w, fill);
}).join(' | '));
} }
} }

View File

@ -9,9 +9,8 @@ export class MultiReporter extends Reporter {
static createBindings(childTokens: any[]): Binding[] { static createBindings(childTokens: any[]): Binding[] {
return [ return [
bind(_CHILDREN) bind(_CHILDREN)
.toFactory( .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)),
(injector: Injector) => ListWrapper.map(childTokens, (token) => injector.get(token)), [Injector]),
[Injector]),
bind(MultiReporter).toFactory(children => new MultiReporter(children), [_CHILDREN]) bind(MultiReporter).toFactory(children => new MultiReporter(children), [_CHILDREN])
]; ];
} }
@ -25,12 +24,12 @@ export class MultiReporter extends Reporter {
reportMeasureValues(values: MeasureValues): Promise<any[]> { reportMeasureValues(values: MeasureValues): Promise<any[]> {
return PromiseWrapper.all( return PromiseWrapper.all(
ListWrapper.map(this._reporters, (reporter) => reporter.reportMeasureValues(values))); this._reporters.map(reporter => reporter.reportMeasureValues(values)));
} }
reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<any[]> { reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<any[]> {
return PromiseWrapper.all(ListWrapper.map( return PromiseWrapper.all(
this._reporters, (reporter) => reporter.reportSample(completeSample, validSample))); this._reporters.map(reporter => reporter.reportSample(completeSample, validSample)));
} }
} }

View File

@ -13,12 +13,11 @@ import {Options} from './common_options';
* Needs one implementation for every supported Browser. * Needs one implementation for every supported Browser.
*/ */
export abstract class WebDriverExtension { export abstract class WebDriverExtension {
static bindTo(childTokens): Binding[] { static bindTo(childTokens: any[]): Binding[] {
var res = [ var res = [
bind(_CHILDREN) bind(_CHILDREN)
.toFactory( .toFactory((injector: Injector) => childTokens.map(token => injector.get(token)),
(injector: Injector) => ListWrapper.map(childTokens, (token) => injector.get(token)), [Injector]),
[Injector]),
bind(WebDriverExtension) bind(WebDriverExtension)
.toFactory( .toFactory(
(children, capabilities) => { (children, capabilities) => {

View File

@ -19,7 +19,7 @@ import {Metric, MultiMetric, bind, Injector} from 'benchpress/common';
export function main() { export function main() {
function createMetric(ids) { function createMetric(ids) {
var m = Injector.resolveAndCreate([ var m = Injector.resolveAndCreate([
ListWrapper.map(ids, (id) => bind(id).toValue(new MockMetric(id))), ids.map(id => bind(id).toValue(new MockMetric(id))),
MultiMetric.createBindings(ids) MultiMetric.createBindings(ids)
]) ])
.get(MultiMetric); .get(MultiMetric);

View File

@ -20,7 +20,7 @@ import {Reporter, MultiReporter, bind, Injector, MeasureValues} from 'benchpress
export function main() { export function main() {
function createReporters(ids) { function createReporters(ids) {
var r = Injector.resolveAndCreate([ var r = Injector.resolveAndCreate([
ListWrapper.map(ids, (id) => bind(id).toValue(new MockReporter(id))), ids.map(id => bind(id).toValue(new MockReporter(id))),
MultiReporter.createBindings(ids) MultiReporter.createBindings(ids)
]) ])
.get(MultiReporter); .get(MultiReporter);

View File

@ -21,7 +21,7 @@ export function main() {
function createExtension(ids, caps) { function createExtension(ids, caps) {
return PromiseWrapper.wrap(() => { return PromiseWrapper.wrap(() => {
return Injector.resolveAndCreate([ return Injector.resolveAndCreate([
ListWrapper.map(ids, (id) => bind(id).toValue(new MockExtension(id))), ids.map(id => bind(id).toValue(new MockExtension(id))),
bind(Options.CAPABILITIES).toValue(caps), bind(Options.CAPABILITIES).toValue(caps),
WebDriverExtension.bindTo(ids) WebDriverExtension.bindTo(ids)
]) ])

View File

@ -9,10 +9,15 @@ import {
RouteParams RouteParams
} from 'angular2/router'; } from 'angular2/router';
import * as db from './data'; import * as db from './data';
import {ObservableWrapper, PromiseWrapper} from 'angular2/src/core/facade/async'; import {ObservableWrapper, PromiseWrapper, Promise} from 'angular2/src/core/facade/async';
import {ListWrapper} from 'angular2/src/core/facade/collection'; import {ListWrapper} from 'angular2/src/core/facade/collection';
import {isPresent} from 'angular2/src/core/facade/lang'; import {isPresent} from 'angular2/src/core/facade/lang';
interface RecordData {
id: string, subject: string, content: string, email: string, firstName: string, lastName: string,
date: string, draft?: boolean
}
class InboxRecord { class InboxRecord {
id: string = ''; id: string = '';
subject: string = ''; subject: string = '';
@ -23,29 +28,13 @@ class InboxRecord {
date: string = ''; date: string = '';
draft: boolean = false; draft: boolean = false;
constructor(data: { constructor(data: RecordData = null) {
id: string,
subject: string,
content: string,
email: string,
firstName: string,
lastName: string,
date: string, draft?: boolean
} = null) {
if (isPresent(data)) { if (isPresent(data)) {
this.setData(data); this.setData(data);
} }
} }
setData(record: { setData(record: RecordData) {
id: string,
subject: string,
content: string,
email: string,
firstName: string,
lastName: string,
date: string, draft?: boolean
}) {
this.id = record['id']; this.id = record['id'];
this.subject = record['subject']; this.subject = record['subject'];
this.content = record['content']; this.content = record['content'];
@ -53,32 +42,32 @@ class InboxRecord {
this.firstName = record['first-name']; this.firstName = record['first-name'];
this.lastName = record['last-name']; this.lastName = record['last-name'];
this.date = record['date']; this.date = record['date'];
this.draft = record['draft'] == true ? true : false; this.draft = record['draft'] == true;
} }
} }
@Injectable() @Injectable()
class DbService { class DbService {
getData() { getData(): Promise<RecordData[]> {
var p = PromiseWrapper.completer(); var p = PromiseWrapper.completer();
p.resolve(db.data); p.resolve(db.data);
return p.promise; return p.promise;
} }
drafts() { drafts(): Promise<RecordData[]> {
return PromiseWrapper.then(this.getData(), (data) => { return PromiseWrapper.then(this.getData(), (data) => {
return ListWrapper.filter(data, return ListWrapper.filter(data,
(record => isPresent(record['draft']) && record['draft'] == true)); (record => isPresent(record['draft']) && record['draft'] == true));
}); });
} }
emails() { emails(): Promise<RecordData[]> {
return PromiseWrapper.then(this.getData(), (data) => { return PromiseWrapper.then(this.getData(), (data) => {
return ListWrapper.filter(data, (record => !isPresent(record['draft']))); return ListWrapper.filter(data, (record => !isPresent(record['draft'])));
}); });
} }
email(id) { email(id): Promise<RecordData> {
return PromiseWrapper.then(this.getData(), (data) => { return PromiseWrapper.then(this.getData(), (data) => {
for (var i = 0; i < data.length; i++) { for (var i = 0; i < data.length; i++) {
var entry = data[i]; var entry = data[i];
@ -109,9 +98,9 @@ class InboxCmp {
ready: boolean = false; ready: boolean = false;
constructor(public router: Router, db: DbService) { constructor(public router: Router, db: DbService) {
PromiseWrapper.then(db.emails(), (emails) => { PromiseWrapper.then(db.emails(), emails => {
this.ready = true; this.ready = true;
this.items = ListWrapper.map(emails, (email) => { return new InboxRecord(email); }); this.items = emails.map(data => new InboxRecord(data));
}); });
} }
} }
@ -126,7 +115,7 @@ class DraftsCmp {
constructor(public router: Router, db: DbService) { constructor(public router: Router, db: DbService) {
PromiseWrapper.then(db.drafts(), (drafts) => { PromiseWrapper.then(db.drafts(), (drafts) => {
this.ready = true; this.ready = true;
this.items = ListWrapper.map(drafts, (email) => { return new InboxRecord(email); }); this.items = drafts.map(data => new InboxRecord(data));
}); });
} }
} }