Skip to content

Instantly share code, notes, and snippets.

@ammoradi
Last active October 31, 2020 23:13
Show Gist options
  • Save ammoradi/d327078962545d60a46f32a655628163 to your computer and use it in GitHub Desktop.
Save ammoradi/d327078962545d60a46f32a655628163 to your computer and use it in GitHub Desktop.
JavaScript simple string encoder/decoder written in TypeScript
// see [Inspiration Source](https://www.geeksforgeeks.org/decode-the-string-encoded-with-the-given-algorithm/)
// JavaScriptSimpleEncoder => iSmtpplierEcnScaovdaeJr
const encodeString = (inputStr: string): string => {
const len = inputStr.length
if (!len) return inputStr
const isLenEven = len % 2 === 0
const str: string = isLenEven ? `${inputStr} ` : inputStr
const halfLength: number = Math.floor(len / 2)
let result: string = str[halfLength]
for (let i = 1; i <= halfLength; i += 1) {
result += str[halfLength - i]
result += str[halfLength + i]
}
if (isLenEven) return result.slice(0, len)
return result
}
// iSmtpplierEcnScaovdaeJr => JavaScriptSimpleEncoder
const decodeString = (str: string): string => {
const len = str.length
if (!len) return str
let result = str[0]
let factor = -1
for (let i = 1; i < len; i += 1) {
result = factor > 0 ? result + str[i] : str[i] + result
factor *= -1
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment