Skip to content

Instantly share code, notes, and snippets.

@maurodaprotis
Created March 27, 2019 12:18
Show Gist options
  • Save maurodaprotis/b9098291cf55eb06540514e3fe6cbae5 to your computer and use it in GitHub Desktop.
Save maurodaprotis/b9098291cf55eb06540514e3fe6cbae5 to your computer and use it in GitHub Desktop.
Solución a la actividad enviada por NexoSmart
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Nexosmart JS solution</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<!-- Easy way to insert a new id -->
<form action="/" method="GET">
<label for="id">
Id
<input type="number" id="id" name="id" value="0">
</label>
<button type="submit">Submit</button>
</form>
<div id="app"></div>
<script>
/*
IMPORTANTE:
Esta solución guardará los valores ingresados
en una cookie en el navegador del cliente,
por lo que el mismo podría modificar los valores ingresados.
Por lo tanto, antes de utilizar estos valores en el servidor
se debería realizar un chequeo similar al de la solución hecha
en PHP.
*/
/* Complementary functions */
/* Read cookie from the browser */
function getCookie(cname) {
const name = `${cname}=`;
const cookiesArray = document.cookie.split('; ');
const cookie = cookiesArray.find(currentCookie =>
currentCookie.startsWith(name)
);
if (cookie) {
/* Solo necesitamos el valor de la cookie */
return cookie.split('=')[1];
}
return '';
}
/* Set cookie in the browser */
function setCookie(cname, cvalue) {
document.cookie = `${cname}=${cvalue};`;
}
/* Returns an string of the last inserted values */
function printStoredValues(array) {
return array
.reverse()
.reduce((acc, element) => acc + `Ingresé al array y tengo el ID: ${element} <br>`, '');
}
/* si es superior y solo igual a 2, tomando números pares únicamente hasta llegar a 10 */
function conditionA(value) {
return value >= 2 && value < 10 && value % 2 === 0;
}
/* tienen que ser números enteros(int), sin valores decimales, y pares */
function conditionB(value) {
return typeof value === 'number' && value % 2 === 0;
}
/* Get the url params */
const urlParams = new URLSearchParams(window.location.search);
/* Parse the id into a integer value */
const id = parseInt(urlParams.get('id'));
/* Get the stored values from the cookie - otherwise initialize with an empty array */
const storedValues = JSON.parse(getCookie('storedValues') || '[]');
/* Check conditions */
if (conditionA(id) && conditionB(id)) {
/* Save the new value */
storedValues.push(id);
/* Store the new cookie */
setCookie('storedValues', JSON.stringify(storedValues));
}
/* Get the app node from the dom */
const app = document.getElementById('app');
/* Set inner html with the stored values */
app.innerHTML = printStoredValues(storedValues);
/* Get the input from the dom */
const input = document.getElementById('id');
/* Save the last inserted value on the input */
input.value = id || 0;
</script>
</div>
</body>
</html>
<?php
/* Complementary functions */
function printStoredValues ($array) {
/* Reverse the array to print last inserted value first */
foreach (array_reverse($array) as $key => $value) {
echo "Ingresé al array y tengo el ID: {$value} <br>";
}
}
/* si es superior y solo igual a 2, tomando números pares únicamente hasta llegar a 10 */
function conditionA ($id) {
return ((2 <= $id) && ($id < 10) && ($id % 2 === 0));
}
/* tienen que ser números enteros(int), sin valores decimales, y pares */
function conditionB ($id) {
return ((gettype($id) === 'integer') && ($id % 2 === 0));
}
/* Start session */
session_start();
$hasStoredValues = isset($_SESSION['stored_values']);
/* If stored_values is not set initialize the array */
if (!$hasStoredValues) {
$_SESSION['stored_values'] = [];
}
/* Check if the query param has an id property */
if (isset($_GET['id'])) {
/* Convert id to an integer number (avoid any injection) */
$id = intval($_GET['id']);
/* Check conditions */
if (conditionA($id) && conditionB($id)) {
/* Store valid id on the array */
array_push($_SESSION['stored_values'], $id);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Nexosmart PHP solution</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<!-- Easy way to insert a new id -->
<form action="/" method="GET">
<label for="ID">
Id
<input type="number" id="ID" name="id" value="<?php echo(isset($_GET['id']) ? intval($_GET['id']):0) ?>">
</label>
<button type="submit">Submit</button>
</form>
<?php
/* Check if there are stored values to print */
if ($hasStoredValues) {
/* Call the print function */
printStoredValues($_SESSION['stored_values']);
}
?>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment