From d9f6edb0e5ea880da05cc04c936d8a2f070bd65e Mon Sep 17 00:00:00 2001 From: Shinigami92 Date: Wed, 15 Mar 2023 17:53:49 +0100 Subject: [PATCH 1/2] fix(random): prevent infinite do-while --- src/modules/random/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/modules/random/index.ts b/src/modules/random/index.ts index a2847bbc3d3..b35b7c8722d 100644 --- a/src/modules/random/index.ts +++ b/src/modules/random/index.ts @@ -125,6 +125,8 @@ export class RandomModule { ]; let result: string; + let iteration = 0; + do { // randomly pick from the many faker methods that can generate words const randomWordMethod = this.faker.helpers.arrayElement(wordMethods); @@ -133,6 +135,14 @@ export class RandomModule { result = randomWordMethod(); } catch { // catch missing locale data potentially required by randomWordMethod + iteration++; + + if (iteration > 100) { + throw new FakerError( + 'No matching word data available for the current locale' + ); + } + continue; } } while (!result || bannedChars.some((char) => result.includes(char))); From 0cce18ba566b85bd060876f16826ee5630f26481 Mon Sep 17 00:00:00 2001 From: Shinigami92 Date: Wed, 15 Mar 2023 18:27:42 +0100 Subject: [PATCH 2/2] add test --- test/random.spec.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/random.spec.ts b/test/random.spec.ts index 3818274f516..5e6a93b284c 100644 --- a/test/random.spec.ts +++ b/test/random.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { faker, FakerError, fakerZH_CN } from '../src'; +import { Faker, faker, FakerError, fakerZH_CN } from '../src'; import { seededTests } from './support/seededRuns'; import { times } from './support/times'; @@ -81,6 +81,12 @@ describe('random', () => { ); } ); + + it('should throw error if no data are available', () => { + const faker = new Faker({ locale: [{ title: 'custom' }] }); + + expect(() => faker.random.word()).toThrowError(); + }); }); describe('words', () => {