Skip to content

Commit

Permalink
Merge pull request #15 from ZIMkaRU/bugfix/fix-clone-deep-to-not-thro…
Browse files Browse the repository at this point in the history
…w-err-for-non-obj

Fix clone deep to not throw err for non obj
  • Loading branch information
prdn authored Nov 20, 2023
2 parents 4ff41a5 + 9bbbde3 commit 76f61c2
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 1.5.1
- fix: cloneDeep should not throw an error when cloning non-objects

# 1.5.0
- feat: shuffle

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bitfinex/lib-js-util-base",
"version": "1.5.0",
"version": "1.5.1",
"description": "general utils",
"main": "index.js",
"scripts": {
Expand Down
13 changes: 12 additions & 1 deletion src/cloneDeep.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
'use strict'

const cloneDeep = (obj) => JSON.parse(JSON.stringify(obj))
const isObject = require('./isObject')

const cloneDeep = (obj) => {
if (obj instanceof Function) {
return {}
}
if (!isObject(obj)) {
return obj
}

return JSON.parse(JSON.stringify(obj))
}

module.exports = cloneDeep
18 changes: 17 additions & 1 deletion test/cloneDeep.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/* eslint-env mocha */

const assert = require('assert')
const { cloneDeep } = require('../index')
const { cloneDeep, isPlainObject } = require('../index')

describe('cloneDeep', () => {
it('should deep clone objects', () => {
Expand All @@ -19,4 +19,20 @@ describe('cloneDeep', () => {
assert.deepStrictEqual(obj, clone)
assert.notStrictEqual(obj, clone)
})

it('should not throw an error when cloning non-objects', () => {
const sources = [undefined, Symbol('a'), () => {}]

for (const obj of sources) {
const clone = cloneDeep(obj)

if (obj instanceof Function) {
assert.strictEqual(isPlainObject(clone), true)

return
}

assert.deepStrictEqual(obj, clone)
}
})
})

0 comments on commit 76f61c2

Please sign in to comment.