-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtoQuantity.ts
50 lines (43 loc) · 1.57 KB
/
toQuantity.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// @ts-ignore
import { Vocabularies } from "./src/Humanizer/Inflections/Vocabularies.ts"
import "./numberToWords.ts"
declare global {
interface String {
toQuantity(quantity: number, showQuantityAs?: ShowQuantityAs): string
}
}
/**
* Enumerates the ways of displaying a quantity value when converting
*/
export enum ShowQuantityAs {
/** Indicates that no quantity will be included in the formatted string. */
None,
/**
* Indicates that the quantity will be included in the output, formatted
* as its numeric value (e.g. "1").
*/
Numeric,
/**
* Incidates that the quantity will be included in the output, formatted as
* words (e.g. 123 => "one hundred and twenty three").
*/
Words
}
/**
* Prefixes the provided word with the number and accordingly pluralizes or singularizes the word
* @param {number} quantity - The quantity of the word
* @param {ShowQuantityAs} showQuantityAs - How to show the quantity. Numeric by default
* @returns {string} - The converted value
*/
String.prototype.toQuantity = function (quantity: number, showQuantityAs: ShowQuantityAs = ShowQuantityAs.Numeric): string {
const transformedInput = quantity === 1
? Vocabularies.Default().singularize(this as string, false)
: Vocabularies.Default().pluralize(this as string, false)
if (showQuantityAs === ShowQuantityAs.None) {
return transformedInput;
}
if (showQuantityAs === ShowQuantityAs.Numeric) {
return `${quantity} ${transformedInput}`
}
return `${quantity.toWords()} ${transformedInput}`
}