PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs/globalize/1.0.0/globalize/plural.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 359 lines | 238 code | 64 blank | 57 comment | 81 complexity | bf4a19b38d006dee36ee07d17747de94 MD5 | raw file
  1. /**
  2. * Globalize v1.0.0
  3. *
  4. * http://github.com/jquery/globalize
  5. *
  6. * Copyright jQuery Foundation and other contributors
  7. * Released under the MIT license
  8. * http://jquery.org/license
  9. *
  10. * Date: 2015-04-23T12:02Z
  11. */
  12. /*!
  13. * Globalize v1.0.0 2015-04-23T12:02Z Released under the MIT license
  14. * http://git.io/TrdQbw
  15. */
  16. (function( root, factory ) {
  17. // UMD returnExports
  18. if ( typeof define === "function" && define.amd ) {
  19. // AMD
  20. define([
  21. "cldr",
  22. "../globalize",
  23. "cldr/event",
  24. "cldr/supplemental"
  25. ], factory );
  26. } else if ( typeof exports === "object" ) {
  27. // Node, CommonJS
  28. module.exports = factory( require( "cldrjs" ), require( "globalize" ) );
  29. } else {
  30. // Global
  31. factory( root.Cldr, root.Globalize );
  32. }
  33. }(this, function( Cldr, Globalize ) {
  34. var validateCldr = Globalize._validateCldr,
  35. validateDefaultLocale = Globalize._validateDefaultLocale,
  36. validateParameterPresence = Globalize._validateParameterPresence,
  37. validateParameterType = Globalize._validateParameterType,
  38. validateParameterTypePlainObject = Globalize._validateParameterTypePlainObject;
  39. var MakePlural;
  40. /* jshint ignore:start */
  41. MakePlural = (function() {
  42. var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); };
  43. var _toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } };
  44. var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
  45. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
  46. /**
  47. * make-plural.js -- https://github.com/eemeli/make-plural.js/
  48. * Copyright (c) 2014-2015 by Eemeli Aro <eemeli@gmail.com>
  49. *
  50. * Permission to use, copy, modify, and/or distribute this software for any
  51. * purpose with or without fee is hereby granted, provided that the above
  52. * copyright notice and this permission notice appear in all copies.
  53. *
  54. * The software is provided "as is" and the author disclaims all warranties
  55. * with regard to this software including all implied warranties of
  56. * merchantability and fitness. In no event shall the author be liable for
  57. * any special, direct, indirect, or consequential damages or any damages
  58. * whatsoever resulting from loss of use, data or profits, whether in an
  59. * action of contract, negligence or other tortious action, arising out of
  60. * or in connection with the use or performance of this software.
  61. */
  62. var Parser = (function () {
  63. function Parser() {
  64. _classCallCheck(this, Parser);
  65. }
  66. _createClass(Parser, [{
  67. key: 'parse',
  68. value: function parse(cond) {
  69. var _this = this;
  70. if (cond === 'i = 0 or n = 1') {
  71. return 'n >= 0 && n <= 1';
  72. }if (cond === 'i = 0,1') {
  73. return 'n >= 0 && n < 2';
  74. }if (cond === 'i = 1 and v = 0') {
  75. this.v0 = 1;
  76. return 'n == 1 && v0';
  77. }
  78. return cond.replace(/([tv]) (!?)= 0/g, function (m, sym, noteq) {
  79. var sn = sym + '0';
  80. _this[sn] = 1;
  81. return noteq ? '!' + sn : sn;
  82. }).replace(/\b[fintv]\b/g, function (m) {
  83. _this[m] = 1;
  84. return m;
  85. }).replace(/([fin]) % (10+)/g, function (m, sym, num) {
  86. var sn = sym + num;
  87. _this[sn] = 1;
  88. return sn;
  89. }).replace(/n10+ = 0/g, 't0 && $&').replace(/(\w+ (!?)= )([0-9.]+,[0-9.,]+)/g, function (m, se, noteq, x) {
  90. if (m === 'n = 0,1') return '(n == 0 || n == 1)';
  91. if (noteq) return se + x.split(',').join(' && ' + se);
  92. return '(' + se + x.split(',').join(' || ' + se) + ')';
  93. }).replace(/(\w+) (!?)= ([0-9]+)\.\.([0-9]+)/g, function (m, sym, noteq, x0, x1) {
  94. if (Number(x0) + 1 === Number(x1)) {
  95. if (noteq) return '' + sym + ' != ' + x0 + ' && ' + sym + ' != ' + x1;
  96. return '(' + sym + ' == ' + x0 + ' || ' + sym + ' == ' + x1 + ')';
  97. }
  98. if (noteq) return '(' + sym + ' < ' + x0 + ' || ' + sym + ' > ' + x1 + ')';
  99. if (sym === 'n') {
  100. _this.t0 = 1;return '(t0 && n >= ' + x0 + ' && n <= ' + x1 + ')';
  101. }
  102. return '(' + sym + ' >= ' + x0 + ' && ' + sym + ' <= ' + x1 + ')';
  103. }).replace(/ and /g, ' && ').replace(/ or /g, ' || ').replace(/ = /g, ' == ');
  104. }
  105. }, {
  106. key: 'vars',
  107. value: (function (_vars) {
  108. function vars() {
  109. return _vars.apply(this, arguments);
  110. }
  111. vars.toString = function () {
  112. return _vars.toString();
  113. };
  114. return vars;
  115. })(function () {
  116. var vars = [];
  117. if (this.i) vars.push('i = s[0]');
  118. if (this.f || this.v) vars.push('f = s[1] || \'\'');
  119. if (this.t) vars.push('t = (s[1] || \'\').replace(/0+$/, \'\')');
  120. if (this.v) vars.push('v = f.length');
  121. if (this.v0) vars.push('v0 = !s[1]');
  122. if (this.t0 || this.n10 || this.n100) vars.push('t0 = Number(s[0]) == n');
  123. for (var k in this) {
  124. if (/^.10+$/.test(k)) {
  125. var k0 = k[0] === 'n' ? 't0 && s[0]' : k[0];
  126. vars.push('' + k + ' = ' + k0 + '.slice(-' + k.substr(2).length + ')');
  127. }
  128. }if (!vars.length) return '';
  129. return 'var ' + ['s = String(n).split(\'.\')'].concat(vars).join(', ');
  130. })
  131. }]);
  132. return Parser;
  133. })();
  134. var MakePlural = (function () {
  135. function MakePlural(lc) {
  136. var _ref = arguments[1] === undefined ? MakePlural : arguments[1];
  137. var cardinals = _ref.cardinals;
  138. var ordinals = _ref.ordinals;
  139. _classCallCheck(this, MakePlural);
  140. if (!cardinals && !ordinals) throw new Error('At least one type of plural is required');
  141. this.lc = lc;
  142. this.categories = { cardinal: [], ordinal: [] };
  143. this.parser = new Parser();
  144. this.fn = this.buildFunction(cardinals, ordinals);
  145. this.fn._obj = this;
  146. this.fn.categories = this.categories;
  147. this.fn.toString = this.fnToString.bind(this);
  148. return this.fn;
  149. }
  150. _createClass(MakePlural, [{
  151. key: 'compile',
  152. value: function compile(type, req) {
  153. var cases = [];
  154. var rules = MakePlural.rules[type][this.lc];
  155. if (!rules) {
  156. if (req) throw new Error('Locale "' + this.lc + '" ' + type + ' rules not found');
  157. this.categories[type] = ['other'];
  158. return '\'other\'';
  159. }
  160. for (var r in rules) {
  161. var _rules$r$trim$split = rules[r].trim().split(/\s*@\w*/);
  162. var _rules$r$trim$split2 = _toArray(_rules$r$trim$split);
  163. var cond = _rules$r$trim$split2[0];
  164. var examples = _rules$r$trim$split2.slice(1);
  165. var cat = r.replace('pluralRule-count-', '');
  166. if (cond) cases.push([this.parser.parse(cond), cat]);
  167. }
  168. this.categories[type] = cases.map(function (c) {
  169. return c[1];
  170. }).concat('other');
  171. if (cases.length === 1) {
  172. return '(' + cases[0][0] + ') ? \'' + cases[0][1] + '\' : \'other\'';
  173. } else {
  174. return [].concat(_toConsumableArray(cases.map(function (c) {
  175. return '(' + c[0] + ') ? \'' + c[1] + '\'';
  176. })), ['\'other\'']).join('\n : ');
  177. }
  178. }
  179. }, {
  180. key: 'buildFunction',
  181. value: function buildFunction(cardinals, ordinals) {
  182. var _this3 = this;
  183. var compile = function compile(c) {
  184. return c ? (c[1] ? 'return ' : 'if (ord) return ') + _this3.compile.apply(_this3, _toConsumableArray(c)) : '';
  185. },
  186. fold = { vars: function vars(str) {
  187. return (' ' + str + ';').replace(/(.{1,78})(,|$) ?/g, '$1$2\n ');
  188. },
  189. cond: function cond(str) {
  190. return (' ' + str + ';').replace(/(.{1,78}) (\|\| |$) ?/gm, '$1\n $2');
  191. } },
  192. cond = [ordinals && ['ordinal', !cardinals], cardinals && ['cardinal', true]].map(compile).map(fold.cond),
  193. body = [fold.vars(this.parser.vars())].concat(_toConsumableArray(cond)).join('\n').replace(/\s+$/gm, '').replace(/^[\s;]*[\r\n]+/gm, ''),
  194. args = ordinals && cardinals ? 'n, ord' : 'n';
  195. return new Function(args, body);
  196. }
  197. }, {
  198. key: 'fnToString',
  199. value: function fnToString(name) {
  200. return Function.prototype.toString.call(this.fn).replace(/^function( \w+)?/, name ? 'function ' + name : 'function').replace('\n/**/', '');
  201. }
  202. }], [{
  203. key: 'load',
  204. value: function load() {
  205. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  206. args[_key] = arguments[_key];
  207. }
  208. args.forEach(function (cldr) {
  209. var data = cldr && cldr.supplemental || null;
  210. if (!data) throw new Error('Data does not appear to be CLDR data');
  211. MakePlural.rules = {
  212. cardinal: data['plurals-type-cardinal'] || MakePlural.rules.cardinal,
  213. ordinal: data['plurals-type-ordinal'] || MakePlural.rules.ordinal
  214. };
  215. });
  216. return MakePlural;
  217. }
  218. }]);
  219. return MakePlural;
  220. })();
  221. MakePlural.cardinals = true;
  222. MakePlural.ordinals = false;
  223. MakePlural.rules = { cardinal: {}, ordinal: {} };
  224. return MakePlural;
  225. }());
  226. /* jshint ignore:end */
  227. var validateParameterTypeNumber = function( value, name ) {
  228. validateParameterType(
  229. value,
  230. name,
  231. value === undefined || typeof value === "number",
  232. "Number"
  233. );
  234. };
  235. var validateParameterTypePluralType = function( value, name ) {
  236. validateParameterType(
  237. value,
  238. name,
  239. value === undefined || value === "cardinal" || value === "ordinal",
  240. "String \"cardinal\" or \"ordinal\""
  241. );
  242. };
  243. /**
  244. * .plural( value )
  245. *
  246. * @value [Number]
  247. *
  248. * Return the corresponding form (zero | one | two | few | many | other) of a
  249. * value given locale.
  250. */
  251. Globalize.plural =
  252. Globalize.prototype.plural = function( value, options ) {
  253. validateParameterPresence( value, "value" );
  254. validateParameterTypeNumber( value, "value" );
  255. return this.pluralGenerator( options )( value );
  256. };
  257. /**
  258. * .pluralGenerator( [options] )
  259. *
  260. * Return a plural function (of the form below).
  261. *
  262. * fn( value )
  263. *
  264. * @value [Number]
  265. *
  266. * Return the corresponding form (zero | one | two | few | many | other) of a value given the
  267. * default/instance locale.
  268. */
  269. Globalize.pluralGenerator =
  270. Globalize.prototype.pluralGenerator = function( options ) {
  271. var cldr, isOrdinal, plural, type;
  272. validateParameterTypePlainObject( options, "options" );
  273. options = options || {};
  274. type = options.type || "cardinal";
  275. cldr = this.cldr;
  276. validateParameterTypePluralType( options.type, "options.type" );
  277. validateDefaultLocale( cldr );
  278. isOrdinal = type === "ordinal";
  279. cldr.on( "get", validateCldr );
  280. cldr.supplemental([ "plurals-type-" + type, "{language}" ]);
  281. cldr.off( "get", validateCldr );
  282. MakePlural.rules = {};
  283. MakePlural.rules[ type ] = cldr.supplemental( "plurals-type-" + type );
  284. plural = new MakePlural( cldr.attributes.language, {
  285. "ordinals": isOrdinal,
  286. "cardinals": !isOrdinal
  287. });
  288. return function( value ) {
  289. validateParameterPresence( value, "value" );
  290. validateParameterTypeNumber( value, "value" );
  291. return plural( value );
  292. };
  293. };
  294. return Globalize;
  295. }));