31
src/core/utils/__test__/jsonParse.test.ts
Normal file
31
src/core/utils/__test__/jsonParse.test.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
import {jsonParse} from '../jsonParse';
|
||||||
|
|
||||||
|
describe('jsonParse', () => {
|
||||||
|
it('Должен вернуть значение', () => {
|
||||||
|
expect(jsonParse('{}')).toEqual({});
|
||||||
|
expect(jsonParse('null')).toBeNull();
|
||||||
|
expect(jsonParse('0')).toBe(0);
|
||||||
|
expect(jsonParse(' 1 ')).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Должен вернуть значение при наличии дефолта', () => {
|
||||||
|
expect(jsonParse('{}', {str: 9})).toEqual({});
|
||||||
|
expect(jsonParse('null', {str: 9})).toBeNull();
|
||||||
|
expect(jsonParse('0', {str: 9})).toBe(0);
|
||||||
|
expect(jsonParse(' 1 ', {str: 9})).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Должен вернуть undefined для не корректных значений', () => {
|
||||||
|
expect(jsonParse()).toBeUndefined();
|
||||||
|
expect(jsonParse('')).toBeUndefined();
|
||||||
|
expect(jsonParse(' ')).toBeUndefined();
|
||||||
|
expect(jsonParse('{"9')).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Должен вернуть дефолтное значение', () => {
|
||||||
|
expect(jsonParse(undefined, 'to')).toBe('to');
|
||||||
|
expect(jsonParse('', 'to')).toBe('to');
|
||||||
|
expect(jsonParse(' ', 'to')).toBe('to');
|
||||||
|
expect(jsonParse('./6dh', 9)).toBe(9);
|
||||||
|
});
|
||||||
|
});
|
||||||
10
src/core/utils/jsonParse.ts
Normal file
10
src/core/utils/jsonParse.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
export const jsonParse = <T>(str?: string, defaultValue?: T): Undefinable<T> => {
|
||||||
|
const trimStr = str?.trim();
|
||||||
|
try {
|
||||||
|
const parsedValue = JSON.parse(trimStr ?? '');
|
||||||
|
|
||||||
|
return parsedValue === undefined ? defaultValue : parsedValue;
|
||||||
|
} catch (e) {
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
};
|
||||||
3
src/core/utils/jsonStringify.ts
Normal file
3
src/core/utils/jsonStringify.ts
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
export const jsonStringify = <T>(obj: T, space = 4): string => (
|
||||||
|
JSON.stringify(obj, null, space)
|
||||||
|
);
|
||||||
Reference in New Issue
Block a user