UNPKG

2.24 kBJavaScriptView Raw
1export const CC_TO_UP = new Array(256);
2export const CC_TO_LO = new Array(256);
3for (let i = 0; i < CC_TO_UP.length; i++) {
4 CC_TO_LO[i] = String.fromCharCode(i).toLowerCase();
5 CC_TO_UP[i] = String.fromCharCode(i).toUpperCase();
6}
7/** @internal */
8function formatAllCaps(w) {
9 return w.slice(0, w.length - 1).toLowerCase() + CC_TO_UP[w.charCodeAt(w.length - 1)];
10}
11/**
12 * @internal
13 *
14 * Inspired by https://stackoverflow.com/a/2970667
15 *
16 * This is not as optimal as the original SO answer (we split into per-word),
17 * however it does pass the tests (which the SO version doesn't) and is still
18 * a major improvement over the original camelcase npm package -
19 *
20 * camelcase: 20.88 μs/op
21 * this: 1.00 μs/op
22 *
23 * Caveat of this: only Ascii, but acceptable for the intended usecase
24 */
25function converter(format) {
26 return (value) => {
27 const parts = value
28 // replace all separators (including consequtive) with spaces
29 .replace(/[-_., ]+/g, ' ')
30 // we don't want leading or trailing spaces
31 .trim()
32 // split into words
33 .split(' ');
34 const count = parts.length;
35 let result = '';
36 for (let i = 0; i < count; i++) {
37 const w = parts[i];
38 // apply the formatting
39 result += format(/^[\dA-Z]+$/.test(w)
40 // all full uppercase + letters are changed to lowercase
41 ? w.toLowerCase()
42 // all consecutive capitals + letters are changed to lowercase
43 // e.g. UUID64 -> uuid64, while preserving splits, eg. NFTOrder -> nftOrder
44 : w.replace(/^[\dA-Z]{2,}[^a-z]/, formatAllCaps), i);
45 }
46 return result;
47 };
48}
49/**
50 * @name stringCamelCase
51 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to camelCase
52 */
53export const stringCamelCase = /*#__PURE__*/ converter((w, i) =>
54(i ? CC_TO_UP[w.charCodeAt(0)] : CC_TO_LO[w.charCodeAt(0)]) + w.slice(1));
55/**
56 * @name stringPascalCase
57 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to PascalCase
58 */
59export const stringPascalCase = /*#__PURE__*/ converter((w) =>
60CC_TO_UP[w.charCodeAt(0)] + w.slice(1));
\No newline at end of file