Skip to content

Instantly share code, notes, and snippets.

@cdroulers
Last active May 23, 2016 21:53
Show Gist options
  • Save cdroulers/479c966506c92ed1fac0 to your computer and use it in GitHub Desktop.
Save cdroulers/479c966506c92ed1fac0 to your computer and use it in GitHub Desktop.
BaseEntity for blog post about TypeScript and JSON.stringify (http://cdroulers.com/blog/2015/04/22/typescript-properties-and-json-stringify/)
module shared {
"use strict";
export interface IMapOptions {
Properties: { [key: string]: (x: any) => any };
Ignore?: string[];
PropertyNames?: { [key: string]: string };
}
function includeProperty(mapOptions: IMapOptions, prop: string) {
return mapOptions == null || mapOptions.Ignore == null || mapOptions.Ignore.indexOf(prop) < 0;
}
export class BaseEntity {
constructor(data?: Object, private _mapOptions?: IMapOptions) {
if (data) {
for (var prop in data) {
if (data.hasOwnProperty(prop) && typeof this[prop] !== "function") {
if (this._mapOptions && this._mapOptions.Properties && this._mapOptions.Properties[prop]) {
this[prop] = this._mapOptions.Properties[prop](data[prop]);
} else if (this._mapOptions && this._mapOptions.PropertyNames && this._mapOptions.PropertyNames[prop]) {
this[this._mapOptions.PropertyNames[prop]] = data[prop];
} else if (includeProperty(this._mapOptions, prop)) {
this[prop] = data[prop];
}
}
}
}
}
public toJSON(): any {
var result = {};
var reverseMaps = {};
if (this._mapOptions && this._mapOptions.PropertyNames) {
for (var reverseProp in this._mapOptions.PropertyNames) {
if (this._mapOptions.PropertyNames.hasOwnProperty(reverseProp)) {
reverseMaps[this._mapOptions.PropertyNames[reverseProp]] = reverseProp;
}
}
}
var options: IMapOptions = angular.extend({}, this._mapOptions);
options.Ignore = options.Ignore || [];
options.Ignore.push("_mapOptions");
for (var prop in this) {
if (this.hasOwnProperty(prop)) {
if (reverseMaps[prop]) {
result[reverseMaps[prop]] = this[prop];
} else if (includeProperty(options, prop)) {
result[prop] = this[prop];
}
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment