Skip to content

Instantly share code, notes, and snippets.

@mukhortov
Last active November 29, 2023 09:53
Show Gist options
  • Save mukhortov/075e97ab18cbced433b08153d1627820 to your computer and use it in GitHub Desktop.
Save mukhortov/075e97ab18cbced433b08153d1627820 to your computer and use it in GitHub Desktop.
Shuffle and group lines in a text file using deno
// ! deno run -A shuffle.ts
// Shuffle and group lines in a text file.
// Groups are created by adding two newlines between each group.
const filename = 'items.txt'
const txt = Deno.readTextFileSync(filename)
const nonEmpty = (i: string) => i.trim() !== ''
const groupSeparator = '\n\n'
const numberOfGroups = txt.split(groupSeparator).filter(nonEmpty).length
const shuffled = txt.split('\n').filter(nonEmpty)
.map(value => ({ sort: Math.random(), value }))
.sort((a, b) => a.sort - b.sort)
.map(i => i.value)
const grouped = Object.values(Object.groupBy(shuffled, (_, index) => Math.round(index % numberOfGroups)))
const sorted = grouped.length > 1 ? grouped.map(i => i.sort((a, b) => a.localeCompare(b))) : grouped
const stringified = sorted.flatMap(i => i.join('\n')).join(groupSeparator)
Deno.writeTextFileSync(filename, stringified)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment