Skip to content

Commit

Permalink
🧑‍💻 Add deepCloneJson helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
richardfrost committed Aug 14, 2024
1 parent e3c6d66 commit 22c3c0a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/script/lib/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export function booleanToNumber(value: boolean): number {
return value ? Constants.TRUE : Constants.FALSE;
}

export function deepCloneJson(object) {
return JSON.parse(JSON.stringify(object));
}

/* istanbul ignore next */
export function dynamicList(list: string[], select: HTMLSelectElement, upperCaseFirstChar: boolean = false, title?: string) {
removeChildren(select);
Expand Down
45 changes: 45 additions & 0 deletions test/spec/lib/helper.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect } from 'chai';
import Constants from '@APF/lib/constants';
import {
booleanToNumber,
deepCloneJson,
formatNumber,
getParent,
getVersion,
Expand Down Expand Up @@ -33,6 +34,50 @@ describe('Helper', function() {
});
});

describe('deepJsonClone()', function() {
const deepObject = {
children: {
deep: false,
name: 'shallow',
shallow: true,
},
deep: true,
name: 'deep',
numbers: [1, 2],
shallow: false,
strings: ['one', 'two'],
};

const shallowObject = {
deep: false,
name: 'shallow',
shallow: true,
};

it('Shallow clones object', function() {
expect(JSON.stringify(deepCloneJson(shallowObject))).to.eql(JSON.stringify(shallowObject));
});

it('Deep clones object', function() {
expect(JSON.stringify(deepCloneJson(deepObject))).to.eql(JSON.stringify(deepObject));
});

it('Is a clone (delete)', function() {
const clone = deepCloneJson(deepObject);
delete clone.name;
expect(clone.name).to.be.undefined;
expect(deepObject.name).to.not.be.undefined;
});

it('Is a clone (update)', function() {
const clone = deepCloneJson(deepObject);
const key = 'name2';
clone[key] = 'deep2';
expect(clone[key]).to.not.be.undefined;
expect(deepObject[key]).to.be.undefined;
});
});

describe('formatNumber()', function() {
it('Format numbers for counter display', function() {
expect(formatNumber(999)).to.eql('999');
Expand Down

0 comments on commit 22c3c0a

Please sign in to comment.