@isaacs/string-locale-compare
Advanced tools
Comparing version 1.0.1 to 1.1.0
36
index.js
@@ -5,19 +5,39 @@ const hasIntl = typeof Intl === 'object' && !!Intl | ||
const collatorCompare = locale => { | ||
const collator = new Collator(locale) | ||
const collatorCompare = (locale, opts) => { | ||
const collator = new Collator(locale, opts) | ||
return (a, b) => collator.compare(a, b) | ||
} | ||
const localeCompare = locale => (a, b) => a.localeCompare(b, locale) | ||
const localeCompare = (locale, opts) => (a, b) => a.localeCompare(b, locale, opts) | ||
module.exports = locale => { | ||
const knownOptions = [ | ||
'sensitivity', | ||
'numeric', | ||
'ignorePunctuation', | ||
'caseFirst', | ||
] | ||
const { hasOwnProperty } = Object.prototype | ||
module.exports = (locale, options = {}) => { | ||
if (!locale || typeof locale !== 'string') | ||
throw new TypeError('locale required') | ||
if (cache.has(locale)) | ||
return cache.get(locale) | ||
const opts = knownOptions.reduce((opts, k) => { | ||
if (hasOwnProperty.call(options, k)) { | ||
opts[k] = options[k] | ||
} | ||
return opts | ||
}, {}) | ||
const key = `${locale}\n${JSON.stringify(opts)}` | ||
const compare = hasIntl ? collatorCompare(locale) : localeCompare(locale) | ||
cache.set(locale, compare) | ||
if (cache.has(key)) | ||
return cache.get(key) | ||
const compare = hasIntl | ||
? collatorCompare(locale, opts) | ||
: localeCompare(locale, opts) | ||
cache.set(key, compare) | ||
return compare | ||
} |
{ | ||
"name": "@isaacs/string-locale-compare", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"files": [ | ||
@@ -5,0 +5,0 @@ "index.js" |
@@ -15,2 +15,18 @@ # @isaacs/string-locale-compare | ||
myArrayOfStrings.sort(stringLocaleCompare('en')) | ||
// can also pass extra options | ||
myArrayOfNumericStrings.sort(stringLocaleCompare('en', { numeric: true })) | ||
``` | ||
## API | ||
`stringLocaleCompare(locale, [options])` | ||
Locale is required, must be a valid locale string. | ||
Options is optional. The following options are supported: | ||
* `sensitivity` | ||
* `numeric` | ||
* `ignorePunctuation` | ||
* `caseFirst` |
3162
33
32