Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add custom convertCurrency function #53

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ $ yarn add react-currency-hooks
import { useCurrency } from 'react-currency-hooks';
```

<!-- TODO update docs -->

#### Params

| Name | Type | Default | Description |
Expand Down
30 changes: 17 additions & 13 deletions __tests__/useCurrency.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { renderHook } from '@testing-library/react-hooks';

import { useCurrency } from '../src';

// TODO test different amount
// TODO test root options
describe('useCurrency', () => {
const rates = {
GBP: 0.92,
Expand All @@ -18,9 +20,9 @@ describe('useCurrency', () => {
rates,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toBe(192.85714285714286);
expect(result.current(200, options)).toBe(192.85714285714286);
});

it('should return 2 `to` values', () => {
Expand All @@ -31,9 +33,9 @@ describe('useCurrency', () => {
rates,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toMatchObject({
expect(result.current(200, options)).toMatchObject({
chf: 192.85714285714286,
gbp: 164.28571428571428,
});
Expand All @@ -48,9 +50,9 @@ describe('useCurrency', () => {
keepPrecision: false,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toBe(192.86);
expect(result.current(200, options)).toBe(192.86);
});

it('should return single `to` value from hook with the same `base` and `from` rates', () => {
Expand All @@ -61,9 +63,9 @@ describe('useCurrency', () => {
rates,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toBe(216);
expect(result.current(200, options)).toBe(216);
});

it('should return single `to` value from hook with the same `base` and `to` rates', () => {
Expand All @@ -74,9 +76,9 @@ describe('useCurrency', () => {
rates,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toBe(178.57142857142856);
expect(result.current(200, options)).toBe(178.57142857142856);
});

it('should return single `to` value from hook without `base` rate', () => {
Expand All @@ -87,9 +89,9 @@ describe('useCurrency', () => {
rates,
};

const { result } = renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

expect(result.current).toBe(192.85714285714286);
expect(result.current(200, options)).toBe(192.85714285714286);
});

it('should return an error', () => {
Expand All @@ -101,7 +103,9 @@ describe('useCurrency', () => {
rates,
};

renderHook(() => useCurrency(200, options));
const { result } = renderHook(() => useCurrency());

result.current(200, options);
} catch (err) {
expect(err.message).toBe(
'`rates` object does not contain either `from` or `to` currency!'
Expand Down
2 changes: 1 addition & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ export default {
},
],
plugins: [resolve(), typescript(), terser()],
external: Object.keys(pkg.peerDependencies),
external: Object.keys(pkg.peerDependencies || {}), // TODO add fallback for dependencies
};
91 changes: 47 additions & 44 deletions src/useCurrency.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,66 @@
import { useState, useEffect, useCallback } from 'react';
import { useCallback } from 'react';

import { hasKey } from './helpers/hasKey';

import { Options } from './interfaces/Options';

import type { Rates } from './types/rates';

export const useCurrency = (amount: number, options: Options) => {
const { from, to, base, rates, keepPrecision = true } = options;
type ConvertCurrencyCallback = (
amount: number,
options?: Options
) => number | Record<string, number> | undefined;

const [conversion, setConversion] = useState<number | Rates | undefined>(
to instanceof Array ? {} : undefined
);
export const useCurrency = (rootOptions?: Options) => {
return useCallback<ConvertCurrencyCallback>(
(amount, options) => {
const { from, to, base, rates, keepPrecision = true } = {
...rootOptions,
...options,
};

const getRate = useCallback(
(to: string) => {
if (from === base && hasKey(rates, to)) {
return rates[to];
}
const getRate = (to: string) => {
if (from === base && hasKey(rates, to)) {
return rates[to];
}

if (to === base && hasKey(rates, from)) {
return 1 / rates[from];
}
if (to === base && hasKey(rates, from)) {
return 1 / rates[from];
}

if (hasKey(rates, from) && hasKey(rates, to)) {
return rates[to] * (1 / rates[from]);
}
if (hasKey(rates, from) && hasKey(rates, to)) {
return rates[to] * (1 / rates[from]);
}

throw new Error(
'`rates` object does not contain either `from` or `to` currency!'
);
},
[base, from, rates]
);
throw new Error(
'`rates` object does not contain either `from` or `to` currency!'
);
};

const convert = useCallback(
(to: string) => {
const convertedValue = amount * 100 * getRate(to);
// TODO rename function
const convert = (to: string) => {
const convertedValue = amount * 100 * getRate(to);

return (
(keepPrecision ? convertedValue : Math.round(convertedValue)) / 100
);
},
[amount, getRate, keepPrecision]
);
return (
(keepPrecision ? convertedValue : Math.round(convertedValue)) / 100
);
};

useEffect(() => {
if (to instanceof Array) {
const converted: Rates = {};
// TODO refactor
if (to instanceof Array) {
const converted: Rates = {};

to.map((currency) => {
converted[currency.toLowerCase()] = convert(currency);
});
to.map((currency) => {
converted[currency.toLowerCase()] = convert(currency);
});

setConversion(converted);
} else if (typeof to === 'string') {
setConversion(convert(to));
}
}, [convert, to]);
return converted;
} else if (typeof to === 'string') {
return convert(to);
}

return conversion;
return undefined;
},
[rootOptions]
);
};