UNPKG

1.88 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.stringPascalCase = exports.stringCamelCase = void 0;
7
8// Copyright 2017-2022 @polkadot/util authors & contributors
9// SPDX-License-Identifier: Apache-2.0
10// Inspired from https://stackoverflow.com/a/2970667
11//
12// this is not as optimal as the original answer (we split into multiple),
13// however it does pass the tests (which the original doesn't) and it is still
14// a 10+x improvement over the original camelcase npm package (at running)
15//
16// original: 20.88 μs/op
17// this: 2.86 μs/op
18//
19// Caveat of this: only Ascii, but acceptable for the intended usecase
20function converter(fn) {
21 const format = (w, i) => fn(w[0], i) + w.slice(1);
22
23 return value => value.toString() // replace all seperators (including consequtive) with spaces
24 .replace(/[-_., ]+/g, ' ') // we don't want leading or trailing spaces
25 .trim() // split into words
26 .split(' ') // apply the formatting
27 .map((w, i) => format(w.toUpperCase() === w // all full uppercase + letters are changed to lowercase
28 ? w.toLowerCase() // all consecutive capitals + letters are changed to lowercase
29 // e.g. UUID64 -> uuid64, while preserving splits, eg. NFTOrder -> nftOrder
30 : w.replace(/^[A-Z0-9]{2,}[^a-z]/, w => w.slice(0, w.length - 1).toLowerCase() + w.slice(-1).toUpperCase()), i)) // combine into a single word
31 .join('');
32}
33/**
34 * @name stringCamelCase
35 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to camelCase
36 */
37
38
39const stringCamelCase = converter((w, i) => i ? w.toUpperCase() : w.toLowerCase());
40/**
41 * @name stringPascalCase
42 * @summary Convert a dash/dot/underscore/space separated Ascii string/String to PascalCase
43 */
44
45exports.stringCamelCase = stringCamelCase;
46const stringPascalCase = converter(w => w.toUpperCase());
47exports.stringPascalCase = stringPascalCase;
\No newline at end of file