Skip to content
SDETRole
SDETRole

Deep clone test data

intermediate Objects Challenge 10 of 18

Write deepClone(value) so each test can start from its own copy of a shared fixture, with no state leaking between tests.

Requirements

  • Copy plain objects and arrays at every level of nesting. The copy must share no object or array with the original.
  • Copy Date instances as new Date objects with the same time.
  • Return primitives, null and functions unchanged (functions by reference).
  • An array clones to an array, not to an object with numeric keys.
  • Do not use JSON.stringify/JSON.parse, which would break Dates and functions.

Expected output

const copy = deepClone({ user: { roles: ['admin'] }, created: new Date(0) }); copy.user.roles.push('qa') leaves the original untouched; copy.created is a new Date with the same time

Test cases (5)

  • ○copies nested objects and arrays
  • ○mutating the copy leaves the original untouched
  • ○clones Dates as Dates
  • ○keeps functions by reference
  • ○handles arrays at the top level and primitives
solution.jsExecutes in your browser

Ctrl/⌘ + Enter to run tests · your code is saved in this browser

Results

Run the tests to see results here.

Type to search across SDETRole.

Full-text search by Pagefind · runs in your browser Open search page →