diff --git a/CHANGELOG b/CHANGELOG index d8de468..576d9d9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,6 @@ +# 1.5.1 +- fix: cloneDeep should not throw an error when cloning non-objects + # 1.5.0 - feat: shuffle diff --git a/package.json b/package.json index 45afed0..8f5b747 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/cloneDeep.js b/src/cloneDeep.js index 08b6c68..0326bc8 100644 --- a/src/cloneDeep.js +++ b/src/cloneDeep.js @@ -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 diff --git a/test/cloneDeep.js b/test/cloneDeep.js index dc7db0a..90c0565 100644 --- a/test/cloneDeep.js +++ b/test/cloneDeep.js @@ -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', () => { @@ -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) + } + }) })