I am working on a javascript code to heavily encode strings.
function splitIntoChunks(str, chunkSize) {
let chunks = [];
for (let i = 0; i < str.length; i += chunkSize) {
let chunk = str.slice(i, i + chunkSize);
}
return chunks;
}
function baseLog(x, y) {
return Math.log(y) / Math.log(x);
}
function stringToNumber(string, bool) {
var str = string;
let num = BigInt(0);
for (let i = 0; i < str.length; i++) {
num = num * BigInt(1103871) + BigInt(str.charCodeAt(i));
}
if (bool) {
console.log(string);
console.log(numberToString(num, false));
}
return num;
}
function numberToString(number, bool) {
let str = '';
var num = number;
while (num > 0) {
let charCode = Number(num % BigInt(1103871));
str = String.fromCharCode(charCode) + str;
num = num / BigInt(1103871);
}
if (bool) {
console.log(number);
console.log(stringToNumber(str, false));
}
return str;
}
function encode(string) {
var encodedString = encodeURIComponent(string);
var array = encodedString.split("");
var newNumberArray = [];
array.forEach(char => {
newNumberArray.push(JSON.stringify(10 + char.charCodeAt(0)));
})
return encodeURIComponent(numberToString(BigInt(parseInt(newNumberArray.join(""))), true));
}
function decode(string) {
var weirdUnicodeCharacters = decodeURIComponent(string);
var jumbledArray = splitIntoChunks(stringToNumber(weirdUnicodeCharacters, true).toString(), 2);
var resultString = "";
jumbledArray.forEach(num => {
resultString = resultString + String.fromCharCode(parseInt(num) - 10);
})
return resultString;
}
/* Usage:
encode(str);
decode(str);
*/
// Testing:
console.log(encode("Hello world!"));
console.log(decode(encode("Hello world!")));
For some reason, the string is being distorted, maybe due to a round-off error or a bug in javascript. I have looked through my code, and I can’t seem to find an error. I even added some debugging using console.log. It may be due to the fact I am using BigInt and normal numbers. I am new to javascript and StackOverflow, so some of my code isn’t that efficient. Thanks so much!
6