Skip to content

Commit

Permalink
chore(helpers): move unique store into faker instance (#2072)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinigami92 authored Apr 28, 2023
1 parent 8cd1965 commit 8395e69
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
17 changes: 16 additions & 1 deletion src/modules/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ function getRepetitionsBasedOnQuantifierParameters(
* A number of methods can generate strings according to various patterns: [`replaceSymbols()`](https://next.fakerjs.dev/api/helpers.html#replacesymbols), [`replaceSymbolWithNumber()`](https://next.fakerjs.dev/api/helpers.html#replacesymbolwithnumber), and [`fromRegExp()`](https://next.fakerjs.dev/api/helpers.html#fromregexp).
*/
export class HelpersModule {
/**
* Global store of unique values.
* This means that faker should *never* return duplicate values across all API methods when using `faker.helpers.unique` without passing `options.store`.
*
* @internal
*/
private readonly uniqueStore: Record<RecordKey, RecordKey> = {};

constructor(private readonly faker: Faker) {
// Bind `this` so namespaced is working correctly
for (const name of Object.getOwnPropertyNames(
Expand Down Expand Up @@ -1335,13 +1343,20 @@ export class HelpersModule {
until: '9.0',
});

const { maxTime = 50, maxRetries = 50 } = options;
const {
maxTime = 50,
maxRetries = 50,
exclude = [],
store = this.uniqueStore,
} = options;
return uniqueExec.exec(method, args, {
...options,
startTime: new Date().getTime(),
maxTime,
maxRetries,
currentIterations: 0,
exclude,
store,
});
}

Expand Down
16 changes: 2 additions & 14 deletions src/modules/helpers/unique.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,6 @@ import { FakerError } from '../../errors/faker-error';

export type RecordKey = string | number | symbol;

/**
* Global store of unique values.
* This means that faker should *never* return duplicate values across all API methods when using `Faker.helpers.unique` without passing `options.store`.
*/
const GLOBAL_UNIQUE_STORE: Record<RecordKey, RecordKey> = {};

/**
* Global exclude list of results.
* Defaults to nothing excluded.
*/
const GLOBAL_UNIQUE_EXCLUDE: RecordKey[] = [];

/**
* Uniqueness compare function.
* Default behavior is to check value as key against object hash.
Expand Down Expand Up @@ -108,9 +96,9 @@ export function exec<
maxTime = 50,
maxRetries = 50,
compare = defaultCompare,
store = GLOBAL_UNIQUE_STORE,
store,
} = options;
let { exclude = GLOBAL_UNIQUE_EXCLUDE } = options;
let { exclude } = options;
options.currentIterations = options.currentIterations ?? 0;

// Support single exclude argument as string
Expand Down

0 comments on commit 8395e69

Please sign in to comment.