diff --git a/src/index.ts b/src/index.ts index 98b5f51e9a6..6e5b297d3f6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,6 +16,7 @@ import { Phone } from './phone_number'; import { Random } from './random'; import { System } from './system'; import { Time } from './time'; +import { Unique } from './unique'; import { Word } from './word'; export interface FakerOptions { @@ -168,7 +169,7 @@ export class Faker { seedValue?: any[] | any; readonly fake: Fake['fake'] = new Fake(this).fake; - readonly unique = new (require('./unique'))(this).unique; + readonly unique: Unique['unique'] = new Unique().unique; readonly mersenne: Mersenne = new Mersenne(); random: Random = new Random(this); diff --git a/src/unique.ts b/src/unique.ts new file mode 100644 index 00000000000..c077ea58577 --- /dev/null +++ b/src/unique.ts @@ -0,0 +1,50 @@ +const uniqueExec = require('../vendor/unique'); + +export class Unique { + // maximum time unique.exec will attempt to run before aborting + maxTime: number = 10; + + // maximum retries unique.exec will recurse before aborting ( max loop depth ) + maxRetries: number = 10; + + // time the script started + // startTime: number = 0; + + constructor() { + // Bind `this` so namespaced is working correctly + for (const name of Object.getOwnPropertyNames(Unique.prototype)) { + if (name === 'constructor' || typeof this[name] !== 'function') { + continue; + } + this[name] = this[name].bind(this); + } + } + + /** + * unique + * + * @method unique + */ + unique( + method: any, + args: any, + opts?: { + startTime?: number; + maxTime?: number; + maxRetries?: number; + currentIterations?: number; + [key: string]: any; + } + ): any { + opts ||= {}; + opts.startTime = new Date().getTime(); + if (typeof opts.maxTime !== 'number') { + opts.maxTime = this.maxTime; + } + if (typeof opts.maxRetries !== 'number') { + opts.maxRetries = this.maxRetries; + } + opts.currentIterations = 0; + return uniqueExec.exec(method, args, opts); + } +}