Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Last active June 19, 2019 04:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeBelt/eacb3a2b82b1b0bb4be9ce634e7f7700 to your computer and use it in GitHub Desktop.
Save codeBelt/eacb3a2b82b1b0bb4be9ce634e7f7700 to your computer and use it in GitHub Desktop.
import LocationModel from './LocationModel';
import CarModel from './CarModel';
class PersonModel {
firstName = '';
lastName = '';
age = 0;
address = null
cars = [];
/*
* firstName & lastName will be an empty string if there is no data.
* age will be zero if there is no data
* address will be a new LocationModel or null if there is no data
* cars will be an array of CarModel's or an empty array if there is no data
*/
constructor(data) {
this.firstName = data.firstName || '';
this.lastName = data.lastName || '';
this.age = isNaN(data.age) ? 0 : data.age;
this.address = data.address ? new LocationModel(data.address) : null;
this.cars = this._safelyCreateArrayData(data.cars, CarModel);
}
_safelyCreateArrayData(dataForArray, Model) {
// if dataForArray is undefined or null, return empty array
if (dataForArray == null) {
return [];
}
// if dataForArray is a valid array, create array of models
if (Array.isArray(dataForArray)) {
return dataForArray.map((model) => new Model(model))
}
// if dataForArray is a single object, create a model and return an array
return [
new Model(dataForArray)
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment