From 2a777921656f2e960908716845ff0c666ab08f10 Mon Sep 17 00:00:00 2001 From: Jeff Avallone Date: Sun, 6 Jan 2019 16:54:24 -0500 Subject: [PATCH] Splitting locale matching into separate file to facilitate testing --- src/components/LocaleSwitcher/index.js | 15 +-------------- .../LocaleSwitcher/locale-to-available.js | 15 +++++++++++++++ .../LocaleSwitcher/locale-to-available.test.js | 18 ++++++++++++++++++ 3 files changed, 34 insertions(+), 14 deletions(-) create mode 100644 src/components/LocaleSwitcher/locale-to-available.js create mode 100644 src/components/LocaleSwitcher/locale-to-available.test.js diff --git a/src/components/LocaleSwitcher/index.js b/src/components/LocaleSwitcher/index.js index 18e7e21..76fd8cf 100644 --- a/src/components/LocaleSwitcher/index.js +++ b/src/components/LocaleSwitcher/index.js @@ -5,22 +5,9 @@ import ExpandIcon from 'react-feather/dist/icons/chevrons-down'; import i18n, { locales } from 'i18n'; +import localeToAvailable from './locale-to-available'; import style from './style.module.css'; -const localeToAvailable = (locale, available, defaultLocale) => { - if (available.includes(locale)) { - return locale; - } - - const parts = locale.split('-'); - - if (parts.length > 0 && available.includes(parts[0])) { - return parts[0]; - } - - return defaultLocale; -}; - export class LocaleSwitcher extends React.PureComponent { state = { current: localeToAvailable( diff --git a/src/components/LocaleSwitcher/locale-to-available.js b/src/components/LocaleSwitcher/locale-to-available.js new file mode 100644 index 0000000..3dba9bd --- /dev/null +++ b/src/components/LocaleSwitcher/locale-to-available.js @@ -0,0 +1,15 @@ +const localeToAvailable = (locale, available, defaultLocale) => { + if (available.includes(locale)) { + return locale; + } + + const parts = locale.split('-'); + + if (parts.length > 0 && available.includes(parts[0])) { + return parts[0]; + } + + return defaultLocale; +}; + +export default localeToAvailable; diff --git a/src/components/LocaleSwitcher/locale-to-available.test.js b/src/components/LocaleSwitcher/locale-to-available.test.js new file mode 100644 index 0000000..8b98112 --- /dev/null +++ b/src/components/LocaleSwitcher/locale-to-available.test.js @@ -0,0 +1,18 @@ +import localeToAvailable from './locale-to-available'; + +describe('localeToAvailable', () => { + test('when requested language and region are available', () => { + expect(localeToAvailable('en-US', ['en', 'en-US', 'other'], 'other')) + .toEqual('en-US'); + }); + + test('when only requested language is available', () => { + expect(localeToAvailable('en-US', ['en', 'en-GB', 'other'], 'other')) + .toEqual('en'); + }); + + test('when language is unavailable', () => { + expect(localeToAvailable('en-US', ['tlh', 'other'], 'other')) + .toEqual('other'); + }); +});