ilib
Version:
iLib is a cross-engine library of internationalization (i18n) classes written in pure JS
2 lines • 11 kB
JavaScript
// !data plurals
var ilib=require("./ilib.js"),Utils=require("./Utils.js"),MathUtils=require("./MathUtils.js"),Locale=require("./Locale.js"),IString=function(string){this.str="object"==typeof string?string instanceof IString?string.str:string.toString():"string"==typeof string?new String(string):"",this.length=this.str.length,this.cpLength=-1,this.localeSpec=ilib.getLocale()};IString._isSurrogate=function(ch){var n=ch.charCodeAt(0);return 56320<=n&&n<=57343||55296<=n&&n<=56319},IString.plurals_default={one:{and:[{eq:["i",1]},{eq:["v",0]}]}},IString.fromCodePoint=function(codepoint){if(codepoint<65536)return String.fromCharCode(codepoint);var high=Math.floor(codepoint/65536)-1,low=65535&codepoint;return String.fromCharCode(55296|(15&high)<<6|(64512&low)>>10)+String.fromCharCode(56320|1023&low)},IString.toCodePoint=function(str,index){if(!str||0===str.length)return-1;var code=-1,high=str.charCodeAt(index);if(55296<=high&&high<=56319){if(str.length>index+1){var low=str.charCodeAt(index+1);56320<=low&&low<=57343&&(code=1+((960&high)>>6)<<16|(63&high)<<10|1023&low)}}else code=high;return code},IString.loadPlurals=function(sync,locale,loadParams,onLoad){var loc;(loc=locale?"string"==typeof locale?new Locale(locale):locale:new Locale(ilib.getLocale())).getLanguage();Utils.loadData({name:"plurals.json",object:"IString",locale:loc,sync:sync,loadParams:loadParams,callback:ilib.bind(this,function(plurals){plurals=plurals||IString.plurals_default,onLoad&&"function"==typeof onLoad&&onLoad(plurals)})})},IString._fncs={firstProp:function(obj){for(var p in obj)if(p&&obj[p])return p},firstPropRule:function(obj){if("[object Array]"===Object.prototype.toString.call(obj))return"inrange";if("[object Object]"===Object.prototype.toString.call(obj))for(var p in obj)if(p&&obj[p])return p},getValue:function(obj,n){if("object"!=typeof obj)return"string"==typeof obj?"object"==typeof n?n[obj]:n:obj;var subrule=IString._fncs.firstPropRule(obj);return"inrange"===subrule?IString._fncs[subrule](obj,n):IString._fncs[subrule](obj[subrule],n)},matchRangeContinuous:function(n,range){for(var num in range)if(void 0!==num&&void 0!==range[num]){var obj=range[num];if("number"==typeof obj){if(n===range[num])return!0;if(n>=range[0]&&n<=range[1])return!0}else if("[object Array]"===Object.prototype.toString.call(obj)&&n>=obj[0]&&n<=obj[1])return!0}return!1},calculateNumberDigits:function(number){var numberToString=number.toString(),parts=[],numberDigits={},operandSymbol={};return-1!==numberToString.indexOf(".")?(parts=numberToString.split(".",2),numberDigits.integerPart=parseInt(parts[0],10),numberDigits.decimalPartLength=parts[1].length,numberDigits.decimalPart=parseInt(parts[1],10),operandSymbol.n=parseFloat(number),operandSymbol.i=numberDigits.integerPart,operandSymbol.v=numberDigits.decimalPartLength,operandSymbol.w=numberDigits.decimalPartLength,operandSymbol.f=numberDigits.decimalPart,operandSymbol.t=numberDigits.decimalPart):(numberDigits.integerPart=number,numberDigits.decimalPartLength=0,numberDigits.decimalPart=0,operandSymbol.n=parseInt(number,10),operandSymbol.i=numberDigits.integerPart,operandSymbol.v=0,operandSymbol.w=0,operandSymbol.f=0,operandSymbol.t=0),operandSymbol},matchRange:function(n,range){return IString._fncs.matchRangeContinuous(n,range)},is:function(rule,n){return IString._fncs.getValue(rule[0],n)==IString._fncs.getValue(rule[1],n)},isnot:function(rule,n){return IString._fncs.getValue(rule[0],n)!=IString._fncs.getValue(rule[1],n)},inrange:function(rule,n){if("number"==typeof rule[0])return"object"==typeof n?IString._fncs.matchRange(n.n,rule):IString._fncs.matchRange(n,rule);if(void 0!==rule[0])return IString._fncs.matchRange(IString._fncs.getValue(rule[0],n),rule[1]);var subrule=IString._fncs.firstPropRule(rule);return IString._fncs[subrule](rule[subrule],n)},notin:function(rule,n){return!IString._fncs.matchRange(IString._fncs.getValue(rule[0],n),rule[1])},within:function(rule,n){return IString._fncs.matchRangeContinuous(IString._fncs.getValue(rule[0],n),rule[1])},mod:function(rule,n){return MathUtils.mod(IString._fncs.getValue(rule[0],n),IString._fncs.getValue(rule[1],n))},n:function(rule,n){return n},or:function(rule,n){var i,ruleLength=rule.length;for(i=0;i<ruleLength;i++)if(IString._fncs.getValue(rule[i],n))return!0;return!1},and:function(rule,n){var i,ruleLength=rule.length;for(i=0;i<ruleLength;i++)if(!IString._fncs.getValue(rule[i],n))return!1;return!0},eq:function(rule,n){var valueRight,valueLeft=IString._fncs.getValue(rule[0],n);return"string"==typeof rule[0]?"object"==typeof n&&(valueRight=n[rule[0]],"number"==typeof rule[1]?valueRight=IString._fncs.getValue(rule[1],n):"object"==typeof rule[1]&&"inrange"===IString._fncs.firstPropRule(rule[1])&&(valueRight=IString._fncs.getValue(rule[1],n))):valueRight="inrange"===IString._fncs.firstPropRule(rule[1])?IString._fncs.getValue(rule[1],valueLeft):IString._fncs.getValue(rule[1],n),"boolean"==typeof valueRight?!!valueRight:valueLeft==valueRight},neq:function(rule,n){var valueRight,leftRange,rightRange,valueLeft=IString._fncs.getValue(rule[0],n);if("string"==typeof rule[0]){if(valueRight=n[rule[0]],"number"==typeof rule[1])valueRight=IString._fncs.getValue(rule[1],n);else if("object"==typeof rule[1]&&(leftRange=rule[1][0],rightRange=rule[1][1],"number"==typeof leftRange&&"number"==typeof rightRange))return!(leftRange<=valueLeft&&valueRight<=rightRange)}else valueRight="inrange"===IString._fncs.firstPropRule(rule[1])?IString._fncs.getValue(rule[1],valueLeft):IString._fncs.getValue(rule[1],n);return"boolean"==typeof valueRight?!valueRight:valueLeft!==valueRight}},IString.prototype={_length:function(){return this.str.length},format:function(params){var regex,formatted=this.str;if(params)for(var p in params)void 0!==params[p]&&(regex=new RegExp("{"+p+"}","g"),formatted=formatted.replace(regex,params[p]));return formatted.toString()},_testChoice:function(index,limit){var operandValue={};switch(typeof index){case"number":if(operandValue=IString._fncs.calculateNumberDigits(index),"<="===limit.substring(0,2))return limit=parseFloat(limit.substring(2)),operandValue.n<=limit;if(">="===limit.substring(0,2))return limit=parseFloat(limit.substring(2)),operandValue.n>=limit;if("<"===limit.charAt(0))return limit=parseFloat(limit.substring(1)),operandValue.n<limit;if(">"===limit.charAt(0))return limit=parseFloat(limit.substring(1)),operandValue.n>limit;switch(this.locale=this.locale||new Locale(this.localeSpec),limit){case"zero":case"one":case"two":case"few":case"many":var ruleset=ilib.data["plurals_"+this.locale.getLanguage()]||IString.plurals_default;if(ruleset){var rule=ruleset[limit];return IString._fncs.getValue(rule,operandValue)}break;case"":case"other":return!0;default:var dash=limit.indexOf("-");if(-1===dash)return operandValue.n===parseInt(limit,10);var start=limit.substring(0,dash),end=limit.substring(dash+1);return operandValue.n>=parseInt(start,10)&&operandValue.n<=parseInt(end,10)}break;case"boolean":return"true"===limit&&!0===index||"false"===limit&&!1===index;case"string":return new RegExp(limit,"i").test(index);case"object":throw"syntax error: formatChoice parameter for the argument index cannot be an object"}return!1},formatChoice:function(argIndex,params){var i,parts,choices=this.str.split("|"),limits=[],strings=[],result=void 0,defaultCase="";if(0===this.str.length)return"";for(i=0;i<choices.length;i++)if(2<(parts=choices[i].split("#")).length)limits[i]=parts[0],parts=parts.shift(),strings[i]=parts.join("#");else{if(2!==parts.length)throw"syntax error in choice format pattern: "+choices[i];limits[i]=parts[0],strings[i]=parts[1]}var args=ilib.isArray(argIndex)?argIndex:[argIndex];for(i=0;i<limits.length;i++)if(0===limits[i].length)defaultCase=new IString(strings[i]);else{for(var limitsArr=-1<limits[i].indexOf(",")?limits[i].split(","):[limits[i]],applicable=!0,j=0;applicable&&j<args.length&&j<limitsArr.length;j++)applicable=this._testChoice(args[j],limitsArr[j]);applicable&&(result=new IString(strings[i]),i=limits.length)}return result||(result=defaultCase||new IString("")),(result=result.format(params)).toString()},toString:function(){return this.str.toString()},valueOf:function(){return this.str.valueOf()},charAt:function(index){return new IString(this.str.charAt(index))},charCodeAt:function(index){return this.str.charCodeAt(index)},concat:function(strings){return new IString(this.str.concat(strings))},indexOf:function(searchValue,start){return this.str.indexOf(searchValue,start)},lastIndexOf:function(searchValue,start){return this.str.lastIndexOf(searchValue,start)},match:function(regexp){return this.str.match(regexp)},replace:function(searchValue,newValue){return new IString(this.str.replace(searchValue,newValue))},search:function(regexp){return this.str.search(regexp)},slice:function(start,end){return new IString(this.str.slice(start,end))},split:function(separator,limit){return this.str.split(separator,limit)},substr:function(start,length){var plat=ilib._getPlatform();return"qt"!==plat&&"rhino"!==plat&&"trireme"!==plat||void 0===length&&(length=this.str.length-start),new IString(this.str.substr(start,length))},substring:function(from,to){return this.str.substring(from,to)},toLowerCase:function(){return this.str.toLowerCase()},toUpperCase:function(){return this.str.toUpperCase()},_toCodePoint:function(index){return IString.toCodePoint(this.str,index)},forEach:function(callback){if("function"==typeof callback)for(var it=this.charIterator();it.hasNext();)callback(it.next())},forEachCodePoint:function(callback){if("function"==typeof callback)for(var it=this.iterator();it.hasNext();)callback(it.next())},iterator:function(){return new function(istring){this.index=0,this.hasNext=function(){return this.index<istring.str.length},this.next=function(){if(this.index<istring.str.length){var num=istring._toCodePoint(this.index);this.index+=65535<num?2:1}else num=-1;return num}}(this)},charIterator:function(){return new function(istring){this.index=0,this.hasNext=function(){return this.index<istring.str.length},this.next=function(){var ch;return this.index<istring.str.length&&(ch=istring.str.charAt(this.index),IString._isSurrogate(ch)&&this.index+1<istring.str.length&&IString._isSurrogate(istring.str.charAt(this.index+1))&&(this.index++,ch+=istring.str.charAt(this.index)),this.index++),ch}}(this)},codePointAt:function(index){if(index<0)return-1;var count,ch,it=this.iterator();for(count=index;0<=count&&it.hasNext();count--)ch=it.next();return count<0?ch:-1},setLocale:function(locale,sync,loadParams,onLoad){this.locale="object"==typeof locale?locale:(this.localeSpec=locale,new Locale(locale)),IString.loadPlurals(void 0===sync||sync,this.locale,loadParams,onLoad)},getLocale:function(){return(this.locale?this.locale.getSpec():this.localeSpec)||ilib.getLocale()},codePointLength:function(){if(-1===this.cpLength){var it=this.iterator();for(this.cpLength=0;it.hasNext();)this.cpLength++,it.next()}return this.cpLength}},module.exports=IString;