mirror of
https://github.com/cupcakearmy/canihazusername.git
synced 2025-09-05 14:50:41 +00:00
cleanup & updates
This commit is contained in:
63
src/index.ts
63
src/index.ts
@@ -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
|
||||
|
Reference in New Issue
Block a user