Skip to content

Commit

Permalink
flags
Browse files Browse the repository at this point in the history
  • Loading branch information
eddow committed May 13, 2024
1 parent 1799bf5 commit a8404ea
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/flags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Locale } from './types'

function toEmoji(name: string) {
return String.fromCodePoint(...Array.from(name).map((k) => k.charCodeAt(0) + 127365))
}

/**
* Some language codes do not have a clear country code and should be indicated here
*
* https://emojipedia.org/flags
*/
export const flagCodeExceptions: Record<string, string> = { en: '๐Ÿ‡ฌ๐Ÿ‡ง' }

export function localeFlags(locale: Locale) {
const parts = locale
.toLowerCase()
.split('-', 3)
.slice(0, 2)
.map((code) => flagCodeExceptions[code] || toEmoji(code))
return parts[0] === parts[1] ? [parts[0]] : parts
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export {
url2specs
} from './server/index'
export { FileDB, MemDB, type MemDBDictionary, type MemDBDictionaryEntry } from './db/index'
export { localeFlags, flagCodeExceptions } from './flags'

declare global {
interface Set<T> {
Expand Down
15 changes: 14 additions & 1 deletion test/specifics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import {
Translator,
bulkDictionary,
bulkObject,
reports
reports,
localeFlags,
flagCodeExceptions
} from '../src/index'
import { localStack } from './utils'

Expand All @@ -18,6 +20,17 @@ reports.missing = ({ key }: TContext, fallback?: string) => {
return fallback ?? '[no]'
}

test('flags', async () => {
expect(localeFlags('en')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('en-GB')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('en-US-gb')).toEqual(['๐Ÿ‡ฌ๐Ÿ‡ง', '๐Ÿ‡บ๐Ÿ‡ธ'])
flagCodeExceptions.en = '๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ'
expect(localeFlags('en-GB')).toEqual(['๐Ÿด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ', '๐Ÿ‡ฌ๐Ÿ‡ง'])
expect(localeFlags('fr')).toEqual(['๐Ÿ‡ซ๐Ÿ‡ท'])
expect(localeFlags('fr-FR')).toEqual(['๐Ÿ‡ซ๐Ÿ‡ท'])
expect(localeFlags('fr-BE')).toEqual(['๐Ÿ‡ซ๐Ÿ‡ท', '๐Ÿ‡ง๐Ÿ‡ช'])
})

describe('bulk', () => {
let T: Translator, client: I18nClient
const expected = {
Expand Down

0 comments on commit a8404ea

Please sign in to comment.