canihazusername/src/index.ts

32 lines
930 B
TypeScript
Raw Normal View History

2020-02-05 21:21:51 +01:00
import wordlist from './wordlist.json'
2019-02-09 19:09:08 +01:00
const randomElementFromArray = <T>(arr: T[]): T => arr[Math.floor(Math.random() * arr.length)]
2020-02-05 21:21:51 +01:00
export const showAvailableLists = () => {
const keys = Object.keys(wordlist)
console.log(keys)
return keys
2019-02-09 19:09:08 +01:00
}
2020-02-05 21:21:51 +01:00
export const generate = (format: string = '{character}_{english}', maxReformats = 16): string => {
for (let i = 0; i < 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 wordlist]
const lists = keys.map(key => Array.isArray(wordlist[key]) ? wordlist[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
}
export default generate