Skip to content

Commit

Permalink
reafactor: better typings and format
Browse files Browse the repository at this point in the history
  • Loading branch information
maryiabydanova committed Dec 5, 2021
1 parent 09421df commit f66674c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 22 deletions.
36 changes: 17 additions & 19 deletions packages/xlsx-import/src/mappers/jsonMapper.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
type JsonMapperSignature<TDefaultResult> = <TJsonResult>(value: string) => TJsonResult | TDefaultResult;

type callSignature = <TJsonResult, TDefaultResult>(value: string) => TJsonResult | TDefaultResult;

type JsonMapper = {
default: <TDefaultResult>(defaultResult: TDefaultResult) => JsonMapper
} & callSignature;
export type JsonMapper<TJsonResult> = JsonMapperSignature<TJsonResult> & {
default: <TDefaultResult>(value: TDefaultResult) => JsonMapper<TDefaultResult>;
};

interface IJsonMapperOptions {
default: any;
interface IJsonMapperOptions<TDefaultResult> {
default: TDefaultResult;
}

const factory = (options: Readonly<IJsonMapperOptions>): JsonMapper => {
const mapper = (json: string) => {
const factory = <TDefaultResult>(options: Readonly<IJsonMapperOptions<TDefaultResult>>): JsonMapper<TDefaultResult> => {
const mapper: JsonMapper<TDefaultResult> = <TJsonResult>(json: string): TJsonResult | TDefaultResult => {
try {
return JSON.parse(json);
} catch (e) {
return options.default
return options.default;
}
}
};

mapper.default = <TDefaultResult>(defaultResult: TDefaultResult) => factory({
...options,
default: defaultResult
});
mapper.default = <TJSonResult>(defaultResult: TJSonResult) =>
factory<TJSonResult>({
...options,
default: defaultResult,
});

return mapper;
};



export const jsonMapper: JsonMapper = factory({
export const jsonMapper = factory({
default: null,
});
});
6 changes: 3 additions & 3 deletions packages/xlsx-import/tests/unit/mappers/jsonMapper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ describe('UNIT TEST: src/mappers/', () => {
});

it('Should return default value on error', () => {
const mapper = jsonMapper.default({a: 1});
chai.expect(mapper('invalid')).eql({a: 1});
})
const mapper = jsonMapper.default({ a: 1 });
chai.expect(mapper('invalid')).eql({ a: 1 });
});
});
});

0 comments on commit f66674c

Please sign in to comment.