array copy

Benchmark created on


Setup

const testValue = {
  description: { gm: "", value: "" },
  rules: [],
  slug: null,
  _migration: { version: null, lastMigration: null },
  traits: {
    otherTags: [
      "value",
      "value",
      "value",
      "value",
      "value",
      "value",
      "value",
      "value",
      "value",
    ],
    value: [],
  },
  publication: { title: "", authors: "", license: "OGL", remaster: false },
  group: null,
  duration: { value: -1, unit: "unlimited", expiry: null },
  value: { isValued: false, value: 0 },
  references: [
    { children: [], overrides: [], overriddenBy: [] },
    { children: [], overrides: [], overriddenBy: [] },
    { children: [], overrides: [], overriddenBy: [] },
    { children: [], overrides: [], overriddenBy: [] },
  ],
  overrides: [],
}

function deepClone(original, { strict = false, _d = 0 } = {}) {
  if (_d > 100) {
    throw new Error(
      "Maximum depth exceeded. Be sure your object does not contain cyclical data structures.",
    )
  }
  _d++

  // Simple types
  if (typeof original !== "object" || original === null) return original

  // Arrays
  if (original instanceof Array)
    return original.map((o) => deepClone(o, { strict, _d }))

  // Dates
  if (original instanceof Date) return new Date(original)

  // Unsupported advanced objects
  if (original.constructor && original.constructor !== Object) {
    if (strict) throw new Error("deepClone cannot clone advanced objects")
    return original
  }

  // Other objects
  const clone = {}
  for (let k of Object.keys(original)) {
    clone[k] = deepClone(original[k], { strict, _d })
  }
  return clone
}

function deepCloneProposal(original, { strict = false, _d = 0 } = {}) {
  return _deepCloneProposal(original, strict, _d)
}

function _deepCloneProposal(original, strict, _d) {
  if (_d > 100) {
    throw new Error(
      "Maximum depth exceeded. Be sure your object does not contain cyclical data structures.",
    )
  }
  _d++

  // Simple types
  if (typeof original !== "object" || original === null) return original

  // Arrays
  if (original instanceof Array)
    return original.map((o) => _deepCloneProposal(o, strict, _d))

  // Dates
  if (original instanceof Date) return new Date(original)

  // Unsupported advanced objects
  if (original.constructor && original.constructor !== Object) {
    if (strict) throw new Error("deepClone cannot clone advanced objects")
    return original
  }

  // Other objects
  const clone = {}
  for (let k of Object.keys(original)) {
    clone[k] = _deepCloneProposal(original[k], strict, _d)
  }
  return clone
}

Test runner

Ready to run.

Testing in
TestOps/sec
Original Foundry deepClone
deepClone(testValue)
ready
Proposal
deepCloneProposal(testValue)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.