Skip to content

Commit

Permalink
feat: 🔥 Clean up fakFromArray logic
Browse files Browse the repository at this point in the history
Move randUniqueElement logic into fakFromArray. Simplified
fakeFromFunction while loop logic

#220
  • Loading branch information
theryansmee committed Mar 22, 2022
1 parent 485782e commit 6b57aa0
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 16 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Create massive amounts of fake data in the browser and NodeJS. Tree Shakeable &

</p>

✅ &nbsp;193 Functions
✅ &nbsp;192 Functions
✅ &nbsp;Tree Shakable
✅ &nbsp;Fully Typed
✅ &nbsp;Entity Functions
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ title: Getting Started
/>
</p>

✅ &nbsp;193 Functions
✅ &nbsp;192 Functions
✅ &nbsp;Tree Shakable
✅ &nbsp;Fully Typed
✅ &nbsp;Entity Functions
Expand Down
24 changes: 10 additions & 14 deletions packages/falso/src/lib/core/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,7 @@ export function fakeFromFunction<T, Options extends FakeOptions>(
let attempts = 0;
const maxAttempts = options.length * 2;

while (items.length < options.length) {
if (attempts >= maxAttempts) {
break;
}

while (items.length < options.length && attempts < maxAttempts) {
const item = data();

if (!items.includes(item)) {
Expand Down Expand Up @@ -75,17 +71,17 @@ export function fakeFromArray<T, Options extends FakeOptions>(
}

const clonedData: T[] = JSON.parse(JSON.stringify(data));
return Array.from({ length: options.length }, (_, index) =>
randUniqueElement(clonedData)
).filter((item) => item);
}
const newArray: T[] = [];

export function randUniqueElement<T>(arr: T[]): T {
const index = Math.floor(random() * arr.length);
const item = arr[index];
arr.splice(index, 1);
while (clonedData.length && newArray.length !== options.length) {
const randomIndex = getRandomInRange({ min: clonedData.length });
const item = clonedData[randomIndex];

newArray.push(item);
clonedData.splice(randomIndex, 1);
}

return item;
return newArray;
}

export function randElement<T>(arr: T[]): T {
Expand Down

0 comments on commit 6b57aa0

Please sign in to comment.