collation.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2013 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview Contains helper functions for performing locale-sensitive
  16. * collation.
  17. */
  18. goog.provide('goog.i18n.collation');
  19. /**
  20. * Returns the comparator for a locale. If a locale is not explicitly specified,
  21. * a comparator for the user's locale will be returned. Note that if the browser
  22. * does not support locale-sensitive string comparisons, the comparator returned
  23. * will be a simple codepoint comparator.
  24. *
  25. * @param {string=} opt_locale the locale that the comparator is used for.
  26. * @param {{usage: (string|undefined), localeMatcher: (string|undefined),
  27. * sensitivity: (string|undefined), ignorePunctuation: (boolean|undefined),
  28. * numeric: (boolean|undefined), caseFirst: (string|undefined)}=}
  29. * opt_options the optional set of options for use with the native
  30. * collator.
  31. * @return {function(string, string): number} The locale-specific comparator.
  32. */
  33. goog.i18n.collation.createComparator = function(opt_locale, opt_options) {
  34. // See http://code.google.com/p/v8-i18n.
  35. if (goog.i18n.collation.hasNativeComparator()) {
  36. var intl = goog.global.Intl;
  37. return new intl.Collator([opt_locale || goog.LOCALE], opt_options || {})
  38. .compare;
  39. } else {
  40. return function(arg1, arg2) { return arg1.localeCompare(arg2); };
  41. }
  42. };
  43. /**
  44. * Returns true if a locale-sensitive comparator is available for a locale. If
  45. * a locale is not explicitly specified, the user's locale is used instead.
  46. *
  47. * @param {string=} opt_locale The locale to be checked.
  48. * @return {boolean} Whether there is a locale-sensitive comparator available
  49. * for the locale.
  50. */
  51. goog.i18n.collation.hasNativeComparator = function(opt_locale) {
  52. var intl = goog.global.Intl;
  53. return !!(intl && intl.Collator);
  54. };