-
-
Save timwhitlock/5599003 to your computer and use it in GitHub Desktop.
Simple translate function requiring no external libraries. Includes plural form logic baked into closure. Feedback welcome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Example Loco JavaScript export. | |
| * Usage: var singular = t('File'); | |
| * Usage: var multiple = t('File','Files',3); | |
| * See: http://localize.biz/free/converter/api#to-js | |
| * Locale: pl_PL, Polish | |
| */ | |
| var t = function( pairs ){ | |
| // named plural forms according to Unicode | |
| var pluralForms = ["one","few","many"]; | |
| // calc numeric index of a plural form (0-2) | |
| function pluralIndex( n ){ | |
| return Number( (n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2) ); | |
| } | |
| // expose public t() function | |
| return function( msgid1, msgid2, n ){ | |
| var value = pairs[msgid1]; | |
| if( arguments.length < 2 ){ | |
| if( null == value ){ | |
| return msgid1||''; | |
| } | |
| if( 'string' !== typeof value ){ | |
| value = value.one; | |
| } | |
| return value; | |
| } | |
| // plural operation | |
| n = pluralIndex( n ); | |
| value = value ? value[ pluralForms[n]||'other' ] : null; | |
| if( null == value ){ | |
| return n ? msgid2||msgid1 : msgid1; | |
| } | |
| return value; | |
| } | |
| }( | |
| {"File":{"one":"Plik","few":"Pliki","many":"Pliko'w"}} | |
| ); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working on neat design pattern for a machine-generated script for the Loco language pack converter
The translations and plural rules are baked into the closure to avoid external dependencies.