Skip to content
This repository has been archived by the owner on Jan 8, 2020. It is now read-only.

Solución Caesar cipher - Daniela Gonzales #74

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"parserOptions": {
"ecmaVersion": 6
},
"rules": {
"keyword-spacing": 1,
"space-before-function-paren": [1, "never"],
"eqeqeq": 1,
"space-infix-ops": 1,
"comma-spacing": 1,
"brace-style": 1,
"no-multiple-empty-lines": 1,
"camelcase": 1,
"func-call-spacing": 1,
"key-spacing": 1,
"semi": 1,
"no-floating-decimal": 1,
"no-multi-spaces": 1,
"object-property-newline": 1,
"padded-blocks": [1, "never"],
"space-before-blocks": 1,
"space-in-parens": 1,
"spaced-comment": 1,
"quotes": [1, "single"],
"id-length": [1, { "exceptions": ["i", "j", "x"] }],
"indent": [1, 2],
"no-array-constructor": 1
}
}
10 changes: 10 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cifrando con Cesar</title>
</head>
<body>
<script src="js/app.js" charset="utf-8"></script>
</body>
</html>
85 changes: 85 additions & 0 deletions js/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// funcion para cifrar una cadena de texto
function cipher(myString) {
var myStringCipher = ''; // almacenar el valor del string Cifrado

for (var i = 0 ; i < myString.length ; i++) { // recorrer el string del usuario
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generalmente, los espacios al rededor del semicolon son como los de las comas. No hay espacio antes, pero si hay uno despues. Por favor quitar espacio antes de los semicolons en esta linea.

var numberOfTheLetter = myString.charCodeAt(i); // numero de la letra en el codigo ASCII
var cipherFormula; // almacena fórmula de cifrado que se utiliza
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

La razon por la cual les damos nombres descriptivos para nuestros variables es para no necesitar comentarios explicando que hacen. Favor de borrar los comentarios que no sean necesarios.

var theNewLetter; // alamacena valor de la nueva letra cifrada
if (numberOfTheLetter >= 65 && numberOfTheLetter <= 90) { // valor UNICODE de letras mayúsculas en ASCII
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Para hacer los ifs mas legibles, cambiaria los numeros como 65, 90, 97, 122, y 32 con las letras seguidas por charCodeAt(0).
Por ejemplo, el primer if podria verse asi: numberOfTheLetter >= 'A'.charCodeAt(0) && numberOfTheLetter <= 'Z'.charCodeAt(0)

Lo mismo aplica para los otros if.

cipherFormula = (numberOfTheLetter - 65 + 33) % 26 + 65; // formula de Cifrado Cesar: obtener nuevo numero de letra en el codigo ASCII
theNewLetter = String.fromCharCode(cipherFormula); // obtener el valor de la letra cifrada
myStringCipher += theNewLetter; // formar el string cifrado
} else if (numberOfTheLetter >= 97 && numberOfTheLetter <= 122) { // valor UNICODE de letras minúsculas en ASCII
cipherFormula = (numberOfTheLetter - 97 + 33) % 26 + 97; // fórmula de cifrado Cesar
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

el mismo comentario que en los ifs.
Actualiza el 97 a 'a'.charCodeAt(0) para mejorar legibilidad

theNewLetter = String.fromCharCode(cipherFormula); // valor de letra cifrada
myStringCipher += theNewLetter; // formar el string cifrado
} else if (numberOfTheLetter === 32) { // verificar si es un espacio vacio
myStringCipher += ' '; // añadir espacio en string cifrado
} else {
break; // Si no es una letra detente
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

en este caso, el break se sale del loop, pero aun vamos a llegar a la linea de return myStringCipher. Creo que las indicaciones dicen que tenemos que prevenir que el usuario ponga un mensaje que tenga algo que no sea letra o espacio. Por favor enseniarle un mensaje al usuario y no regresar nada.

}
}
return myStringCipher; // Retorna el valor de la cadena cifrada
}

// funcion para descifrar una cadena de texto
function decipher(myString) {
var myStringDechiper = ''; // alamacenar el valor del string decifrado
for (var i = 0; i < myString.length ; i++) { // recorrer el string del usuario
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

quitar espacio antes del segundo semicolon

var numberOfTheLetter = myString.charCodeAt(i); // valor UNICODE de la letra en el código ASCII
var decipherFormula; // almacena fórmula de decifrado
var theNewLetter; // almacena el nuevo valor de la letra decifrada
if (numberOfTheLetter >= 65 && numberOfTheLetter <= 90) { // saber si la letra está en mayúscula
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mismo comentario que hice en la otra function

decipherFormula = (numberOfTheLetter - 13 - 33) % 26 + 65; // formula para descifrar
theNewLetter = String.fromCharCode(decipherFormula); // obtener el valor de la letra descifrada
myStringDechiper += theNewLetter; // formar la cadena descifrada
} else if (numberOfTheLetter >= 97 && numberOfTheLetter <= 122) { // saber si la letra está en minúscula
decipherFormula = (numberOfTheLetter - 45 - 33) % 26 + 97; // formula para descifrar
theNewLetter = String.fromCharCode(decipherFormula); // obtener el valor de la letra descifrada
myStringDechiper += theNewLetter; // formar la cadena descifrada
} else if (numberOfTheLetter === 32) { // verificar si es un espacio vacio
myStringDechiper += ' '; // añadir un espacio en string decifrado
} else {
break;
}
}
return myStringDechiper; // retornar el valor de la cadena decifrada
}

// fuction para saber que desea realizar el usuario
function dataUser(option) {
var userText; // almacenar el texto que el usuario ingreso.
var verification; // verificar que inicie con letras

switch (true) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Para el switch, estas checando el valor de tu variable "option" asi que en vez de switch (true) puedes poner switch (option) y ya en cada case solamente tienes que poner case ('1') y case ('2')

case (option === '1'):
userText = prompt('¿Qué texto desea cifrar? (Por favor ingresar un texto)');
verification = parseInt(userText); // parsear para verificar que una cadena de texto
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creo que seria mejor tener un helper function que te verifique que solamente haya letras y espacios en el userText, en vez de usar parseInt

// Si la cadena inicia con números volver a pedir un texto para cifrar
while (verification >= 0 || verification <= 0 || userText === '') {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

con el helper function que estoy explicando, regresarias un bool y podrias checar:
While (!verify(userText))

userText = prompt('¿Qué texto desea cifrar? (Por favor ingresar un texto)');
verification = parseInt(userText); // seguir parseando el string hasta que no inicie con números
}
alert(cipher(userText)); // mostrar un alert que invoque a la función cipher y retorne el texto cifrado
break;

case (option === '2'):
userText = prompt('¿Qué texto desea descifrar? (Por favor ingresar un texto)');
verification = parseInt(userText); // parsear para verificar que una cadena de texto
// Si la cadena inicia con números volver a pedir un texto para decifrar
while (verification >= 0 || verification <= 0 || userText === '') {
userText = prompt('¿Qué texto desea decifrar? (Por favor ingresar un texto)');
verification = parseInt(userText); // seguir parseando el string hasta que no inicie con números
}
alert(decipher(userText)); // mostrar un alert que invoque a la función decipher y retorne el texto decifrado
break;
}
}

// bucle para ver que desea realizar el usuario
do {
var menu = 'Por favor escribir 1 si desea cifrar un texto \n Por favor escribir 2 si desea descifrar un texto \n Por favor escribir 3 si desea salir del sistema';
var option = prompt(menu); // mostrar el menu al usuario y alamcenar la opción que elije
dataUser(option);
} while (option !== '3'); // seguir preguntadole hasta que desee salir del programa