#21. Добавление json парсеров (#27)

This commit is contained in:
Nikolay
2020-12-28 00:27:08 +03:00
committed by GitHub
parent 94f3b5452a
commit fbe6f9d286
3 changed files with 44 additions and 0 deletions

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

View 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;
}
};

View File

@ -0,0 +1,3 @@
export const jsonStringify = <T>(obj: T, space = 4): string => (
JSON.stringify(obj, null, space)
);