cleanup & updates

This commit is contained in:
2021-03-15 18:14:19 +01:00
parent 842e1ba94f
commit 170023f7bb
21 changed files with 6589 additions and 183 deletions

View File

@@ -1,36 +1,41 @@
import wordlist from './wordlist.json'
const DEFAULT_OPTIONS = {
maxReformats: 16,
lists: {} as { [name: string]: string[] }
maxReformats: 16,
lists: {} as Record<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}', 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
const keys = match[0]
.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 flatteded = lists.reduce((acc, val) => acc.concat(val), []);
const value: string = flatteded.length > 0
? randomElementFromArray(flatteded)
: ''
format = format.replace(match[0], value)
}
return format
function randomElementFromArray<T>(arr: T[]): T {
return arr[Math.floor(Math.random() * arr.length)]
}
export default generate
export function showAvailableLists(): string[] {
return Object.keys(wordlist)
}
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
const keys = match[0]
.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) : ''
format = format.replace(match[0], value)
}
return format
}
export default generate