object.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. const hasOwnProperty = Object.prototype.hasOwnProperty;
  8. /** Create new object if any property in "update" changes in "source". */
  9. export function shallowMerge2<T>(source: T, update: Partial<T>): T {
  10. // Adapted from LiteMol (https://github.com/dsehnal/LiteMol)
  11. let changed = false;
  12. for (let k of Object.keys(update)) {
  13. if (!hasOwnProperty.call(update, k)) continue;
  14. if ((update as any)[k] !== (source as any)[k]) {
  15. changed = true;
  16. break;
  17. }
  18. }
  19. if (!changed) return source;
  20. return Object.assign({}, source, update);
  21. }
  22. export function shallowEqual<T>(a: T, b: T) {
  23. if (!a) {
  24. if (!b) return true;
  25. return false;
  26. }
  27. if (!b) return false;
  28. let keys = Object.keys(a);
  29. if (Object.keys(b).length !== keys.length) return false;
  30. for (let k of keys) {
  31. if (!hasOwnProperty.call(a, k) || (a as any)[k] !== (b as any)[k]) return false;
  32. }
  33. return true;
  34. }
  35. export function shallowMerge<T>(source: T, ...rest: (Partial<T> | undefined)[]): T {
  36. // Adapted from LiteMol (https://github.com/dsehnal/LiteMol)
  37. let ret: any = source;
  38. for (let s = 0; s < rest.length; s++) {
  39. if (!rest[s]) continue;
  40. ret = shallowMerge2(source, rest[s] as T);
  41. if (ret !== source) {
  42. for (let i = s + 1; i < rest.length; i++) {
  43. ret = Object.assign(ret, rest[i]);
  44. }
  45. break;
  46. }
  47. }
  48. return ret;
  49. }
  50. /** Simple deep clone for number, boolean, string, null, undefined, object, array */
  51. export function deepClone<T>(source: T): T {
  52. if (null === source || "object" !== typeof source) return source;
  53. if (source instanceof Array) {
  54. const copy: any[] = [];
  55. for (let i = 0, len = source.length; i < len; i++) {
  56. copy[i] = deepClone(source[i]);
  57. }
  58. return copy as any as T;
  59. }
  60. if (source instanceof Object) {
  61. const copy: { [k: string]: any } = {};
  62. for (let k in source) {
  63. if (hasOwnProperty.call(source, k)) copy[k] = deepClone(source[k]);
  64. }
  65. return copy as any as T;
  66. }
  67. throw new Error(`Can't clone, type "${typeof source}" unsupported`);
  68. }