Skip to content

Commit

Permalink
feat: add rndFromString and invertString
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Mar 28, 2023
1 parent 5244512 commit e9bd10f
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/functions/strings.spec.ts
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!')
})
})
43 changes: 43 additions & 0 deletions src/functions/strings.ts
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}

0 comments on commit e9bd10f

Please sign in to comment.