Skip to content

Instantly share code, notes, and snippets.

@timwhitlock
Last active December 17, 2015 10:59
Show Gist options
  • Select an option

  • Save timwhitlock/5599003 to your computer and use it in GitHub Desktop.

Select an option

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
/**
* 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"}}
);
@timwhitlock
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment