Skip to content
This repository was archived by the owner on Jan 8, 2020. It is now read-only.
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
}
}
137 changes: 95 additions & 42 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,57 +1,110 @@
# Cifrado César
# PRODUCTO FINAL - CIFRADO CÉSAR

> Recuerda seguir siempre esta [guía de estilos](https://github.com/Laboratoria/js-style-guide/)
#### Consideraciones Específicas:

Crea una web que pida, por medio de un `prompt()`, una frase al usuario y
devuelva el mismo mensaje encriptado según el
[algoritmo de Cifrado César](https://en.wikipedia.org/wiki/Caesar_cipher)
con el parámetro de desplazamiento de **33 espacios hacia la derecha**
1. Tu programa debe ser capaz de cifrar y descifrar tanto letras mayúsculas como minúsculas. La fórmula para descifrar es: (x - n) % 26
2. Tu código debe estar compuesto por 2 funciones con los siguientes nombres: cipher y decipher
3. El usuario no debe poder ingresar un campo vacío o que contenga números

Por ejemplo:
### PSEUDOCODIGO:

- Texto original: `ABCDEFGHIJKLMNOPQRSTUVWXYZ`
- Texto codificado: `HIJKLMNOPQRSTUVWXYZABCDEFG`

## Entregables
Creamos función Cipher:
~~~
Funcion Cipher(phrase){

Definir output,texto,i

Para cada producto debes entregar **un repositorio de GitHub** que
contenga:
1. Archivo `README.md` que explique el **pseudocódigo** de tu solución y su
**diagrama de flujo**
2. Archivo `app.js` con el **código** de tu solución
3. Archivo `index.html` vinculado con tu `app.js`
output = ''(vacio)
texto = phrase(convertido en mayusculas)

## Tips
Para( i = 0 , i < longitud de la variable texto , i = i + 1){

A continuación un video de Michelle que te lleva a través de la fórmula
matemática del Cifrado César y un par de cosas más que debes saber para
resolver este reto. ¡Escúchala con detenimiento y sigue sus consejos! :)
output = output + String.fromCharCode(Devuelve una cadena desde un numero ASCII)((((texto.charCodeAt[ i ](Devuelve numero ASCII de la variable texto1 en su indice i )-65)+33)%26)+65)
}

[![tips caesar cipher](https://img.youtube.com/vi/zd8eVrXhs7Y/0.jpg)](https://www.youtube.com/watch?v=zd8eVrXhs7Y)
retorne variable output
}
~~~
Ahora creamos una funcion Decipher a la cual no le cambiamos las variables porque son distintas funciones:
~~~
Funcion Decipher(phrase){

Definimos como variable a output,texto,i

También te compartimos más información de lo que Michelle te ha explicado
en el video anterior:
output = ''(vacio)
texto = phrase(convertido en mayusculas)

- [Aprende más sobre `charCodeAt()`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/charCodeAt)
- [Aprende más sobre `String.fromCharCode()`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/fromCharCode)
- [Aprende más sobre `ASCII`](http://conceptodefinicion.de/ascii/)
Para( i = 0 , i<longitud de la variable texto , j = j + 1){

## Consideraciones específicas
output = output + String.fromCharCode(Devuelve una cadena desde un numero ASCII)((((texto.charCodeAt[ i ](Devuelve numero ASCII de la variable texto en su indice i )+65)-33)%26)+65)
}

1. Tu programa debe ser capaz de cifrar y descifrar tanto letras
mayúsculas como minúsculas. La fórmula para descifrar es: `(x - n) % 26`
2. Tu código debe estar compuesto por 2 funciones con los siguientes
nombres: `cipher` y `decipher`
3. El usuario no debe poder ingresar un campo vacío o que contenga números
retorne variable output
}
~~~
Ahora que ya tenemos las funciones creadas pasaremos a preguntar al usuario, validar y llamar a las funciones:
~~~
Definimos como variable a order,k,value,spaces

order = prompt('Ingresa una frase')(Pide al usuario)

Si(order es distinto de ""(vacio))Entonces{

Para (j = 0 , j < longitud de la variable order,j = j + 1){
Si(order en la posicion [ j ] es igual a " " (campo en blanco) )Entonces{

spaces = true
break; (sale del bucle)

}Sino{

spaces = false
}
}

Si (spaces = true) Entonces{

Alerta ('No ingrese campos en blanco')

}Sino{

Para (k = 0 , k < longitud de la variable order,k = k + 1){
Si(order convertido a ASCII mayor 64 y menor a 91 )Entonces{

value = true

}Sino{

value = false
Alerta ('Ingrese solo letras')
}
}

Si (value = true) Entonces{

Escribir en documento ('Cifrado ->' + (LLamamos a la funcion Cipher) Cipher(order))
Escribir en documento ('<p> Decifrado ->' + (LLamamos a la funcion Decipher) Decipher(order))

}
}

}Sino{

Alerta('Ingrese una frase')
}
~~~

### DIAGRAMA DE FLUJO

Funcion Cipher:

![Sin titulo](assets/docs/FuncionCipher.jpg)

Funcion Decipher:

![Sin titulo](assets/docs/FuncionDecipher.jpg)

## Criterios de evaluación
Validando y llamando a las funciones:

Se tomarán en cuenta las siguientes consideraciones a la hora de evaluar tu solución:
![Sin titulo](assets/docs/LLamando.jpg)

1. Nombramiento de variables
2. Indentación
3. Validación de input: el usuario no debe poder ingresar un campo vacío o de tipo que no corresponda
4. Estructura de tus archivos
5. Archivo `README.md` correctamente redactado
6. Uso de comentarios para hacer tu código más legible
7. Que el programa cumpla con el propósito requerido
Binary file added assets/docs/FuncionCipher.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/docs/FuncionDecipher.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/docs/LLamando.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Cifrado César</title>
</head>
<body>
<h1>Cifrado César</h1>
<script src="js/app.js"></script>
</body>
</html>
101 changes: 101 additions & 0 deletions js/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Creamos las funciones de CIPHER y DECIPHER:
function cipher(phrase) {
var output = '';

// Bucle que recorra la variable phrase:
for (var i = 0; i < phrase.length; i++) {
// Convierte a ascii
var ascii = phrase.charCodeAt(i);

// Condición y covierte nuevamente en letra
if (ascii > 64 && ascii < 91) // fórmula para mayúsculas
output += String.fromCharCode(((ascii - 65) + 33) % 26 + 65);
else if (ascii > 96 && ascii < 123) // fórmula para minúsculas
output += String.fromCharCode(((ascii - 97) + 33) % 26 + 97);
}

// Cuando se llame la función, retornará la variable output:
return output;
}

function decipher(phrase) {
var output = '';

// Bucle que recorra la variable phrase:
for (var i = 0; i < phrase.length; i++) {
// Convierte a ascii
var ascii = phrase.charCodeAt(i);

// Condición y covierte nuevamente en letra
if (ascii > 64 && ascii < 91) // formula para mayusculas
output += String.fromCharCode((((ascii - 65) - 33) + 26 * 2) % 26 + 65);
else if (ascii > 96 && ascii < 123) // para minusculas
output += String.fromCharCode((((ascii - 97) - 33) + 26 * 2) % 26 + 97);
}

// Cuando se llame la función, retornará la variable output:
return output;
}

// Por medio de 'prompt' le pedimos al usuario que ingrese un frase:
var phrase = prompt('INGRESE UNA FRASE: ');

// Condicional para que no puedan dejar el prompt vacio:
if (phrase !== '') {
// Bucle que recorra la variable phrase:
for (var j = 0; j < phrase.length; j++) {
// Condicional para que no ingresen campos vacios:
if (phrase[j] === ' ') {
spaces = true;
break; // Para que cuando spaces sea true, salga del bucle.
} else {
spaces = false;
}
}

// Mensaje si ha ingresado espacios:
if (spaces === true) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

=== true no es necesario. Puedes escribir solo:

if (spaces)

alert('No ingrese campos en blanco');
} else {
// Bucle que recorra la variable phrase:
for (var re = 0; re < phrase.length; re++) {
// Condicional para que no se pueda ingresar numeros:
if (phrase.charCodeAt(re) >= 65 && phrase.charCodeAt(re) <= 90 || phrase.charCodeAt(re) > 96 && phrase.charCodeAt(re) < 123) {
var stringContainsOnlyLetters = true;
} else {
var stringContainsOnlyLetters = false;
break; // Para que cuando stringContainsOnlyLetters sea true, salga del bucle.
}
}

// Condicional si ha ingresado solo letras sin numeros:
if (stringContainsOnlyLetters) {
// Preguntamos y llamamos a las funciones:
do {
var answer = prompt('INGRESE UNA OPCIÓN: \n \n 1. Cifrar \n 2. Descifrar \n 3. Salir');

// Condicional si no ha ingresado nada
if (answer !== '') {
if (answer === '1') {
document.write('Cifrado -> ' + cipher(phrase));
} else if (answer === '2') {
document.write('<p> Descifrado -> ' + decipher(phrase));
} else if (answer === '3') {
document.write('**** ADIÓS ****');
} else {
alert('Ingrese una opción válida');
}
}
} while (answer === '' || (answer !== '1' && answer !== '2' && answer !== '3'));
}

// Mensaje si ha ingresado numeros:
if (!stringContainsOnlyLetters) {
alert('Ingrese solo letras');
}
}

// Mensaje si no ingreso nada en el prompt:
} else {
alert('Ingrese una frase');
}