Skip to content

Commit

Permalink
Update randsamp to use proper shuffle algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronccasanova committed Dec 18, 2022
1 parent a84ec39 commit ada0d68
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/wicked-pears-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'randsamp': patch
---

Add proper shuffle algorithm
26 changes: 24 additions & 2 deletions packages/randsamp/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ export async function randsamp(options: RandsampOptions) {
throw new Error('No samples found.')
}

const randomizedSampleFiles = sampleFiles.sort(() => Math.random() - 0.5)
const shuffledSampleFiles = shuffle(sampleFiles)

const targetSampleFiles = randomizedSampleFiles.slice(0, sampleCount)
const targetSampleFiles = shuffledSampleFiles.slice(0, sampleCount)

if (!fs.existsSync(absoluteOutputDir)) {
await fs.promises.mkdir(absoluteOutputDir)
Expand All @@ -73,3 +73,25 @@ export async function randsamp(options: RandsampOptions) {
}),
)
}

// https://stackoverflow.com/a/2450976
function shuffle(array: string[]) {
let currentIndex: number = array.length
let randomIndex: number

// While there remain elements to shuffle.
while (currentIndex !== 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1

// And swap it with the current element.
// eslint-disable-next-line no-param-reassign
;[array[currentIndex], array[randomIndex]] = [
array[randomIndex]!,
array[currentIndex]!,
]
}

return array
}

3 comments on commit ada0d68

@vercel
Copy link

@vercel vercel bot commented on ada0d68 Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

aacc-next-ts-styled-comps – ./recipes/next-ts-styled-comps

aacc-next-ts-styled-comps.vercel.app
aacc-next-ts-styled-comps-aaronccasanova-gmailcom.vercel.app
aacc-next-ts-styled-comps-git-main-aaronccasanova-gmailcom.vercel.app

@vercel
Copy link

@vercel vercel bot commented on ada0d68 Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on ada0d68 Dec 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

aacc-next-ts – ./recipes/next-ts

aacc-next-ts-aaronccasanova-gmailcom.vercel.app
aacc-next-ts-git-main-aaronccasanova-gmailcom.vercel.app
aacc-next-ts.vercel.app

Please sign in to comment.