customize the lists

This commit is contained in:
2020-02-07 16:01:34 +01:00
parent 31d6d4447f
commit 3709f8c0f3
2 changed files with 36 additions and 4 deletions

View File

@@ -1,11 +1,19 @@
import wordlist from './wordlist.json'
const DEFAULT_OPTIONS = {
maxReformats: 16,
lists: {} as { [name: string]: string[] }
}
const randomElementFromArray = <T>(arr: T[]): T => arr[Math.floor(Math.random() * arr.length)]
export const showAvailableLists = () => Object.keys(wordlist)
export const generate = (format: string = '{character}_{english}', maxReformats = 16): string => {
for (let i = 0; i < maxReformats; i++) {
export const generate = (format: string = '{character}_{english}', options: Partial<typeof DEFAULT_OPTIONS> = {}): string => {
const opt: typeof DEFAULT_OPTIONS = Object.assign(DEFAULT_OPTIONS, options)
const combined = Object.assign(wordlist, options.lists)
for (let i = 0; i < opt.maxReformats; i++) {
const match = /\{.*?\}/.exec(format)
if (match === null) break
@@ -13,8 +21,8 @@ export const generate = (format: string = '{character}_{english}', maxReformats
.slice(1, -1)
.split('|')
.map(key => key.trim())
.filter(key => key !== '') as [keyof typeof wordlist]
const lists = keys.map(key => Array.isArray(wordlist[key]) ? wordlist[key] : [])
.filter(key => key !== '') as [keyof typeof combined]
const lists = keys.map(key => Array.isArray(combined[key]) ? combined[key] : [])
const flatteded = lists.reduce((acc, val) => acc.concat(val), []);
const value: string = flatteded.length > 0
? randomElementFromArray(flatteded)