mirror of
https://github.com/cupcakearmy/canihazusername.git
synced 2024-12-22 07:36:23 +00:00
customize the lists
This commit is contained in:
parent
31d6d4447f
commit
3709f8c0f3
24
README.md
24
README.md
@ -53,6 +53,30 @@ const username = generate('{quantity|age|cats|}')
|
||||
|
||||
This example will choose a random word between the `quantity`, `age` and `cats` list.
|
||||
|
||||
### ✒️ Use you own lists
|
||||
|
||||
You can also add your own lists or owerwrite the built in one.
|
||||
|
||||
```typescript
|
||||
import { generate } from 'canihazusername'
|
||||
|
||||
const gits = ['gitlab', 'github', 'gitea']
|
||||
const username = generate('{gits}', { lists: { gits } })
|
||||
```
|
||||
|
||||
### 🔐 Reformats limit
|
||||
|
||||
For security reasons the default limit for the maximum reformats/insertions is set to 16.
|
||||
|
||||
If you use more than 16 `{}` you can increase them with the `maxReformats` option.
|
||||
|
||||
```typescript
|
||||
import { generate } from 'canihazusername'
|
||||
|
||||
const username = generate('{1} {2} ... {17}', { maxReformats: 16 }) // ❌ The last one will not be replaced
|
||||
const username = generate('{1} {2} ... {17}', { maxReformats: 20 }) // ✅
|
||||
```
|
||||
|
||||
## 🗂 Lists
|
||||
|
||||
- age
|
||||
|
16
src/index.ts
16
src/index.ts
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user