Charset
Charset, short for "character set", defines a set of characters. Charset can be sequential or random.
Instantiate
ts
function useCharset(): UseCharset;
function useCharset(options: UseCharsetOptions): UseCharset;
function useCharset(options?: UseCharsetOptions): UseCharset;
Props
ts
type UseCharsetOptions = {
/**
* A function that returns an array of characters.
*/
charset?: () => string[];
/**
* The empty character. Defaults to a space.
*/
emptyChar?: string;
/**
* Provide a shuffle function `boolean` to enable/disable the default shuffle.
*/
shuffle?: ((chars: string[]) => string[]) | boolean;
/**
* An array of characters to omit from the `charset`.
*/
blacklist?: string[];
/**
* An array of characters to include in the `charset`.
*/
whitelist?: string[];
};
Returns
ts
type UseCharset = {
/**
* The charset that was given.
*/
charset: string[];
/**
* The empty character from the charset.
*/
emptyChar: string;
/**
* Determines if the given value is blacklisted.
*/
isBlacklisted: (value: DigitizedValue) => boolean;
/**
* Determines if the given value is whitelisted.
*/
isWhitelisted: (value: DigitizedValue) => boolean;
/**
* Get a chunk of the charset for the given count.
*/
chunk: (value: DigitizedValue | undefined, count: number) => string[];
/**
* Gets the next characters in the charset for the given count.
*/
next: (value?: DigitizedValue, target?: DigitizedValue | DigitizedValues, count?: number) => DigitizedValue | undefined;
/**
* Gets the previous characters in the charset for the given count.
*/
prev: (value?: DigitizedValue, target?: DigitizedValue | DigitizedValues, count?: number) => DigitizedValue | undefined;
};
Usage
ts
const { next, prev, chunk } = useCharset({
blacklist: ['#'],
whitelist: ['@']
});
expect(next('a')).toBe('b');
expect(next('b')).toBe('c');
expect(next(' ')).toBeUndefined();
expect(next(undefined, 'a')).toBe('a');
expect(next(undefined, 'a', 2)).toBe('a');
expect(prev('b')).toBe('a');
expect(prev('c')).toBe('b');
expect(prev('a')).toBe(' ');
expect(prev(' ')).toBeUndefined();
expect(prev('a', undefined, 2)).toBeUndefined();
expect(chunk(undefined, 1)).toStrictEqual(['a']);
expect(chunk(undefined, 5)).toStrictEqual(['a', 'b', 'c', 'd', 'e']);
TIP
These are just a few examples and far from complete. If you want to see a feature-complete example, check tests/helpers/charset.test.ts
in the repo.