-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[ResponseOps] adds FormatNumber mustache lambda (#159644)
resolves #155869 Adds mustache lambda `{{#FormatNumber}}`, which uses [Intl.NumberFormat][] to format the number. [Intl.NumberFormat]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
- Loading branch information
Showing
6 changed files
with
354 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
124 changes: 124 additions & 0 deletions
124
x-pack/plugins/actions/server/lib/number_formatter.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0; you may not use this file except in compliance with the Elastic License | ||
* 2.0. | ||
*/ | ||
|
||
import { formatNumber } from './number_formatter'; | ||
|
||
describe('formatNumber()', () => { | ||
it('using defaults is successful', () => { | ||
expect(formatNumber('1;;')).toMatchInlineSnapshot(`"1"`); | ||
}); | ||
|
||
it('error cases handled', () => { | ||
expect(formatNumber('1')).toMatchInlineSnapshot(`"invalid format, missing semicolons: '1'"`); | ||
expect(formatNumber('nope;;')).toMatchInlineSnapshot(`"invalid number: 'nope'"`); | ||
expect(formatNumber('1;; nah')).toMatchInlineSnapshot( | ||
`"invalid options: missing colon in option: 'nah'"` | ||
); | ||
expect(formatNumber('1;; minimumIntegerDigits: N.O.')).toMatchInlineSnapshot( | ||
`"error formatting number: minimumIntegerDigits value is out of range."` | ||
); | ||
expect(formatNumber('1;; compactDisplay: uhuh')).toMatchInlineSnapshot( | ||
`"error formatting number: Value uhuh out of range for Intl.NumberFormat options property compactDisplay"` | ||
); | ||
}); | ||
|
||
it('using locales is successful', () => { | ||
expect(formatNumber('1000; de-DE;')).toMatchInlineSnapshot(`"1.000"`); | ||
}); | ||
|
||
it('option compactDisplay is successful', () => { | ||
expect( | ||
formatNumber(' 1000;; notation: compact, compactDisplay: short, ') | ||
).toMatchInlineSnapshot(`"1K"`); | ||
}); | ||
|
||
it('option currency is successful', () => { | ||
expect(formatNumber('1000;; currency: EUR, style: currency')).toMatchInlineSnapshot( | ||
`"€1,000.00"` | ||
); | ||
}); | ||
|
||
it('option currencyDisplay is successful', () => { | ||
expect( | ||
formatNumber('1000;; currency: EUR, style: currency, currencyDisplay: name') | ||
).toMatchInlineSnapshot(`"1,000.00 euros"`); | ||
}); | ||
|
||
it('option currencySign is successful', () => { | ||
expect( | ||
formatNumber('-1;; currency: EUR, style: currency, currencySign: accounting') | ||
).toMatchInlineSnapshot(`"(€1.00)"`); | ||
}); | ||
|
||
// not sure how to test this, and probably doesn't matter | ||
// because we default to en-US, and generally don't have | ||
// control over the server's locale | ||
it.skip('option localeMatcher is successful', () => {}); | ||
|
||
it('option notation is successful', () => { | ||
expect(formatNumber('1000;; notation: engineering')).toMatchInlineSnapshot(`"1E3"`); | ||
}); | ||
|
||
it('option numberingSystem is successful', () => { | ||
expect(formatNumber('1;; numberingSystem: fullwide')).toMatchInlineSnapshot(`"1"`); | ||
}); | ||
|
||
it('option signDisplay is successful', () => { | ||
expect(formatNumber('1;; signDisplay: always')).toMatchInlineSnapshot(`"+1"`); | ||
}); | ||
|
||
it('option style is successful', () => { | ||
expect(formatNumber('1;; style: percent')).toMatchInlineSnapshot(`"100%"`); | ||
}); | ||
|
||
it('option unit is successful', () => { | ||
expect(formatNumber('1;; style: unit, unit: acre-per-liter')).toMatchInlineSnapshot(`"1 ac/L"`); | ||
}); | ||
|
||
it('option unitDisplay is successful', () => { | ||
expect( | ||
formatNumber('1;; style: unit, unit: petabyte, unitDisplay: narrow') | ||
).toMatchInlineSnapshot(`"1PB"`); | ||
}); | ||
|
||
it('option useGrouping is successful', () => { | ||
expect(formatNumber('1000;; useGrouping: true ')).toMatchInlineSnapshot(`"1,000"`); | ||
expect(formatNumber('1000;; useGrouping: false')).toMatchInlineSnapshot(`"1000"`); | ||
}); | ||
|
||
// not yet supported in node.js | ||
it.skip('option roundingMode is successful', () => {}); | ||
|
||
// not yet supported in node.js | ||
it.skip('option roundingPriority is successful', () => {}); | ||
|
||
// not yet supported in node.js | ||
it.skip('option roundingIncrement is successful', () => {}); | ||
|
||
// not yet supported in node.js | ||
it.skip('option trailingZeroDisplay is successful', () => {}); | ||
|
||
it('option minimumIntegerDigits is successful', () => { | ||
expect(formatNumber('1;; minimumIntegerDigits: 7')).toMatchInlineSnapshot(`"0,000,001"`); | ||
}); | ||
|
||
it('option minimumFractionDigits is successful', () => { | ||
expect(formatNumber('1;; minimumFractionDigits: 3')).toMatchInlineSnapshot(`"1.000"`); | ||
}); | ||
|
||
it('option maximumFractionDigits is successful', () => { | ||
expect(formatNumber('1.234;; maximumFractionDigits: 2')).toMatchInlineSnapshot(`"1.23"`); | ||
}); | ||
|
||
it('option minimumSignificantDigits is successful', () => { | ||
expect(formatNumber('1;; minimumSignificantDigits: 3')).toMatchInlineSnapshot(`"1.00"`); | ||
}); | ||
|
||
it('option maximumSignificantDigits is successful', () => { | ||
expect(formatNumber('123456;; maximumSignificantDigits: 4')).toMatchInlineSnapshot(`"123,500"`); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License | ||
* 2.0; you may not use this file except in compliance with the Elastic License | ||
* 2.0. | ||
*/ | ||
|
||
const DEFAULT_LOCALES = ['en-US']; | ||
|
||
/** | ||
* Takes a string which contains a number and formatting options, | ||
* and returns that string formatted according to the options. | ||
* Intl.FormatNumber is used for formatting. | ||
* | ||
* The format is 'number; locales; options', where | ||
* - `number` is the number to format | ||
* - `locales` is a comma-separated list of locales | ||
* - `options` is a comma-separated list of Intl.NumberFormat options | ||
* | ||
* Both semicolons are required , but the `locales` and `options` can | ||
* be empty. If `locales` is empty, `en-US` is used, for consistency. | ||
* | ||
* Examples: | ||
* `1234.567; en-US; style: currency, currency: USD` | ||
* `1234.567;; style: currency, currency: USD` | ||
* `1234.567;;` | ||
* | ||
* see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat | ||
* | ||
* @param numberAndFormat string containing a number and formatting options | ||
* @returns number formatted according to the options | ||
*/ | ||
export function formatNumber(numberLocalesOptions: string): string { | ||
const [numString, localesString, optionsString] = splitNumberLocalesOptions(numberLocalesOptions); | ||
if (localesString === undefined || optionsString === undefined) { | ||
return `invalid format, missing semicolons: '${numberLocalesOptions}'`; | ||
} | ||
|
||
const num = parseFloat(numString); | ||
if (isNaN(num)) return `invalid number: '${numString}'`; | ||
|
||
const locales = getLocales(localesString); | ||
|
||
const [options, optionsError] = getOptions(optionsString); | ||
if (optionsError) return `invalid options: ${optionsError}`; | ||
|
||
try { | ||
return new Intl.NumberFormat(locales, options).format(num); | ||
} catch (err) { | ||
return `error formatting number: ${err.message}`; | ||
} | ||
} | ||
|
||
function getLocales(localesString: string): string[] { | ||
const locales = splitCommas(localesString) | ||
.map((s) => s.trim()) | ||
.filter((s) => s.length > 0); | ||
|
||
if (locales.length > 0) return locales; | ||
|
||
return DEFAULT_LOCALES; | ||
} | ||
|
||
type IntlNumberOptions = Record<string, string | number | boolean>; | ||
|
||
function getOptions(optionsString: string): [IntlNumberOptions, string?] { | ||
const options: IntlNumberOptions = {}; | ||
|
||
const keyVals = splitCommas(optionsString); | ||
|
||
for (const keyVal of keyVals) { | ||
if (keyVal === '') continue; | ||
|
||
const [key, valString] = splitKeyVal(keyVal); | ||
if (valString === undefined) { | ||
return [{}, `missing colon in option: '${keyVal}'`]; | ||
} | ||
|
||
options[key] = getVal(valString); | ||
} | ||
|
||
return [options]; | ||
} | ||
|
||
// Intl.NumberFormat options can be a string, number, or boolean | ||
// There don't seem to be cases of needing to send a string version | ||
// of a boolean or number. | ||
function getVal(valString: string): string | number | boolean { | ||
const valAsNum = parseFloat(valString); | ||
if (!isNaN(valAsNum)) return valAsNum; | ||
|
||
if (valString === 'true') return true; | ||
if (valString === 'false') return false; | ||
|
||
return valString; | ||
} | ||
|
||
function splitCommas(str: string): string[] { | ||
return str.split(',').map((s) => s.trim()); | ||
} | ||
|
||
function splitKeyVal(s: string): [string, string | undefined] { | ||
const [key, val] = s.split(':', 2); | ||
return [key.trim(), val?.trim()]; | ||
} | ||
|
||
function splitNumberLocalesOptions( | ||
numberLocalesOptions: string | ||
): [string, string | undefined, string | undefined] { | ||
const [num, locales, options] = numberLocalesOptions.split(';', 3); | ||
return [num.trim(), locales?.trim(), options?.trim()]; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters