deepCopier.ts 3.0 KB

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