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, count = CC_TO_UP.length; i < count; 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 let result = '';
35 for (let i = 0, count = parts.length; i < count; i++) {
36 const w = parts[i];
37 // apply the formatting
38 result += format(/^[\dA-Z]+$/.test(w)
39 // all full uppercase + letters are changed to lowercase
40 ? w.toLowerCase()
41 // all consecutive capitals + letters are changed to lowercase
42 // e.g. UUID64 -> uuid64, while preserving splits, eg. NFTOrder -> nftOrder
43 : w.replace(/^[\dA-Z]{2,}[^a-z]/, formatAllCaps), i);
44 }
45 return result;
46 };
47}
48/**
49 * @name stringCamelCase
50 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to camelCase
51 */
52export const stringCamelCase = /*#__PURE__*/ converter((w, i) =>
53(i ? CC_TO_UP[w.charCodeAt(0)] : CC_TO_LO[w.charCodeAt(0)]) + w.slice(1));
54/**
55 * @name stringPascalCase
56 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to PascalCase
57 */
58export const stringPascalCase = /*#__PURE__*/ converter((w) =>
59CC_TO_UP[w.charCodeAt(0)] + w.slice(1));