All files utils.js

75% Statements 18/24
76.92% Branches 10/13
50% Functions 3/6
77.27% Lines 17/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                    2x 2x 2x 2x     2x           10x 10x 10x 10x     2x 3x 3x 3x 3x     3x     1x 1x                        
// @flow
import fetch from 'unfetch';
import ls from 'local-storage';
import LANGUAGE_CODES from './json/language_codes.json';
 
type Currency = {
  format: string,
  fractional?: boolean,
};
 
export const getCurrencyFromBrowserLocale = (): string => {
  Iif (typeof window === 'undefined') return 'USD';
  const lang = window.navigator.language.toLowerCase();
  return LANGUAGE_CODES[lang] || 'USD';
};
 
export const format = (
  amount: number,
  currency: Currency,
  rounding?: number => number = Math.round
): string => {
  // eslint-disable-next-line no-restricted-properties
  const multiplier = Math.pow(10, currency.fractional === false ? 0 : 2);
  const price = rounding(amount * multiplier) / multiplier;
  const readablePrice = price.toLocaleString().replace(/(\.[\d]{1})$/, '$10');
  return currency.format.replace('#', readablePrice);
};
 
export const fetchRates = (base: string): Promise<Object> => {
  const ONE_DAY_AGO = 1000 * 60 * 60 * 24;
  const now = new Date().getTime();
  const key = `react-forex-price-${base}`;
  const { date, rates } = ls(key) || {};
 
  // return localStorage values for rates, if present
  if (date && now - date < ONE_DAY_AGO) return Promise.resolve(rates);
 
  // otherwise, fetch
  window.__REACT_FOREX_PRICE_FETCHING__ = true;
  return fetch(`https://api.fixer.io/latest?base=${base}`)
    .then(response => response.json())
    .then(data => {
      ls(key, { date: now, rates: data.rates });
      window.__REACT_FOREX_PRICE_FETCHING__ = false;
      return data.rates;
    })
    .catch(() => {
      window.__REACT_FOREX_PRICE_FETCHING__ = false;
      return {};
    });
}