So, I'm trying to make a simple encryption and decryption application where the user inputs are upped by some amount of characters. For Eg: user inputs "abcd" then it converts to "bcde".
Code used for encryption:
const encryptedInput = (input) => {
try {
// convert to array
let splitInput = sanitize(input).split("");
//down the characters by derived
let mapped = splitInput.map((element) =>
element == " "
? element
: String.fromCharCode(element.charCodeAt(0) + process.env.NUMBEROFCHARS)
);
let encryptedInput = mapped.join(""); // result
return encryptedInput; //return
} catch (err) {}
};
The above code works perfectly fine. Its when I try to decrypt it back to original form, It gives me weird symbols and not the original message.
Code used for decryption:
const decryptedInput = (input) => {
try {
// convert to array
let splitInput = sanitize(input).split("");
//down the characters by derived
let mapped = splitInput.map((element) =>
element == " "
? element
: String.fromCharCode(element.charCodeAt(0) - process.env.NUMBEROFCHARS)
);
let decryptedInput = mapped.join(""); // result
return decryptedInput; //return
} catch (err) {}
};
Output / Result:
During encryption:
Input: abcd
Output: bcde
During decryption:
Input: bcde
Output: ϕϟϩϳ
But I want the output as abcd not ϕϟϩϳ.
So I restarted my pc and the code works now.
Related
I am trying to make a simple encoder in javascript, and copying the output to the clipboard, but the code gives an error.
I tried this code:
function encode() {
let alphabet = " abcdefghijklmnopqrstuvwxyz1234567890-=!##$%^&*()_+[];'/.,'{}|:~";
const a_list = alphabet.split('');
const m_list = prompt("message: ").split('');
let return_message = "";
for (let i = 0; i < m_list.length; i++) {
let current_letter = m_list[i];
let translated_letter = a_list[a_list.indexOf(current_letter) + 5];
return_message += translated_letter;
}
navigator.clipboard.writeText(return_message);
}
encode()
but the console gives this error:
Error: DOMException {INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, …}
I host the server in replit.
When I try to do an alert with the encoded words, it works fine.
navigator.clipboard.writeText requires a transient user activation. That is why it works when you click on an alert box.
Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.
The "clipboard-write" permission of the Permissions API is granted automatically to pages when they are in the active tab.
https://devdocs.io/dom/clipboard/writetext
The error you are getting is because the indexOf function returns -1 when the sought character is not found in the a_list array.
You can check whether the index returned by indexOf is greater than or equal to zero before accessing the element in the a_list array. If the index returned is less than zero, you can simply add the original character to return_message.
Here is an example:
function encode() {
// Define the list of characters to be substituted
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const charList = alphabet.split('');
// Receive the string to be substituted from the user
const inputString = prompt("Enter the string to be substituted:");
// Convert the string to an array of characters
const inputChars = inputString.split('');
// Create a new array with the substituted characters
const outputChars = inputChars.map(char => {
// Find the index of the current character in the character list
const index = charList.indexOf(char.toLowerCase());
// If the character is not in the character list, keep the original character
if (index === -1) {
return char;
}
// Find the next character in the character list
const nextIndex = (index + 1) % charList.length;
const nextChar = charList[nextIndex];
// Return the next substituted character
return char.toUpperCase() === char ? nextChar.toUpperCase() : nextChar;
});
// Convert the array of characters back to a string
const outputString = outputChars.join('');
// Display the substituted string in the console
navigator.clipboard.writeText(outputString);
}
encode()
And as answered in #dotnetCarpenter reply navigator.clipboard.writeText requires a transient user activation. That's why it works when an alert box is clicked.
I was coding a simple unit conversion command for my discord bot that would convert meters to centimetres. I read over my code several times and couldn't find anything possibly wrong with it, however, when I run the command, it simply returns "undefined" for the result value. I also made a point to double check the scope of my code blocks to make sure all the variables are properly accessible.
Code:
if (message.content.startsWith(prefix + 'convert ')) {
let content = message.content.replace(prefix + 'convert ', '');
content.split(' ');
let value = content[0];
let firstUnit = content[1];
let convertedUnit = content[3];
let result;
let description;
let embedFormula;
if (firstUnit === 'm' && convertedUnit === 'cm') {
const formula = (inputValue) => {
return inputValue * 100;
}
result = formula(value);
description = `${value} m to cm = **${result} cm**`;
embedFormula = '`Multiply the length value by 100`';
}
const conversionEmbed = new Discord.MessageEmbed()
.setTitle('Unit Conversion')
.setDescription(description)
.setColor('#F942FF')
.addFields(
{ name: 'Formula', value: embedFormula }
)
message.delete();
message.channel.send(conversionEmbed);
}
Result:
The command runs when the user types "_convert 1 m to cm" (1 can of course be swapped with any number).
Is there anything missing here?
Thanks in advance.
content.split() won't edit existing variables:
let content = 'Hello!';
content.split();
console.log(content); // Still 'Hello!'
console.log(content[0]); // This just gets the first character
So instead of this:
let content = message.content.replace(prefix + 'convert ', '');
content.split(' ');
You should do this:
let content = message.content.replace(prefix + 'convert ', '').split(' ');
I have the following problem statement:
Write a function, uncompress, that takes in a string as an argument.
The input string will be formatted into multiple groups according to
the following pattern:
number + char
for example, '2c' or '3a'.
The function should return an uncompressed version of the string where
each 'char' of a group is repeated 'number' times consecutively. You
may assume that the input string is well-formed according to the
previously mentioned pattern.
test_00: uncompress("2c3a1t"); // -> 'ccaaat'
Here is my code which is using a stack. The problem is that it's only returning 'cc' and I can't figure out why. I've console logged what goes into the IF ELSE and I'm hitting both so I don't understand why nothing gets pushed to the stack.
Would really appreciate the help if someone can spot what I'm missing.
const uncompress = (s) => {
const nums = '23456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
const num = stack.pop();
stack.push(char.repeat(num));
};
};
return stack.join('');
};
console.log(uncompress("2c3a1t")); // -> 'ccaaat'
Here's how I would do it:
Split the string up into pairs of numbers and chars:
str.match(/\d+[a-zA-Z]/g)
And reduce that array to a string, while taking each value from the array, getting the char from it (cv.match(/[a-zA-Z]/)[0]) and repeating it according to the number (.repeat(parseInt(cv)))
const uncompress = str => str.match(/\d+[a-zA-Z]/g).reduce((acc, cv) =>
acc + cv.match(/[a-zA-Z]/)[0].repeat(parseInt(cv)), "")
console.log(uncompress("2c3a1t"))
console.log(uncompress("27b1d8g"))
And just like that I was able to write the code which passed the test case:
const nums = '123456789';
const stack = [];
for (let char of s) {
if (nums.includes(char)) {
stack.push(Number(char));
} else {
let num = '';
while (nums.includes(stack[stack.length - 1])) {
num += stack.pop();
}
stack.push(char.repeat(num));
};
};
return stack.join('');
};
I'm trying to create a small app that reads a chat message and echoes a filtered text
I need it to take this message:
INPUT:
#notthis/remove
remove this line
This one too
Output:
notthis
At the moment all it does is remove the second word + the first hashtag:
"hello#hello" which becomes hello
I tried adding the / like this input.split("#","/"); but all it does is crash the program.
Not asking to do the program for me, but I'd really appreciate any hints.
Thank you!
const Telegraf = require('telegraf');
const bot = new Telegraf('182049');
const helpMessage = `
Say something to me
/start - start the bot
/help - command reference
`;
bot.start((ctx) => {
ctx.reply("Hi I am echoo bot");
ctx.reply(helpMessage);
});
bot.help((ctx) => {
ctx.reply(helpMessage)
});
bot.on("text", (ctx) => {
let input = ctx.message.text;
let inputArray = input.split("#");
console.log(inputArray);
let message = "";
if (inputArray.length == 1) {
message = "no separator";
} else {
inputArray.shift();
message = inputArray.join(" ");
}
ctx.reply(message);
});
bot.launch()
Regular Expression (regex) is a great way to find substrings in an unknown string, even though it might be a bit daunting to work with. You can use this website to create your regex.
To find a substring starting with # and ending with /, you can use the following expression:
/#\w+\//g
This will match 1 or more word characters that are in between a # and a /.
For example:
#foo/ will match
#f/ will match
#/ will not match
#foo bar/ will not match (whitespace is not a word character)
An example JavaScript code:
const regex = /#\w+\//g;
const text = "something#fooo/bar #lorem/ipsum";
const found = text.match(regex);
// For each found item, remove the first and last characters
const cleaned = found.map((a) => a.slice(1, -1));
console.log(cleaned);
I think I made it
const Telegraf = require('telegraf');
const bot = new Telegraf('18204DjYLa9o9Y');
const regex = /#\w+\//g;
const helpMessage = `
Say something to me
/start - start the bot
/help - command reference
`;
bot.start((ctx) => {
ctx.reply("Hi I am echoo bot");
ctx.reply(helpMessage);
})
bot.help((ctx) => {
ctx.reply(helpMessage)
})
bot.on("text", (ctx) => {
let input = ctx.message.text;
let inputArray = input.split("#");
console.log(inputArray);
let message = "";
inputArray.shift();
message = inputArray.join(" ");
let messageArray = message.split("/");
console.log(messageArray);
for(let index = 0; message[index] != '/'; index++ )
{
ctx.reply("/ta " + message[index]);
}
return null
})
bot.hears("cat", (ctx) =>{
ctx.reply("Meow");
})
bot.launch()
Only a little issue: if my coin has more than 3 letters it gets truncated.
For loop solves the problem but every letter starts with a new line, and the second imput gets messed up
Eg: echobot, [13.05.21 00:54]
E
echobot, [13.05.21 00:54]
O
echobot, [13.05.21 00:54]
S
2nd attempt:
echobot, [13.05.21 00:54]
S
echobot, [13.05.21 00:54]
O
echobot, [13.05.21 00:54]
E
Let us assume I got two strings. In my case the strings are "stringA" and "stringB":
Example 1:
let stringA = "1ABC DEFGHI";
let stringB = "XYZABC DEFGHI";
Even if the two strings are not exactly the same, they still contain a large amount of letter sequences, which are identical in both. In the case above it is the string "ABC DEFGHI" that occurs in both of them.
Example 2: And heres another example:
let stringA = "0142 41193566"
let stringB = "+49 142 41193566"
In this case the result should be 142 41193566 because this string occurs in both of them.
I would describe the operation as a kind of mask operation, but I have not progressed so far in implementing it. Unfortunately, this code snippet is everything I can offer so far.
let stringA = "0142 41193566"
let stringB = "+49 142 41193566"
let stringC = "....ThISisATest"
let stringD = "+Th.ISisATest33"
let detectBiggestOccurrence = function(stringA, stringB) {
let result = []
for (let c in stringA) {
if (stringB.includes(stringA[c])) {
let index = stringB.indexOf(stringA[c])
result+=stringB[index]
}
}; return result
}
let resultWorking = detectBiggestOccurrence(stringA, stringB)
console.log("working:", resultWorking)
let resultNotWorking = detectBiggestOccurrence(stringC, stringD)
console.log("not working:", resultNotWorking)
Issue: The code above is working for the first call (detectBiggestOccurrence(stringA, stringB)) but it does not work for the second one (detectBiggestOccurrence(stringC, stringD)).
The approach that I've used to solve your problem :
Create an empty mask
Populate that empty mask by one letter in first string and check if the mask is present in the second string.
Compare mask length with last response length. If mask is bigger, mask becomes the response
function detectBiggestOccurrence(stringA, stringB){
var mask ="";
var response ="";
stringA.split('').forEach( el => {
mask +=el;
if(stringB.includes(mask)){
if(mask.length > response.length){ response = mask; }
}
else {
mask =el;
}
})
return response;
}
let stringA = "1ABC DEFGHI";
let stringB = "XYZABC DEFGHI";
console.log(detectBiggestOccurrence(stringA, stringB));
let stringC = "0142 41193566";
let stringD = "+49 142 41193566";
console.log(detectBiggestOccurrence(stringC, stringD));
let stringE = "....ThISisATest"
let stringF = "+Th.ISisATest33"
console.log(detectBiggestOccurrence(stringE, stringF));
Here is a modified version of Pierre Capo's answer. It will return a correct result, even if a "problematic" string should be tested (see my comment under Pierre's answer).
function maxmatch(a,b){
var i=0,res='',pat=a[i];
while (i<a.length) {
if (b.includes(pat)) {
if (pat.length>res.length) res=pat;
pat+=a[++i];
}
else {
if (pat.length>1) pat=pat.slice(1);
else pat=a[++i];
}
}
return res;
}
let testStrings=[["1ABC DEFGHI","XYZABC DEFGHI"],
["1ABC DEFGHI","XYZBC DEFGHI ABC"],
["0142 41193566","+49 142 41193566"],
["....ThISisATest","+Th.ISisATest33"]];
testStrings.forEach(t=>console.log(maxmatch(...t)))
When applied to the test strings (please notice: I added a modified version of the first test string) they will all return the correct answer:
ABC DEFGHI
BC DEFGHI
142 41193566
ISisATest