Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix clone deep to not throw err for non obj #15

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To keep consistency with lodash
we should add: if (obj instanceof Function) return {}

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)
}
})
})