2020-02-05 21:21:51 +01:00
|
|
|
import wordlist from './wordlist.json'
|
2019-02-09 19:09:08 +01:00
|
|
|
|
2020-02-07 16:01:34 +01:00
|
|
|
const DEFAULT_OPTIONS = {
|
2021-03-15 18:14:19 +01:00
|
|
|
maxReformats: 16,
|
|
|
|
lists: {} as Record<string, string[]>,
|
2020-02-07 16:01:34 +01:00
|
|
|
}
|
|
|
|
|
2021-03-15 18:14:19 +01:00
|
|
|
function randomElementFromArray<T>(arr: T[]): T {
|
2021-11-02 18:02:21 +01:00
|
|
|
return arr[Math.floor(Math.random() * arr.length)]!
|
2021-03-15 18:14:19 +01:00
|
|
|
}
|
2020-02-05 21:21:51 +01:00
|
|
|
|
2021-03-15 18:14:19 +01:00
|
|
|
export function showAvailableLists(): string[] {
|
|
|
|
return Object.keys(wordlist)
|
|
|
|
}
|
2020-02-05 21:21:51 +01:00
|
|
|
|
2021-03-15 18:14:19 +01:00
|
|
|
export function generate(
|
|
|
|
format: string = '{character}_{english}',
|
|
|
|
options: Partial<typeof DEFAULT_OPTIONS> = {}
|
|
|
|
): string {
|
|
|
|
const opt: typeof DEFAULT_OPTIONS = { ...DEFAULT_OPTIONS, ...options }
|
|
|
|
const combined = { ...wordlist, ...options.lists }
|
|
|
|
|
|
|
|
for (let i = 0; i < opt.maxReformats; i++) {
|
|
|
|
const match = /\{.*?\}/.exec(format)
|
|
|
|
if (match === null) break
|
|
|
|
|
2021-11-02 18:02:21 +01:00
|
|
|
const m0 = match[0]
|
|
|
|
if (!m0) throw new Error('Invalid match')
|
|
|
|
const keys = m0
|
2021-03-15 18:14:19 +01:00
|
|
|
.slice(1, -1)
|
|
|
|
.split('|')
|
|
|
|
.map((key) => key.trim())
|
|
|
|
.filter((key) => key !== '') as [keyof typeof combined]
|
|
|
|
const lists = keys.map((key) => (Array.isArray(combined[key]) ? combined[key] : []))
|
|
|
|
const flattened = lists.reduce((acc, val) => acc.concat(val), [])
|
|
|
|
const value: string = flattened.length > 0 ? randomElementFromArray(flattened) : ''
|
2021-11-02 18:02:21 +01:00
|
|
|
format = format.replace(m0, value)
|
2021-03-15 18:14:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return format
|
2020-02-05 21:21:51 +01:00
|
|
|
}
|
|
|
|
|
2021-03-15 18:14:19 +01:00
|
|
|
export default generate
|