Answer the question
In order to leave comments, you need to log in
How to write an encryption function using the encode substitution method?
Add the encryption function using the substitution method encode(text, openAlph, secureAlph).
Encode function arguments:
text - text to be encrypted
openAlph - open alphabet
secureAlph - encrypted alphabet
Return value — string (encrypted text).
For encryption, each character of the open alphabet must be replaced by the corresponding character of the closed alphabet. If there are non-alphabetic characters in the text, then they should be left unchanged.
For example:
encode(
"message",
"abcdefghijklmnopqrstuvwxyz",
"rsyxuqldnmzvpofceiwktjgabh",
); // should return "puwwrlu"
function encode(text, openAlph, secureAlph) {
let result = "";
return result;
}
Answer the question
In order to leave comments, you need to log in
function encode(text, openAlph, secureAlph) {
let result = ""
text = text.split("") //превращаем строку в массив
text.forEach(char => { //бежим по массиву
let upper = false
if(char != char.toLowerCase()){ //превращаем в строчную и запоминаем
upper = true
char = char.toLowerCase()
}
if(char.match(/^[A-Za-z]$/)){
let oIndex = openAlph.indexOf(char) //индекс в открытом алфавите алфавите
if( oIndex == -1){ //если индекс не нашелся
throw new Error('Не найден символ "'+char+'" в открытом алфавите');
}
if( !secureAlph[oIndex] ){
throw new Error('Не найден индекс "'+oIndex+'" в закрытом алфавите');
}
char = secureAlph[oIndex] //по индексу берем букву в закрытом алфавите
}
if(upper){
char = char.toUpperCase()
}
result += char
});
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question