Quantcast
Channel: January 2022 – Code Buckets
Viewing all articles
Browse latest Browse all 2

Npm Package for Realistic Random Letter Generation

$
0
0

Moving on from my recent post about a realistic way to generate random letters – I’ve now published the work as an npm package. It’s largely an exercise in publishing npm packages but it I still like the utility and it has genuine use cases for writing word games and the like.

Npm Registry

The package plus TypeScript definitions is published to

https://www.npmjs.com/package/correct-frequency-random-letters

and the code is on GitHub at

https://github.com/timbrownls20/correct-frequency-random-letters

Overview

It’s been reworked since the last post. As before it still gets letters in a realistic way using English language letter frequencies e.g.

A is used more commonly than Z so A is returned more frequently than Z

Y is used less commonly than T so Y is returned less frequently than T

For ease of use the functioning has now been split into two classes, DictionaryFrequency and TextFrequency and the lodash dependency has been removed.

Dictionary Frequency

This class returns letters in correct frequency as found in the English dictionary

import {DictionaryFrequency} from "correct-frequency-random-letters"

const dictionary = new DictionaryFrequency();

dictionary.random() // return random letter
dictionary.frequencies() // return frequency table for all letters

Text Frequency

This class returns letters in correct frequency as found in samples of written English text

import {TextFrequency} from "correct-frequency-random-letters"

const text = new TextFrequency();

text.random() // return random letter
text.frequencies() // return frequency table for all letters

Localisation

I’m keen on localisation, so I’ve externalised the letter frequencies here

https://github.com/timbrownls20/correct-frequency-random-letters/blob/main/src/frequency/data/en-GB.ts

Currently it is just English (en-GB) but frequencies can easily be implemented for new languages or language variants by adding another data file and wiring it in. I may do a language or two if I get inspired or anyone else can do one, should they be so inclined.

And that’s it. Hope it’s useful.


Viewing all articles
Browse latest Browse all 2

Trending Articles