From 8395e6991cd00951d9e25ae489cb191c4c3957b6 Mon Sep 17 00:00:00 2001 From: Shinigami Date: Fri, 28 Apr 2023 13:51:04 +0200 Subject: [PATCH] chore(helpers): move unique store into faker instance (#2072) --- src/modules/helpers/index.ts | 17 ++++++++++++++++- src/modules/helpers/unique.ts | 16 ++-------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/modules/helpers/index.ts b/src/modules/helpers/index.ts index 0bb54fb631a..3b94586dc80 100644 --- a/src/modules/helpers/index.ts +++ b/src/modules/helpers/index.ts @@ -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 = {}; + constructor(private readonly faker: Faker) { // Bind `this` so namespaced is working correctly for (const name of Object.getOwnPropertyNames( @@ -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, }); } diff --git a/src/modules/helpers/unique.ts b/src/modules/helpers/unique.ts index 5cf55a66edd..90896c6425d 100644 --- a/src/modules/helpers/unique.ts +++ b/src/modules/helpers/unique.ts @@ -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 = {}; - -/** - * 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. @@ -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