|
1 | 1 | import { inflections } from "./Inflector";
|
| 2 | +import { cacheable } from "./cache"; |
| 3 | +export const humanize = cacheable( |
| 4 | + (lowerCaseAndUnderscoredWord: string, options?: { capitalize?: boolean }) => { |
| 5 | + let result = "" + lowerCaseAndUnderscoredWord; |
| 6 | + const inflector = inflections(); |
| 7 | + const humans = inflector.humans; |
| 8 | + let human, rule, replacement; |
| 9 | + |
| 10 | + options = options || {}; |
| 11 | + |
| 12 | + if (options.capitalize === null || options.capitalize === undefined) { |
| 13 | + options.capitalize = true; |
| 14 | + } |
2 | 15 |
|
3 |
| -export function humanize(lowerCaseAndUnderscoredWord: string, options?: { capitalize?: boolean }) { |
4 |
| - let result = "" + lowerCaseAndUnderscoredWord; |
5 |
| - const inflector = inflections(); |
6 |
| - const humans = inflector.humans; |
7 |
| - let human, rule, replacement; |
8 |
| - |
9 |
| - options = options || {}; |
10 |
| - |
11 |
| - if (options.capitalize === null || options.capitalize === undefined) { |
12 |
| - options.capitalize = true; |
13 |
| - } |
14 |
| - |
15 |
| - for (let i = 0, ii = humans.length; i < ii; i++) { |
16 |
| - human = humans[i]; |
17 |
| - rule = human[0]; |
18 |
| - replacement = human[1]; |
| 16 | + for (let i = 0, ii = humans.length; i < ii; i++) { |
| 17 | + human = humans[i]; |
| 18 | + rule = human[0]; |
| 19 | + replacement = human[1]; |
19 | 20 |
|
20 |
| - if (rule instanceof RegExp ? rule.test(result) : result.indexOf(rule) > -1) { |
21 |
| - result = result.replace(rule, replacement); |
22 |
| - break; |
| 21 | + if (rule instanceof RegExp ? rule.test(result) : result.indexOf(rule) > -1) { |
| 22 | + result = result.replace(rule, replacement); |
| 23 | + break; |
| 24 | + } |
23 | 25 | }
|
24 |
| - } |
25 | 26 |
|
26 |
| - result = result.replace(/_id$/, ""); |
27 |
| - result = result.replace(/_/g, " "); |
| 27 | + result = result.replace(/_id$/, ""); |
| 28 | + result = result.replace(/_/g, " "); |
28 | 29 |
|
29 |
| - result = result.replace(/([a-z\d]*)/gi, function (match) { |
30 |
| - return inflector.lowerToAcronyms[match] || match.toLowerCase(); |
31 |
| - }); |
32 |
| - |
33 |
| - if (options.capitalize) { |
34 |
| - result = result.replace(/^\w/, function (match) { |
35 |
| - return match.toUpperCase(); |
| 30 | + result = result.replace(/([a-z\d]*)/gi, function (match) { |
| 31 | + return inflector.lowerToAcronyms[match] || match.toLowerCase(); |
36 | 32 | });
|
37 |
| - } |
38 | 33 |
|
39 |
| - return result; |
40 |
| -} |
| 34 | + if (options.capitalize) { |
| 35 | + result = result.replace(/^\w/, function (match) { |
| 36 | + return match.toUpperCase(); |
| 37 | + }); |
| 38 | + } |
| 39 | + |
| 40 | + return result; |
| 41 | + }, |
| 42 | + (lowerCaseAndUnderscoredWord, options) => `${lowerCaseAndUnderscoredWord}-${options?.capitalize}` |
| 43 | +); |
0 commit comments