Adjust camelCase with simplified version (#1230)

* Adjust camelCase with simplified version

* Adjust count

* Adjust

* readability

* Ascii-only

* single-line callbacks

* CHANGELOG

* Dedupe string{Lower, Upper}First

* replacer -> fn
This commit is contained in:
Jaco
2021-11-22 16:12:29 +02:00
committed by GitHub
parent b390714285
commit 391ab49b8f
21 changed files with 187 additions and 102 deletions
@@ -4,7 +4,7 @@
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { blake2AsU8a } from '.';
describe('blake2AsU8a', (): void => {
@@ -61,7 +61,7 @@ describe('blake2AsU8a', (): void => {
});
describe.each([256, 512] as (256 | 512)[])('bitLength=$p', (bitLength): void => {
performanceTest(`blake2AsU8a, bitLength=${bitLength}`, 64000, (input, onlyJs) =>
performanceWasm(`blake2AsU8a, bitLength=${bitLength}`, 64000, (input, onlyJs) =>
blake2AsU8a(input, bitLength, null, onlyJs)
);
});
@@ -4,7 +4,7 @@
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { hmacShaAsU8a } from '.';
describe('hmacShaAsU8a', (): void => {
@@ -32,7 +32,7 @@ describe('hmacShaAsU8a', (): void => {
});
});
performanceTest(`hmacShaAsU8a, bitLength=${bitLength}`, 16000, (input, onlyJs) =>
performanceWasm(`hmacShaAsU8a, bitLength=${bitLength}`, 16000, (input, onlyJs) =>
hmacShaAsU8a(input, input, bitLength, onlyJs)
);
});
@@ -4,7 +4,7 @@
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { keccakAsU8a } from '.';
describe('keccakAsU8a', (): void => {
@@ -43,7 +43,7 @@ describe('keccakAsU8a', (): void => {
});
});
performanceTest(`keccakAsU8a, bitLength=${bitLength}`, 128000, (input, onlyJs) =>
performanceWasm(`keccakAsU8a, bitLength=${bitLength}`, 128000, (input, onlyJs) =>
keccakAsU8a(input, bitLength, onlyJs)
);
});
+2 -2
View File
@@ -4,7 +4,7 @@
import { stringToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { naclKeypairFromSeed, naclSign } from '.';
const PAIR = naclKeypairFromSeed(
@@ -30,7 +30,7 @@ describe('naclSign', (): void => {
});
});
performanceTest('naclSign', 250, (input, onlyJs) =>
performanceWasm('naclSign', 250, (input, onlyJs) =>
naclSign(input, PAIR, onlyJs)
);
});
@@ -3,7 +3,7 @@
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { DEFAULT_PARAMS } from './defaults';
import { scryptEncode } from '.';
@@ -30,7 +30,7 @@ describe('scryptEncode', (): void => {
});
});
performanceTest('scryptEncode', 2, (input, onlyJs) =>
performanceWasm('scryptEncode', 2, (input, onlyJs) =>
scryptEncode(input, input, undefined, onlyJs)
);
});
@@ -4,7 +4,7 @@
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { sha256AsU8a } from '.';
const TESTS = [
@@ -43,7 +43,7 @@ describe('sha256AsU8a', (): void => {
});
});
performanceTest('sha256AsU8a', 128000, (input, onlyJs) =>
performanceWasm('sha256AsU8a', 128000, (input, onlyJs) =>
sha256AsU8a(input, onlyJs)
);
});
@@ -3,7 +3,7 @@
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { sha512AsU8a } from '.';
describe('sha512AsU8a', (): void => {
@@ -23,7 +23,7 @@ describe('sha512AsU8a', (): void => {
});
});
performanceTest('sha512AsU8a', 64000, (input, onlyJs) =>
performanceWasm('sha512AsU8a', 64000, (input, onlyJs) =>
sha512AsU8a(input, onlyJs)
);
});
@@ -4,7 +4,7 @@
import { hexToU8a } from '@polkadot/util';
import { waitReady } from '@polkadot/wasm-crypto';
import { performanceTest } from '../../test/performance';
import { performanceWasm } from '../../test/performance';
import { xxhashAsU8a } from '.';
describe('xxhashAsU8a', (): void => {
@@ -38,7 +38,7 @@ describe('xxhashAsU8a', (): void => {
});
});
performanceTest('xxhashAsU8a', 8000, (input, onlyJs) =>
performanceWasm('xxhashAsU8a', 8000, (input, onlyJs) =>
xxhashAsU8a(input, 128, onlyJs)
);
});
+26 -18
View File
@@ -4,38 +4,46 @@
import { arrayRange } from '@polkadot/util';
import { randomAsU8a } from '@polkadot/util-crypto';
const GENERATED = arrayRange(64).map(() => randomAsU8a());
import { formatOps, performanceJs } from '../../util/test/performance';
function loop (count: number, onlyJs: boolean, exec: (input: Uint8Array, onlyJs: boolean) => unknown): number {
type ExecFn = (input: Uint8Array, onlyJs: boolean) => unknown;
const GENERATED = arrayRange(256).map(() => randomAsU8a());
function loop (count: number, onlyJs: boolean, exec: ExecFn): [number, unknown[]] {
const start = Date.now();
const results = new Array<unknown>(GENERATED.length);
for (let i = 0; i < count; i++) {
exec(GENERATED[i % GENERATED.length], onlyJs);
const result = exec(GENERATED[i % GENERATED.length], onlyJs);
if (i < GENERATED.length) {
results[i] = result;
}
}
return Date.now() - start;
return [Date.now() - start, results];
}
function perSecond (count: number, time: number): string {
const micro = (time * 1000) / count;
const ops = 1_000_000 / micro;
return `
${ops.toFixed(2).padStart(10)} ops/s
${micro.toFixed(2).padStart(10)} μs/op`;
}
export function performanceTest (name: string, count: number, exec: (input: Uint8Array, onlyJs: boolean) => unknown): void {
export function performanceWasm (name: string, count: number, exec: ExecFn): void {
it(`performance: ${name}`, (): void => {
const ws = loop(count, false, exec);
const js = loop(count, true, exec);
const [ws, rws] = loop(count, false, exec);
const [js, rjs] = loop(count, true, exec);
console.log(`
performance run for ${name} completed with ${count} iterations.
WebAssembly: ${ws.toString().padStart(10)} ms ${ws < js ? '(fastest)' : `(slowest, ${(ws / js).toFixed(2)}x)`}${perSecond(count, ws)}
${'WebAssembly:'.padStart(19)} ${ws.toString().padStart(15)} ms ${ws < js ? '(fastest)' : `(slowest, ${(ws / js).toFixed(2)}x)`}${formatOps(count, ws)}
JavaScript: ${js.toString().padStart(10)} ms ${ws > js ? '(fastest)' : `(slowest, ${(js / ws).toFixed(2)}x)`}${perSecond(count, js)}
${'JavaScript:'.padStart(19)} ${js.toString().padStart(15)} ms ${ws > js ? '(fastest)' : `(slowest, ${(js / ws).toFixed(2)}x)`}${formatOps(count, js)}
`);
const unmatched = rws.filter((r, i) =>
JSON.stringify(rjs[i]) !== JSON.stringify(r)
);
expect(unmatched.length).toEqual(0);
});
}
export { performanceJs };
-1
View File
@@ -48,7 +48,6 @@
"@polkadot/x-textencoder": "7.9.3-1",
"@types/bn.js": "^4.11.6",
"bn.js": "^4.12.0",
"camelcase": "^6.2.1",
"ip-regex": "^4.3.0"
}
}
+32 -3
View File
@@ -1,7 +1,34 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { stringCamelCase } from '.';
import { randomAsNumber } from '@polkadot/util-crypto';
import words from '@polkadot/util-crypto/mnemonic/bip39-en';
import { performanceJs } from '../../test/performance';
import { arrayRange } from '../array';
import { stringCamelCase, stringUpperFirst } from '.';
const SEPS = [' ', '_', '-'];
const randomWords = arrayRange(256).map((): [string] => {
let result = '';
for (let i = 0; i < 6; i++) {
let word = words[randomAsNumber() % words.length];
if (randomAsNumber() % 2) {
word = stringUpperFirst(word);
}
if (i === 0) {
result = word;
} else {
result += `${SEPS[randomAsNumber() % SEPS.length]}${word}`;
}
}
return [result];
});
describe('stringCamelCase', (): void => {
it('works correctly', (): void => {
@@ -12,7 +39,9 @@ describe('stringCamelCase', (): void => {
it('works correctly for String (class', (): void => {
expect(
stringCamelCase(String('Foo_bar-baz---test'))
).toBe('fooBarBazTest');
stringCamelCase(String('Foo_bar-baz---test-_ spaced'))
).toBe('fooBarBazTestSpaced');
});
performanceJs('stringCamelCase', 64000, randomWords, stringCamelCase);
});
+30 -5
View File
@@ -3,12 +3,37 @@
import type { AnyString } from '../types';
import camelcase from 'camelcase';
const RE_WHITE = /[-_ ]+/g;
const RE_WORDS = /(?:^\w|[A-Z]|\b\w)/g;
const RE_JOIN = /\s/g;
// Adapted from https://stackoverflow.com/a/2970667
//
// this is not as optimal as the original (we split into multiple), however
// it does pass the tests (which the original doesn't) and it is still 10+x
// improvement over the original camelcase npm package (at running)
//
// original: 20.88 μs/op
// this: 1.67 μs/op
//
// Caveat of this: only Ascii, but acceptable for the intended usecase
function converter (fn: (w: string, i: number) => string): (value: AnyString) => string {
return (value: AnyString): string =>
value
.toString()
.replace(RE_WHITE, ' ')
.replace(RE_WORDS, fn)
.replace(RE_JOIN, '');
}
/**
* @name stringCamelCase
* @summary Convert a dash/dot/underscore/space separated string/String to camelCase
* @summary Convert a dash/dot/underscore/space separated Ascii string/String to camelCase
*/
export function stringCamelCase (value: AnyString): string {
return camelcase(value.toString());
}
export const stringCamelCase = converter((w, i) => i ? w.toUpperCase() : w.toLowerCase());
/**
* @name stringPascalCase
* @summary Convert a dash/dot/underscore/space separated Ascii string/String to PascalCase
*/
export const stringPascalCase = converter((w) => w.toUpperCase());
+2 -4
View File
@@ -5,10 +5,8 @@
* @summary Utility methods to convert to work with `string` values
*/
export { stringCamelCase } from './camelCase';
export { stringLowerFirst } from './lowerFirst';
export { stringPascalCase } from './pascalCase';
export { stringCamelCase, stringPascalCase } from './camelCase';
export { stringLowerFirst, stringUpperFirst } from './lowerFirst';
export { stringShorten } from './shorten';
export { stringToHex } from './toHex';
export { stringToU8a } from './toU8a';
export { stringUpperFirst } from './upperFirst';
+24 -5
View File
@@ -3,6 +3,13 @@
import type { AnyString } from '../types';
function converter (fn: (value: string) => string): (value?: AnyString | null) => string {
return (value?: AnyString | null): string =>
value
? fn(value[0]) + value.slice(1)
: '';
}
/**
* @name stringLowerFirst
* @summary Lowercase the first letter of a string
@@ -17,8 +24,20 @@ import type { AnyString } from '../types';
* stringLowerFirst('ABC'); // => 'aBC'
* ```
*/
export function stringLowerFirst (value?: AnyString | null): string {
return value
? value.charAt(0).toLowerCase() + value.slice(1)
: '';
}
export const stringLowerFirst = converter((s) => s.toLowerCase());
/**
* @name stringUpperFirst
* @summary Uppercase the first letter of a string
* @description
* Lowercase the first letter of a string
* @example
* <BR>
*
* ```javascript
* import { stringUpperFirst } from '@polkadot/util';
*
* stringUpperFirst('abc'); // => 'Abc'
* ```
*/
export const stringUpperFirst = converter((s) => s.toUpperCase());
+2 -2
View File
@@ -12,7 +12,7 @@ describe('stringPascalCase', (): void => {
it('works correctly for String (class)', (): void => {
expect(
stringPascalCase(String('foo_bar-baz'))
).toBe('FooBarBaz');
stringPascalCase(String('foo_bar-- __baz Bob'))
).toBe('FooBarBazBob');
});
});
-16
View File
@@ -1,16 +0,0 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AnyString } from '../types';
import camelcase from 'camelcase';
const OPTS = { pascalCase: true };
/**
* @name stringPascalCase
* @summary Convert a dash/dot/underscore/space separated string/String to PascalCase
*/
export function stringPascalCase (value: AnyString): string {
return camelcase(value.toString(), OPTS);
}
+3 -5
View File
@@ -18,9 +18,7 @@ import type { AnyString } from '../types';
* ```
*/
export function stringShorten (value: AnyString, prefixLength = 6): string {
if (value.length <= 2 + 2 * prefixLength) {
return value.toString();
}
return `${value.substr(0, prefixLength)}…${value.slice(-prefixLength)}`;
return value.length <= 2 + 2 * prefixLength
? value.toString()
: `${value.substr(0, prefixLength)}…${value.slice(-prefixLength)}`;
}
-25
View File
@@ -1,25 +0,0 @@
// Copyright 2017-2021 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { AnyString } from '../types';
/**
* @name stringUpperFirst
* @summary Lowercase the first letter of a string
* @description
* Lowercase the first letter of a string
* @example
* <BR>
*
* ```javascript
* import { stringUpperFirst } from '@polkadot/util';
*
* stringUpperFirst('abc'); // => 'Abc'
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function stringUpperFirst (value?: AnyString | null): string {
return value
? value.charAt(0).toUpperCase() + value.slice(1)
: '';
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2017-2021 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { formatDecimal } from '@polkadot/util';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ExecFn = (...params: any[]) => unknown;
function loop (count: number, inputs: unknown[][], exec: ExecFn): number {
const start = Date.now();
for (let i = 0; i < count; i++) {
exec(...inputs[i % inputs.length]);
}
return Date.now() - start;
}
export function formatFixed (value: number): string {
const [a, b] = value.toFixed(2).split('.');
return [formatDecimal(a), b].join('.');
}
export function formatOps (count: number, time: number): string {
const micro = (time * 1000) / count;
const ops = 1_000_000 / micro;
return `
${formatFixed(ops).padStart(15 + 20)} ops/s
${formatFixed(micro).padStart(15 + 20)} μs/op`;
}
export function performanceJs (name: string, count: number, inputs: unknown[][], exec: ExecFn): void {
it(`performance: ${name}`, (): void => {
const time = loop(count, inputs, exec);
console.log(`
performance run for ${name} completed with ${count} iterations.
${'JavaScript:'.padStart(19)} ${time.toString().padStart(15)} ms${formatOps(count, time)}
`);
});
}