-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add rndFromString and invertString
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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!') | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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} |