aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLeyla Jähnig <[email protected]>2022-10-18 19:29:43 +0200
committerGitHub <[email protected]>2022-10-18 19:29:43 +0200
commit79858fea203bce7ada9e9bcc7751f6ab25123977 (patch)
tree440e365a55814763662392fca10c899acfa2c468 /src
parentc977dbc79da0589557205ad2a95befa1cd6a9dea (diff)
downloadfaker-79858fea203bce7ada9e9bcc7751f6ab25123977.tar.xz
faker-79858fea203bce7ada9e9bcc7751f6ab25123977.zip
feat(string): move methods to new module (#1155)
Co-authored-by: Eric Cheng <[email protected]> Co-authored-by: ST-DDT <[email protected]> Co-authored-by: Shinigami92 <[email protected]>
Diffstat (limited to 'src')
-rw-r--r--src/faker.ts2
-rw-r--r--src/index.ts1
-rw-r--r--src/modules/color/index.ts2
-rw-r--r--src/modules/database/index.ts4
-rw-r--r--src/modules/datatype/index.ts105
-rw-r--r--src/modules/finance/index.ts18
-rw-r--r--src/modules/git/index.ts8
-rw-r--r--src/modules/random/index.ts262
-rw-r--r--src/modules/string/index.ts425
-rw-r--r--src/modules/vehicle/index.ts19
10 files changed, 547 insertions, 299 deletions
diff --git a/src/faker.ts b/src/faker.ts
index 5c2f7e79..3452ae49 100644
--- a/src/faker.ts
+++ b/src/faker.ts
@@ -24,6 +24,7 @@ import { PersonModule } from './modules/person';
import { PhoneModule } from './modules/phone';
import { RandomModule } from './modules/random';
import { ScienceModule } from './modules/science';
+import { StringModule } from './modules/string';
import { SystemModule } from './modules/system';
import { VehicleModule } from './modules/vehicle';
import { WordModule } from './modules/word';
@@ -102,6 +103,7 @@ export class Faker {
readonly person: PersonModule = new PersonModule(this);
readonly phone: PhoneModule = new PhoneModule(this);
readonly science: ScienceModule = new ScienceModule(this);
+ readonly string: StringModule = new StringModule(this);
readonly system: SystemModule = new SystemModule(this);
readonly vehicle: VehicleModule = new VehicleModule(this);
readonly word: WordModule = new WordModule(this);
diff --git a/src/index.ts b/src/index.ts
index bbd419bd..f0b87953 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -67,6 +67,7 @@ export type {
export type { PhoneModule } from './modules/phone';
export type { RandomModule } from './modules/random';
export type { ChemicalElement, ScienceModule, Unit } from './modules/science';
+export type { StringModule } from './modules/string';
export type { SystemModule } from './modules/system';
export type { VehicleModule } from './modules/vehicle';
export type { WordModule } from './modules/word';
diff --git a/src/modules/color/index.ts b/src/modules/color/index.ts
index c6dbb0a4..4fd79a06 100644
--- a/src/modules/color/index.ts
+++ b/src/modules/color/index.ts
@@ -313,7 +313,7 @@ export class ColorModule {
let color: string | number[];
let cssFunction: CSSFunction = 'rgb';
if (format === 'hex') {
- color = this.faker.datatype.hexadecimal({
+ color = this.faker.string.hexadecimal({
length: includeAlpha ? 8 : 6,
prefix: '',
});
diff --git a/src/modules/database/index.ts b/src/modules/database/index.ts
index 8a4291f9..d0985c53 100644
--- a/src/modules/database/index.ts
+++ b/src/modules/database/index.ts
@@ -79,9 +79,9 @@ export class DatabaseModule {
* @since 6.2.0
*/
mongodbObjectId(): string {
- return this.faker.datatype.hexadecimal({
+ return this.faker.string.hexadecimal({
length: 24,
- case: 'lower',
+ casing: 'lower',
prefix: '',
});
}
diff --git a/src/modules/datatype/index.ts b/src/modules/datatype/index.ts
index 4c522d53..41c5c3e4 100644
--- a/src/modules/datatype/index.ts
+++ b/src/modules/datatype/index.ts
@@ -1,5 +1,6 @@
import type { Faker } from '../..';
import { FakerError } from '../../errors/faker-error';
+import { deprecated } from '../../internal/deprecated';
import type { MersenneModule } from '../../internal/mersenne/mersenne';
/**
@@ -145,48 +146,46 @@ export class DatatypeModule {
*
* @param length Length of the generated string. Max length is `2^20`. Defaults to `10`.
*
+ * @see faker.string.sample()
+ *
* @example
* faker.datatype.string() // 'Zo!.:*e>wR'
* faker.datatype.string(5) // '6Bye8'
*
* @since 5.5.0
+ *
+ * @deprecated Use faker.string.sample() instead.
*/
string(length = 10): string {
- const maxLength = Math.pow(2, 20);
- if (length >= maxLength) {
- length = maxLength;
- }
-
- const charCodeOption = {
- min: 33,
- max: 125,
- };
-
- let returnString = '';
-
- for (let i = 0; i < length; i++) {
- returnString += String.fromCharCode(this.number(charCodeOption));
- }
-
- return returnString;
+ deprecated({
+ deprecated: 'faker.datatype.string()',
+ proposed: 'faker.string.sample()',
+ since: '8.0',
+ until: '9.0',
+ });
+ return this.faker.string.sample(length);
}
/**
* Returns a UUID v4 ([Universally Unique Identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)).
*
+ * @see faker.string.uuid()
+ *
* @example
* faker.datatype.uuid() // '4136cd0b-d90b-4af7-b485-5d1ded8db252'
*
* @since 5.5.0
+ *
+ * @deprecated Use faker.string.uuid() instead.
*/
uuid(): string {
- const RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
- const replacePlaceholders = (placeholder) => {
- const random = this.number({ min: 0, max: 15 });
- const value = placeholder === 'x' ? random : (random & 0x3) | 0x8;
- return value.toString(16);
- };
- return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
+ deprecated({
+ deprecated: 'faker.datatype.uuid()',
+ proposed: 'faker.string.uuid()',
+ since: '8.0',
+ until: '9.0',
+ });
+ return this.faker.string.uuid();
}
/**
@@ -209,6 +208,8 @@ export class DatatypeModule {
* @param options.prefix Prefix for the generated number. Defaults to `'0x'`.
* @param options.case Case of the generated number. Defaults to `'mixed'`.
*
+ * @see faker.string.hexadecimal()
+ *
* @example
* faker.datatype.hexadecimal() // '0xB'
* faker.datatype.hexadecimal({ length: 10 }) // '0xaE13d044cB'
@@ -220,6 +221,8 @@ export class DatatypeModule {
* faker.datatype.hexadecimal({ length: 10, prefix: '0x', case: 'mixed' }) // '0xAdE330a4D1'
*
* @since 6.1.2
+ *
+ * @deprecated Use `faker.string.hexadecimal()` instead.
*/
hexadecimal(
options: {
@@ -228,44 +231,13 @@ export class DatatypeModule {
case?: 'lower' | 'upper' | 'mixed';
} = {}
): string {
- const { length = 1, prefix = '0x', case: letterCase = 'mixed' } = options;
-
- let wholeString = '';
-
- for (let i = 0; i < length; i++) {
- wholeString += this.faker.helpers.arrayElement([
- '0',
- '1',
- '2',
- '3',
- '4',
- '5',
- '6',
- '7',
- '8',
- '9',
- 'a',
- 'b',
- 'c',
- 'd',
- 'e',
- 'f',
- 'A',
- 'B',
- 'C',
- 'D',
- 'E',
- 'F',
- ]);
- }
-
- if (letterCase === 'upper') {
- wholeString = wholeString.toUpperCase();
- } else if (letterCase === 'lower') {
- wholeString = wholeString.toLowerCase();
- }
-
- return `${prefix}${wholeString}`;
+ deprecated({
+ deprecated: 'faker.datatype.hexadecimal()',
+ proposed: 'faker.string.hexadecimal()',
+ since: '8.0',
+ until: '9.0',
+ });
+ return this.faker.string.hexadecimal({ ...options, casing: options.case });
}
/**
@@ -281,7 +253,9 @@ export class DatatypeModule {
const returnObject: Record<string, string | number> = {};
properties.forEach((prop) => {
- returnObject[prop] = this.boolean() ? this.string() : this.number();
+ returnObject[prop] = this.boolean()
+ ? this.faker.string.sample()
+ : this.number();
});
return JSON.stringify(returnObject);
@@ -300,7 +274,7 @@ export class DatatypeModule {
*/
array(length = 10): Array<string | number> {
return Array.from<string | number>({ length }).map(() =>
- this.boolean() ? this.string() : this.number()
+ this.boolean() ? this.faker.string.sample() : this.number()
);
}
@@ -356,7 +330,8 @@ export class DatatypeModule {
const offset =
BigInt(
- this.faker.random.numeric(delta.toString(10).length, {
+ this.faker.string.numeric({
+ length: delta.toString(10).length,
allowLeadingZeros: true,
})
) %
diff --git a/src/modules/finance/index.ts b/src/modules/finance/index.ts
index 7612eedb..3c60ec41 100644
--- a/src/modules/finance/index.ts
+++ b/src/modules/finance/index.ts
@@ -235,7 +235,8 @@ export class FinanceModule {
let address = this.faker.helpers.arrayElement(['1', '3']);
- address += this.faker.random.alphaNumeric(addressLength, {
+ address += this.faker.string.alphanumeric({
+ length: addressLength,
casing: 'mixed',
bannedChars: '0OIl',
});
@@ -353,9 +354,9 @@ export class FinanceModule {
* @since 5.0.0
*/
ethereumAddress(): string {
- const address = this.faker.datatype.hexadecimal({
+ const address = this.faker.string.hexadecimal({
length: 40,
- case: 'lower',
+ casing: 'lower',
});
return address;
}
@@ -446,15 +447,18 @@ export class FinanceModule {
): string {
const { includeBranchCode = this.faker.datatype.boolean() } = options;
- const bankIdentifier = this.faker.random.alpha({
- count: 4,
+ const bankIdentifier = this.faker.string.alpha({
+ length: 4,
casing: 'upper',
});
const countryCode = this.faker.helpers.arrayElement(iban.iso3166);
- const locationCode = this.faker.random.alphaNumeric(2, { casing: 'upper' });
+ const locationCode = this.faker.string.alphanumeric({
+ length: 2,
+ casing: 'upper',
+ });
const branchCode = includeBranchCode
? this.faker.datatype.boolean()
- ? this.faker.random.alphaNumeric(3, { casing: 'upper' })
+ ? this.faker.string.alphanumeric({ length: 3, casing: 'upper' })
: 'XXX'
: '';
diff --git a/src/modules/git/index.ts b/src/modules/git/index.ts
index cd9e7de0..78cf0c68 100644
--- a/src/modules/git/index.ts
+++ b/src/modules/git/index.ts
@@ -100,9 +100,9 @@ export class GitModule {
* @since 5.0.0
*/
commitSha(): string {
- return this.faker.datatype.hexadecimal({
+ return this.faker.string.hexadecimal({
length: 40,
- case: 'lower',
+ casing: 'lower',
prefix: '',
});
}
@@ -116,9 +116,9 @@ export class GitModule {
* @since 5.0.0
*/
shortSha(): string {
- return this.faker.datatype.hexadecimal({
+ return this.faker.string.hexadecimal({
length: 7,
- case: 'lower',
+ casing: 'lower',
prefix: '',
});
}
diff --git a/src/modules/random/index.ts b/src/modules/random/index.ts
index e79a2e70..7f567edf 100644
--- a/src/modules/random/index.ts
+++ b/src/modules/random/index.ts
@@ -1,97 +1,12 @@
import type { Faker } from '../..';
-import { FakerError } from '../../errors/faker-error';
+import { deprecated } from '../../internal/deprecated';
import type { LiteralUnion } from '../../utils/types';
-
-export type Casing = 'upper' | 'lower' | 'mixed';
-
-const UPPER_CHARS: readonly string[] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
-const LOWER_CHARS: readonly string[] = 'abcdefghijklmnopqrstuvwxyz'.split('');
-const DIGIT_CHARS: readonly string[] = '0123456789'.split('');
-
-export type LowerAlphaChar =
- | 'a'
- | 'b'
- | 'c'
- | 'd'
- | 'e'
- | 'f'
- | 'g'
- | 'h'
- | 'i'
- | 'j'
- | 'k'
- | 'l'
- | 'm'
- | 'n'
- | 'o'
- | 'p'
- | 'q'
- | 'r'
- | 's'
- | 't'
- | 'u'
- | 'v'
- | 'w'
- | 'x'
- | 'y'
- | 'z';
-
-export type UpperAlphaChar =
- | 'A'
- | 'B'
- | 'C'
- | 'D'
- | 'E'
- | 'F'
- | 'G'
- | 'H'
- | 'I'
- | 'J'
- | 'K'
- | 'L'
- | 'M'
- | 'N'
- | 'O'
- | 'P'
- | 'Q'
- | 'R'
- | 'S'
- | 'T'
- | 'U'
- | 'V'
- | 'W'
- | 'X'
- | 'Y'
- | 'Z';
-
-export type NumericChar =
- | '0'
- | '1'
- | '2'
- | '3'
- | '4'
- | '5'
- | '6'
- | '7'
- | '8'
- | '9';
-
-export type AlphaChar = LowerAlphaChar | UpperAlphaChar;
-export type AlphaNumericChar = AlphaChar | NumericChar;
-
-/**
- * Method to reduce array of characters.
- *
- * @param arr existing array of characters
- * @param values array of characters which should be removed
- * @returns new array without banned characters
- */
-function arrayRemove<T>(arr: T[], values: readonly T[]): T[] {
- values.forEach((value) => {
- arr = arr.filter((ele) => ele !== value);
- });
- return arr;
-}
+import type {
+ AlphaChar,
+ AlphaNumericChar,
+ Casing,
+ NumericChar,
+} from '../string';
/**
* Generates random values of different kinds.
@@ -267,12 +182,16 @@ export class RandomModule {
* @param options.casing The casing of the characters. Defaults to `'mixed'`.
* @param options.bannedChars An array with characters to exclude. Defaults to `[]`.
*
+ * @see faker.string.alpha()
+ *
* @example
* faker.random.alpha() // 'b'
* faker.random.alpha(10) // 'qccrabobaf'
* faker.random.alpha({ count: 5, casing: 'upper', bannedChars: ['A'] }) // 'DTCIC'
*
* @since 5.0.0
+ *
+ * @deprecated Use faker.string.alpha() instead.
*/
alpha(
options:
@@ -283,50 +202,16 @@ export class RandomModule {
bannedChars?: readonly LiteralUnion<AlphaChar>[] | string;
} = {}
): string {
+ deprecated({
+ deprecated: 'faker.random.alpha()',
+ proposed: 'faker.string.alpha()',
+ since: '8.0',
+ until: '9.0',
+ });
if (typeof options === 'number') {
- options = {
- count: options,
- };
- }
-
- const { count = 1 } = options;
- let { bannedChars = [] } = options;
-
- if (typeof bannedChars === 'string') {
- bannedChars = bannedChars.split('');
- }
-
- if (count <= 0) {
- return '';
- }
-
- const { casing = 'mixed' } = options;
-
- let charsArray: string[];
- switch (casing) {
- case 'upper':
- charsArray = [...UPPER_CHARS];
- break;
- case 'lower':
- charsArray = [...LOWER_CHARS];
- break;
- case 'mixed':
- default:
- charsArray = [...LOWER_CHARS, ...UPPER_CHARS];
- break;
+ return this.faker.string.alpha(options);
}
-
- charsArray = arrayRemove(charsArray, bannedChars);
-
- if (charsArray.length === 0) {
- throw new FakerError(
- 'Unable to generate string, because all possible characters are banned.'
- );
- }
-
- return Array.from({ length: count }, () =>
- this.faker.helpers.arrayElement(charsArray)
- ).join('');
+ return this.faker.string.alpha({ ...options, length: options.count });
}
/**
@@ -337,12 +222,16 @@ export class RandomModule {
* @param options.casing The casing of the characters. Defaults to `'lower'`.
* @param options.bannedChars An array of characters and digits which should be banned in the generated string. Defaults to `[]`.
*
+ * @see faker.string.alphanumeric()
+ *
* @example
* faker.random.alphaNumeric() // '2'
* faker.random.alphaNumeric(5) // '3e5v7'
* faker.random.alphaNumeric(5, { bannedChars: ["a"] }) // 'xszlm'
*
* @since 3.1.0
+ *
+ * @deprecated Use faker.string.alphanumeric() instead.
*/
alphaNumeric(
count: number = 1,
@@ -351,46 +240,17 @@ export class RandomModule {
bannedChars?: readonly LiteralUnion<AlphaNumericChar>[] | string;
} = {}
): string {
- if (count <= 0) {
- return '';
- }
-
- const {
- // Switch to 'mixed' with v8.0
- casing = 'lower',
- } = options;
- let { bannedChars = [] } = options;
-
- if (typeof bannedChars === 'string') {
- bannedChars = bannedChars.split('');
- }
-
- let charsArray = [...DIGIT_CHARS];
-
- switch (casing) {
- case 'upper':
- charsArray.push(...UPPER_CHARS);
- break;
- case 'lower':
- charsArray.push(...LOWER_CHARS);
- break;
- case 'mixed':
- default:
- charsArray.push(...LOWER_CHARS, ...UPPER_CHARS);
- break;
- }
-
- charsArray = arrayRemove(charsArray, bannedChars);
-
- if (charsArray.length === 0) {
- throw new FakerError(
- 'Unable to generate string, because all possible characters are banned.'
- );
- }
-
- return Array.from({ length: count }, () =>
- this.faker.helpers.arrayElement(charsArray)
- ).join('');
+ deprecated({
+ deprecated: 'faker.random.alphaNumeric()',
+ proposed: 'faker.string.alphanumeric()',
+ since: '8.0',
+ until: '9.0',
+ });
+ return this.faker.string.alphanumeric({
+ length: count,
+ bannedChars: options.bannedChars,
+ casing: options.casing,
+ });
}
/**
@@ -401,6 +261,8 @@ export class RandomModule {
* @param options.allowLeadingZeros If true, leading zeros will be allowed. Defaults to `false`.
* @param options.bannedDigits An array of digits which should be banned in the generated string. Defaults to `[]`.
*
+ * @see faker.string.numeric()
+ *
* @example
* faker.random.numeric() // '2'
* faker.random.numeric(5) // '31507'
@@ -409,6 +271,8 @@ export class RandomModule {
* faker.random.numeric(6, { bannedDigits: ['0'] }) // '943228'
*
* @since 6.3.0
+ *
+ * @deprecated Use faker.string.numeric() instead.
*/
numeric(
length: number = 1,
@@ -417,44 +281,16 @@ export class RandomModule {
bannedDigits?: readonly LiteralUnion<NumericChar>[] | string;
} = {}
): string {
- if (length <= 0) {
- return '';
- }
-
- const { allowLeadingZeros = false } = options;
- let { bannedDigits = [] } = options;
-
- if (typeof bannedDigits === 'string') {
- bannedDigits = bannedDigits.split('');
- }
-
- const allowedDigits = DIGIT_CHARS.filter(
- (digit) => !bannedDigits.includes(digit)
- );
-
- if (
- allowedDigits.length === 0 ||
- (allowedDigits.length === 1 &&
- !allowLeadingZeros &&
- allowedDigits[0] === '0')
- ) {
- throw new FakerError(
- 'Unable to generate numeric string, because all possible digits are banned.'
- );
- }
-
- let result = '';
-
- if (!allowLeadingZeros && !bannedDigits.includes('0')) {
- result += this.faker.helpers.arrayElement(
- allowedDigits.filter((digit) => digit !== '0')
- );
- }
-
- while (result.length < length) {
- result += this.faker.helpers.arrayElement(allowedDigits);
- }
-
- return result;
+ deprecated({
+ deprecated: 'faker.random.numeric()',
+ proposed: 'faker.string.numeric()',
+ since: '8.0',
+ until: '9.0',
+ });
+ return this.faker.string.numeric({
+ length,
+ allowLeadingZeros: options.allowLeadingZeros,
+ bannedDigits: options.bannedDigits,
+ });
}
}
diff --git a/src/modules/string/index.ts b/src/modules/string/index.ts
new file mode 100644
index 00000000..a02fea0f
--- /dev/null
+++ b/src/modules/string/index.ts
@@ -0,0 +1,425 @@
+import type { Faker } from '../..';
+import { FakerError } from '../../errors/faker-error';
+import type { LiteralUnion } from '../../utils/types';
+
+export type Casing = 'upper' | 'lower' | 'mixed';
+
+const UPPER_CHARS: readonly string[] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
+const LOWER_CHARS: readonly string[] = 'abcdefghijklmnopqrstuvwxyz'.split('');
+const DIGIT_CHARS: readonly string[] = '0123456789'.split('');
+
+export type LowerAlphaChar =
+ | 'a'
+ | 'b'
+ | 'c'
+ | 'd'
+ | 'e'
+ | 'f'
+ | 'g'
+ | 'h'
+ | 'i'
+ | 'j'
+ | 'k'
+ | 'l'
+ | 'm'
+ | 'n'
+ | 'o'
+ | 'p'
+ | 'q'
+ | 'r'
+ | 's'
+ | 't'
+ | 'u'
+ | 'v'
+ | 'w'
+ | 'x'
+ | 'y'
+ | 'z';
+
+export type UpperAlphaChar =
+ | 'A'
+ | 'B'
+ | 'C'
+ | 'D'
+ | 'E'
+ | 'F'
+ | 'G'
+ | 'H'
+ | 'I'
+ | 'J'
+ | 'K'
+ | 'L'
+ | 'M'
+ | 'N'
+ | 'O'
+ | 'P'
+ | 'Q'
+ | 'R'
+ | 'S'
+ | 'T'
+ | 'U'
+ | 'V'
+ | 'W'
+ | 'X'
+ | 'Y'
+ | 'Z';
+
+export type NumericChar =
+ | '0'
+ | '1'
+ | '2'
+ | '3'
+ | '4'
+ | '5'
+ | '6'
+ | '7'
+ | '8'
+ | '9';
+
+export type AlphaChar = LowerAlphaChar | UpperAlphaChar;
+export type AlphaNumericChar = AlphaChar | NumericChar;
+
+const SAMPLE_MAX_LENGTH = Math.pow(2, 20);
+
+/**
+ * Module to generate string related entries.
+ */
+export class StringModule {
+ constructor(private readonly faker: Faker) {
+ // Bind `this` so namespaced is working correctly
+ for (const name of Object.getOwnPropertyNames(StringModule.prototype)) {
+ if (name === 'constructor' || typeof this[name] !== 'function') {
+ continue;
+ }
+ this[name] = this[name].bind(this);
+ }
+ }
+
+ /**
+ * Generating a string consisting of letters in the English alphabet.
+ *
+ * @param options Either the number of characters or an options instance. Defaults to `{ length: 1, casing: 'lower', bannedChars: [] }`.
+ * @param options.length The number of characters to generate. Defaults to `1`.
+ * @param options.casing The casing of the characters. Defaults to `'lower'`.
+ * @param options.bannedChars An array with characters to exclude. Defaults to `[]`.
+ *
+ * @example
+ * faker.string.alpha() // 'b'
+ * faker.string.alpha(10) // 'qccrabobaf'
+ * faker.string.alpha({ length: 5, casing: 'upper', bannedChars: ['A'] }) // 'DTCIC'
+ *
+ * @since 8.0.0
+ */
+ alpha(
+ options:
+ | number
+ | {
+ length?: number;
+ casing?: Casing;
+ bannedChars?: readonly LiteralUnion<AlphaChar>[] | string;
+ } = {}
+ ): string {
+ if (typeof options === 'number') {
+ options = {
+ length: options,
+ };
+ }
+
+ const { length = 1, casing = 'mixed' } = options;
+ let { bannedChars = [] } = options;
+
+ if (typeof bannedChars === 'string') {
+ bannedChars = bannedChars.split('');
+ }
+
+ if (length <= 0) {
+ return '';
+ }
+
+ let charsArray: string[];
+ switch (casing) {
+ case 'upper':
+ charsArray = [...UPPER_CHARS];
+ break;
+ case 'lower':
+ charsArray = [...LOWER_CHARS];
+ break;
+ case 'mixed':
+ default:
+ charsArray = [...LOWER_CHARS, ...UPPER_CHARS];
+ break;
+ }
+
+ charsArray = charsArray.filter((elem) => !bannedChars.includes(elem));
+
+ if (charsArray.length === 0) {
+ throw new FakerError(
+ 'Unable to generate string, because all possible characters are banned.'
+ );
+ }
+
+ return Array.from({ length }, () =>
+ this.faker.helpers.arrayElement(charsArray)
+ ).join('');
+ }
+
+ /**
+ * Generating a string consisting of alpha characters and digits.
+ *
+ * @param options Either the number of characters or an options instance. Defaults to `{ length: 1, casing: 'mixed', bannedChars: [] }`.
+ * @param options.length The number of characters and digits to generate. Defaults to `1`.
+ * @param options.casing The casing of the characters. Defaults to `'mixed'`.
+ * @param options.bannedChars An array of characters and digits which should be banned in the generated string. Defaults to `[]`.
+ *
+ * @example
+ * faker.string.alphanumeric() // '2'
+ * faker.string.alphanumeric(5) // '3e5v7'
+ * faker.string.alphanumeric({ length: 5, bannedChars: ["a"] }) // 'xszlm'
+ *
+ * @since 8.0.0
+ */
+ alphanumeric(
+ options:
+ | number
+ | {
+ length?: number;
+ casing?: Casing;
+ bannedChars?: readonly LiteralUnion<AlphaNumericChar>[] | string;
+ } = {}
+ ): string {
+ if (typeof options === 'number') {
+ options = {
+ length: options,
+ };
+ }
+
+ const { length = 1, casing = 'mixed' } = options;
+
+ if (length <= 0) {
+ return '';
+ }
+
+ let { bannedChars = [] } = options;
+
+ if (typeof bannedChars === 'string') {
+ bannedChars = bannedChars.split('');
+ }
+
+ let charsArray = [...DIGIT_CHARS];
+
+ switch (casing) {
+ case 'upper':
+ charsArray.push(...UPPER_CHARS);
+ break;
+ case 'lower':
+ charsArray.push(...LOWER_CHARS);
+ break;
+ case 'mixed':
+ default:
+ charsArray.push(...LOWER_CHARS, ...UPPER_CHARS);
+ break;
+ }
+
+ charsArray = charsArray.filter((elem) => !bannedChars.includes(elem));
+
+ if (charsArray.length === 0) {
+ throw new FakerError(
+ 'Unable to generate string, because all possible characters are banned.'
+ );
+ }
+
+ return Array.from({ length }, () =>
+ this.faker.helpers.arrayElement(charsArray)
+ ).join('');
+ }
+
+ /**
+ * Returns a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) string.
+ *
+ * @param options The optional options object.
+ * @param options.length Length of the generated number. Defaults to `1`.
+ * @param options.casing Casing of the generated number. Defaults to `'mixed'`.
+ * @param options.prefix Prefix for the generated number. Defaults to `'0x'`.
+ *
+ * @example
+ * faker.string.hexadecimal() // '0xB'
+ * faker.string.hexadecimal({ length: 10 }) // '0xaE13d044cB'
+ * faker.string.hexadecimal({ prefix: '0x' }) // '0xE'
+ * faker.string.hexadecimal({ casing: 'lower' }) // '0xf'
+ * faker.string.hexadecimal({ length: 10, prefix: '#' }) // '#f12a974eB1'
+ * faker.string.hexadecimal({ length: 10, casing: 'upper' }) // '0xE3F38014FB'
+ * faker.string.hexadecimal({ casing: 'lower', prefix: '' }) // 'd'
+ * faker.string.hexadecimal({ length: 10, casing: 'mixed', prefix: '0x' }) // '0xAdE330a4D1'
+ *
+ * @since 8.0.0
+ */
+ hexadecimal(
+ options: {
+ length?: number;
+ casing?: Casing;
+ prefix?: string;
+ } = {}
+ ): string {
+ const { length = 1, casing = 'mixed', prefix = '0x' } = options;
+
+ let wholeString = '';
+
+ for (let i = 0; i < length; i++) {
+ wholeString += this.faker.helpers.arrayElement([
+ '0',
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ '6',
+ '7',
+ '8',
+ '9',
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'A',
+ 'B',
+ 'C',
+ 'D',
+ 'E',
+ 'F',
+ ]);
+ }
+
+ if (casing === 'upper') {
+ wholeString = wholeString.toUpperCase();
+ } else if (casing === 'lower') {
+ wholeString = wholeString.toLowerCase();
+ }
+
+ return `${prefix}${wholeString}`;
+ }
+
+ /**
+ * Generates a given length string of digits.
+ *
+ * @param options Either the number of characters or the options to use. Defaults to `{ length: 1, allowLeadingZeros = false, bannedDigits = [] }`.
+ * @param options.length The number of digits to generate. Defaults to `1`.
+ * @param options.allowLeadingZeros If true, leading zeros will be allowed. Defaults to `false`.
+ * @param options.bannedDigits An array of digits which should be banned in the generated string. Defaults to `[]`.
+ *
+ * @example
+ * faker.string.numeric() // '2'
+ * faker.string.numeric(5) // '31507'
+ * faker.string.numeric(42) // '56434563150765416546479875435481513188548'
+ * faker.string.numeric({ length: 42, allowLeadingZeros: true }) // '00564846278453876543517840713421451546115'
+ * faker.string.numeric({ length: 6, bannedDigits: ['0'] }) // '943228'
+ *
+ * @since 8.0.0
+ */
+ numeric(
+ options:
+ | number
+ | {
+ length?: number;
+ allowLeadingZeros?: boolean;
+ bannedDigits?: readonly LiteralUnion<NumericChar>[] | string;
+ } = {}
+ ): string {
+ if (typeof options === 'number') {
+ options = {
+ length: options,
+ };
+ }
+
+ const { length = 1, allowLeadingZeros = false } = options;
+ if (length <= 0) {
+ return '';
+ }
+
+ let { bannedDigits = [] } = options;
+
+ if (typeof bannedDigits === 'string') {
+ bannedDigits = bannedDigits.split('');
+ }
+
+ const allowedDigits = DIGIT_CHARS.filter(
+ (digit) => !bannedDigits.includes(digit)
+ );
+
+ if (
+ allowedDigits.length === 0 ||
+ (allowedDigits.length === 1 &&
+ !allowLeadingZeros &&
+ allowedDigits[0] === '0')
+ ) {
+ throw new FakerError(
+ 'Unable to generate numeric string, because all possible digits are banned.'
+ );
+ }
+
+ let result = '';
+
+ if (!allowLeadingZeros && !bannedDigits.includes('0')) {
+ result += this.faker.helpers.arrayElement(
+ allowedDigits.filter((digit) => digit !== '0')
+ );
+ }
+
+ while (result.length < length) {
+ result += this.faker.helpers.arrayElement(allowedDigits);
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns a string containing UTF-16 chars between 33 and 125 (`!` to `}`).
+ *
+ * @param length Length of the generated string. Max length is `2^20`. Defaults to `10`.
+ *
+ * @example
+ * faker.string.sample() // 'Zo!.:*e>wR'
+ * faker.string.sample(5) // '6Bye8'
+ *
+ * @since 8.0.0
+ */
+ sample(length = 10): string {
+ if (length >= SAMPLE_MAX_LENGTH) {
+ length = SAMPLE_MAX_LENGTH;
+ }
+
+ const charCodeOption = {
+ min: 33,
+ max: 125,
+ };
+
+ let returnString = '';
+
+ while (returnString.length < length) {
+ returnString += String.fromCharCode(
+ this.faker.datatype.number(charCodeOption)
+ );
+ }
+
+ return returnString;
+ }
+
+ /**
+ * Returns a UUID v4 ([Universally Unique Identifier](https://en.wikipedia.org/wiki/Universally_unique_identifier)).
+ *
+ * @example
+ * faker.string.uuid() // '4136cd0b-d90b-4af7-b485-5d1ded8db252'
+ *
+ * @since 8.0.0
+ */
+ uuid(): string {
+ const RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
+ const replacePlaceholders = (placeholder: string) => {
+ const random = this.faker.datatype.number({ min: 0, max: 15 });
+ const value = placeholder === 'x' ? random : (random & 0x3) | 0x8;
+ return value.toString(16);
+ };
+ return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
+ }
+}
diff --git a/src/modules/vehicle/index.ts b/src/modules/vehicle/index.ts
index cd01ece3..3ef8f748 100644
--- a/src/modules/vehicle/index.ts
+++ b/src/modules/vehicle/index.ts
@@ -88,14 +88,16 @@ export class VehicleModule {
*/
vin(): string {
const bannedChars = ['o', 'i', 'q', 'O', 'I', 'Q'];
- return `${this.faker.random.alphaNumeric(10, {
+ return `${this.faker.string.alphanumeric({
+ length: 10,
casing: 'upper',
bannedChars,
- })}${this.faker.random.alpha({
- count: 1,
+ })}${this.faker.string.alpha({
+ length: 1,
casing: 'upper',
bannedChars,
- })}${this.faker.random.alphaNumeric(1, {
+ })}${this.faker.string.alphanumeric({
+ length: 1,
casing: 'upper',
bannedChars,
})}${this.faker.datatype.number({ min: 10000, max: 99999 })}` // return five digit #
@@ -123,8 +125,8 @@ export class VehicleModule {
* @since 5.4.0
*/
vrm(): string {
- return `${this.faker.random.alpha({
- count: 2,
+ return `${this.faker.string.alpha({
+ length: 2,
casing: 'upper',
})}${this.faker.datatype.number({
min: 0,
@@ -132,7 +134,10 @@ export class VehicleModule {
})}${this.faker.datatype.number({
min: 0,
max: 9,
- })}${this.faker.random.alpha({ count: 3, casing: 'upper' })}`.toUpperCase();
+ })}${this.faker.string.alpha({
+ length: 3,
+ casing: 'upper',
+ })}`;
}
/**