From e9bd10f4c50998bbfe6cc9d0442062e4636442c3 Mon Sep 17 00:00:00 2001 From: Adam Laycock Date: Tue, 28 Mar 2023 15:38:45 +0100 Subject: [PATCH] feat: add rndFromString and invertString --- src/functions/strings.spec.ts | 16 +++++++++++++ src/functions/strings.ts | 43 +++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 src/functions/strings.spec.ts create mode 100644 src/functions/strings.ts diff --git a/src/functions/strings.spec.ts b/src/functions/strings.spec.ts new file mode 100644 index 0000000..c33753e --- /dev/null +++ b/src/functions/strings.spec.ts @@ -0,0 +1,16 @@ +import {rndFromString, invertString} from './strings' + +describe('Strings', () => { + it('should generate a random number from a string', () => { + expect(rndFromString('foo')).toBe(0) + expect(rndFromString('foo', 10)).toBe(3) + // Test that it always returns the same + expect(rndFromString('foo', 10)).toBe(3) + }) + + it('should invert strings', () => { + expect(invertString('abc')).toBe('zyx') + expect(invertString('AbC')).toBe('ZyX') + expect(invertString('Alpha!')).toBe('Zoksz!') + }) +}) diff --git a/src/functions/strings.ts b/src/functions/strings.ts new file mode 100644 index 0000000..1df0ee6 --- /dev/null +++ b/src/functions/strings.ts @@ -0,0 +1,43 @@ +/** + * Returns a random number seeded using the supplied string. A given string will always return the same number + * + * @param string The string to seed with + * @param base The maximum number to produce. Defaults to `1`. + * @returns A random number + */ +export const rndFromString = (string: string, base: number = 1) => { + const seed = string.split('').reduce((count, char) => { + return count + char.charCodeAt(0) + }, 0) + + const n = Math.sin(seed) * 10000 + + return Math.round((n - Math.floor(n)) * base) +} + +export const invertString = (string: string) => { + return string + .split('') + .map(char => { + const charCode = char.charCodeAt(0) + + if ( + !( + (charCode >= 65 && charCode <= 90) || + (charCode >= 97 && charCode <= 122) + ) + ) { + return char + } + + const alpha = charCode < 97 ? 65 : 97 + const zeta = charCode < 97 ? 90 : 122 + + const letterCode = charCode - alpha + + return String.fromCharCode(zeta - letterCode) + }) + .join('') +} + +// {rndFromString, invertString}