Last active
November 29, 2023 09:53
-
-
Save mukhortov/075e97ab18cbced433b08153d1627820 to your computer and use it in GitHub Desktop.
Shuffle and group lines in a text file using deno
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ! 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