UNPKG

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