From 3709f8c0f3d3dff229604bc7273e2e834721ec42 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Fri, 7 Feb 2020 16:01:34 +0100 Subject: [PATCH] customize the lists --- README.md | 24 ++++++++++++++++++++++++ src/index.ts | 16 ++++++++++++---- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dadddd5..d67dcfe 100644 --- a/README.md +++ b/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 diff --git a/src/index.ts b/src/index.ts index 102ae9e..7a1db55 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,11 +1,19 @@ import wordlist from './wordlist.json' +const DEFAULT_OPTIONS = { + maxReformats: 16, + lists: {} as { [name: string]: string[] } +} + const randomElementFromArray = (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 = {}): 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)