Today, we’re going to build a license key generator. This flexible generator will allow you to create keys of varying lengths and segment sizes. We’ll also include a validation function to ensure the keys are correct. And, of course, we’ll write Jest test units to ensure everything works as expected. Let’s get started.
Now, there are much easier and more native ways you can create licence keys. Such as the randomUUID
method on the Crypto object. Open up your console and type: window.crypto.randomUUID();
and it will spit out a UUID. However, we’ll go a step further in this post and make the format configurable. This allows you to create keys that have segments with different lengths.
Setting Up the Project
First, let’s set up a new TypeScript project. If you don’t have TypeScript installed, you can do so by running npm install -g typescript
. Once TypeScript is installed, create a new directory for your project and initialize it with npm:
mkdir key-generator cd key-generator npm init -y
Next, install TypeScript and Jest:
npm install typescript jest ts-jest @types/jest
Building the Key Generator
Now, let’s start coding our key generator. Create a new file called keyGenerator.ts
and add the following code:
class KeyGenerator { constructor(private segmentLengths: number[]) {} generateKey(): string { let key = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; for (let segment of this.segmentLengths) { for (let i = 0; i < segment; i++) { key += characters.charAt(Math.floor(Math.random() * characters.length)); } key += '-'; } // Remove the trailing '-' return key.slice(0, -1); } validateKey(key: string): boolean { const segments = key.split('-'); if (segments.length !== this.segmentLengths.length) { return false; } for (let i = 0; i < segments.length; i++) { if (segments[i].length !== this.segmentLengths[i]) { return false; } } return true; } }
Writing Some Tests
Finally, write some Jest test units to ensure our key generator works correctly. Create a new file called keyGenerator.test.ts
and add the following code:
import { KeyGenerator } from './keyGenerator'; describe('KeyGenerator', () => { const keyGenerator = new KeyGenerator([4, 5, 7, 4]); it('generates a key of the correct length and format', () => { const key = keyGenerator.generateKey(); expect(key).toMatch(/^[A-Z0-9]{4}-[A-Z0-9]{5}-[A-Z0-9]{7}-[A-Z0-9]{4}$/); }); it('validates a correct key', () => { const key = keyGenerator.generateKey(); expect(keyGenerator.validateKey(key)).toBe(true); }); it('rejects an incorrect key', () => { expect(keyGenerator.validateKey('ABC-123')).toBe(false); }); });
In these tests, we check that the key generator creates keys of the correct format, validates correct keys, and rejects incorrect keys.
And there you have it! A flexible license key generator that supports varying segment lengths, built with TypeScript and tested with Jest.