deepCopier.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { StringTools } from './stringTools';
  2. var cloneValue = (source: any, destinationObject: any) => {
  3. if (!source) {
  4. return null;
  5. }
  6. if (source.getClassName && source.getClassName() === "Mesh") {
  7. return null;
  8. }
  9. if (source.getClassName && source.getClassName() === "SubMesh") {
  10. return source.clone(destinationObject);
  11. } else if (source.clone) {
  12. return source.clone();
  13. }
  14. return null;
  15. };
  16. /**
  17. * Class containing a set of static utilities functions for deep copy.
  18. */
  19. export class DeepCopier {
  20. /**
  21. * Tries to copy an object by duplicating every property
  22. * @param source defines the source object
  23. * @param destination defines the target object
  24. * @param doNotCopyList defines a list of properties to avoid
  25. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  26. */
  27. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  28. for (var prop in source) {
  29. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  30. continue;
  31. }
  32. if (StringTools.EndsWith(prop, "Observable")) {
  33. continue;
  34. }
  35. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  36. continue;
  37. }
  38. var sourceValue = source[prop];
  39. var typeOfSourceValue = typeof sourceValue;
  40. if (typeOfSourceValue === "function") {
  41. continue;
  42. }
  43. try {
  44. if (typeOfSourceValue === "object") {
  45. if (sourceValue instanceof Array) {
  46. destination[prop] = [];
  47. if (sourceValue.length > 0) {
  48. if (typeof sourceValue[0] == "object") {
  49. for (var index = 0; index < sourceValue.length; index++) {
  50. var clonedValue = cloneValue(sourceValue[index], destination);
  51. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  52. destination[prop].push(clonedValue);
  53. }
  54. }
  55. } else {
  56. destination[prop] = sourceValue.slice(0);
  57. }
  58. }
  59. } else {
  60. destination[prop] = cloneValue(sourceValue, destination);
  61. }
  62. } else {
  63. destination[prop] = sourceValue;
  64. }
  65. }
  66. catch (e) {
  67. // Just ignore error (it could be because of a read-only property)
  68. }
  69. }
  70. }
  71. }