Skip to content

Commit

Permalink
chore: copy method to Json Class
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Sep 1, 2021
1 parent 18118da commit bb129dd
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 2 deletions.
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ yarn add @secjs/utils

### Json

> Use Json to parse json without errors and more.
> Use Json to parse json without errors, deep copy and more.
```js
import { Json } from '@secjs/utils'
Expand All @@ -52,6 +52,22 @@ json.getJson(textWithJsons) // ['{"text":"hello"}', '{"hello":"world"}']
const text = 'a string that is not a valid JSON'

json.parse(text) // null


const object = {
test: 'hello',
hello: () => 'hy',
}

const objectCopy = json.copy(object)

objectCopy.test = 'hello from copy'
objectCopy.hello = () => 'hy from copy'

console.log(object.test) // hello
console.log(object.hello()) // hy
console.log(objectCopy.test) // hello from copy
console.log(objectCopy.hello()) // hy from copy
```

---
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": "@secjs/utils",
"version": "1.3.3",
"version": "1.3.4",
"description": "",
"scripts": {
"build": "tsc",
Expand Down
18 changes: 18 additions & 0 deletions src/Classes/Json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,24 @@ export class Json {
return !results.includes(false)
}

/**
* Deep copy any object properties without reference
*
* @param object The object to be copied
* @return A copy from object without any reference
*/
copy<T>(object: T): T {
const copy: any = {}

for (const i in object) {
const item = object[i]
copy[i] =
item != null && typeof item === 'object' ? this.copy(item) : item
}

return copy
}

/**
* Find all JSON's inside string and return it.
* @param text A valid string with one or more JSON's inside.
Expand Down
17 changes: 17 additions & 0 deletions tests/Classes/json.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,23 @@ describe('\n Json Class', () => {
expect(json.isArrayOfObjects([1, 2, 3])).toBe(false)
})

it('should return a deep copy from the object', async () => {
const object = {
test: 'hello',
hello: () => 'hy',
}

const objectCopy = json.copy(object)

objectCopy.test = 'hello from copy'
objectCopy.hello = () => 'hy from copy'

expect(object.test).toBe('hello')
expect(object.hello()).toBe('hy')
expect(objectCopy.test).toBe('hello from copy')
expect(objectCopy.hello()).toBe('hy from copy')
})

it('should return all json found inside of the string', () => {
const text =
'this is a string with a json inside of it {"text":"hello"} and one more json {"hello":"world"}'
Expand Down

0 comments on commit bb129dd

Please sign in to comment.