/** * 对象工具。简化常见的对象检查,转换操作。 * * author: Sand * since: 12/15/2016 */ "use strict"; class ObjectUtil { constructor() { } /** * 检查对象是否为JSON。 * * @see http://stackoverflow.com/questions/11182924/how-to-check-if-javascript-object-is-json * * @param value */ static isJsonObject(value) { return {}.constructor === value.constructor; }; /** * 克隆一个对象。 */ static cloneObject(obj){ var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = ObjectUtil.cloneObject(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = ObjectUtil.cloneObject(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } /** * 检查对象是否具有指定的属性列表。 * * @param arguments 可变参数列表 * @returns {{pass: boolean, message: string}} */ static fieldsCheck() { var ret = {pass: false, message: ''}; if (arguments.length <= 1) { ret.message = 'Function arguments not enough.'; return ret; } var obj = arguments[0]; if (!this.isJsonObject(obj)) { ret.message = 'Function first argument must be a dict.'; return ret; } ret.pass = true; ret.message = 'Missing field(s): '; for (var i = 1; i < arguments.length; ++i) { if (!obj.hasOwnProperty(arguments[i])) { ret.pass = false; ret.message += arguments[i]; if (i !== arguments.length - 1) { ret.message += ", "; } } } if (ret.pass) ret.message = null; return ret; }; static timestampToLong(tm) { return Date.parse(new Date(tm)); }; } module.exports = ObjectUtil;