mgm
Version:
My generic modules
37 lines (33 loc) • 1.28 kB
JavaScript
const moment = require('moment');
const BaseEntity = require('../model/BaseEntity');
module.exports = class Tools {
static formatDate(date, pattern = 'YYYY-MM-DD HH:mm:ss.SSS') {
return moment(date).format(pattern);
}
static clone(object, clazz) {
let dest = new clazz();
let source = JSON.parse(JSON.stringify(object));
Tools.copyValues(dest, source);
return dest;
}
static copyValues(dest, source) {
Object.keys(source).forEach(key => {
if (dest[key] instanceof BaseEntity) {
let newInstance = new dest[key].constructor();
Tools.copyValues(newInstance, source[key]);
dest[key] = newInstance;
} else if (dest[key] instanceof Array) {
source[key].forEach((value) => {
let newInstance = Tools.newInstance(key.replace(/list/, ''));
Tools.copyValues(newInstance, value);
dest[key].push(newInstance);
});
} else {
dest[key] = source[key];
}
});
}
static newInstance(className) {
return new Function('return new ' + className + '();')();
}
};