object.util.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * 对象工具。简化常见的对象检查,转换操作。
  3. *
  4. * author: Sand
  5. * since: 12/15/2016
  6. */
  7. "use strict";
  8. class ObjectUtil {
  9. constructor() {
  10. }
  11. /**
  12. * 检查对象是否为JSON。
  13. *
  14. * @see http://stackoverflow.com/questions/11182924/how-to-check-if-javascript-object-is-json
  15. *
  16. * @param value
  17. */
  18. static isJsonObject(value) {
  19. return {}.constructor === value.constructor;
  20. };
  21. /**
  22. * 克隆一个对象。
  23. */
  24. static cloneObject(obj){
  25. var copy;
  26. // Handle the 3 simple types, and null or undefined
  27. if (null == obj || "object" != typeof obj) return obj;
  28. // Handle Date
  29. if (obj instanceof Date) {
  30. copy = new Date();
  31. copy.setTime(obj.getTime());
  32. return copy;
  33. }
  34. // Handle Array
  35. if (obj instanceof Array) {
  36. copy = [];
  37. for (var i = 0, len = obj.length; i < len; i++) {
  38. copy[i] = ObjectUtil.cloneObject(obj[i]);
  39. }
  40. return copy;
  41. }
  42. // Handle Object
  43. if (obj instanceof Object) {
  44. copy = {};
  45. for (var attr in obj) {
  46. if (obj.hasOwnProperty(attr)) copy[attr] = ObjectUtil.cloneObject(obj[attr]);
  47. }
  48. return copy;
  49. }
  50. throw new Error("Unable to copy obj! Its type isn't supported.");
  51. }
  52. /**
  53. * 检查对象是否具有指定的属性列表。
  54. *
  55. * @param arguments 可变参数列表
  56. * @returns {{pass: boolean, message: string}}
  57. */
  58. static fieldsCheck() {
  59. var ret = {pass: false, message: ''};
  60. if (arguments.length <= 1) {
  61. ret.message = 'Function arguments not enough.';
  62. return ret;
  63. }
  64. var obj = arguments[0];
  65. if (!this.isJsonObject(obj)) {
  66. ret.message = 'Function first argument must be a dict.';
  67. return ret;
  68. }
  69. ret.pass = true;
  70. ret.message = 'Missing field(s): ';
  71. for (var i = 1; i < arguments.length; ++i) {
  72. if (!obj.hasOwnProperty(arguments[i])) {
  73. ret.pass = false;
  74. ret.message += arguments[i];
  75. if (i !== arguments.length - 1) {
  76. ret.message += ", ";
  77. }
  78. }
  79. }
  80. if (ret.pass) ret.message = null;
  81. return ret;
  82. };
  83. static timestampToLong(tm) {
  84. return Date.parse(new Date(tm));
  85. };
  86. }
  87. module.exports = ObjectUtil;