Last active
July 26, 2021 18:40
-
-
Save mugan86/fe5ec7a5fa06ff2bcdcb74ba1779f5c0 to your computer and use it in GitHub Desktop.
Javascript tips - Parte 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// nº aleatorioentre 0 (incluido) y 1 (no incluido) | |
Math.random(); // 0, 0.02, 0.334,... | |
// nº aleatorio ENTERO entre 0 (incluido) y el máximo (10, no incluido) | |
Math.floor(Math.random() * 10); // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | |
// nº aleatorio ENTERO entre 0 (incluido) y el máximo (11, no incluido) | |
Math.floor(Math.random() * 11); // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 | |
// aleatorio ENTERO entre 0 (incluido) y el máx. (100, incluido por el +1) | |
Math.floor(Math.random() * 100) + 1; // 0, 1, 2, ..., 99, 100 | |
// Obtener un valor entero aleatorio entre min y máx incluidos | |
const getRandomValue = (min, max) => { | |
return Math.floor(Math.random() * (max - min + 1) + min); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const random_hex_color_code = () => { | |
let n = (Math.random() * 0xfffff * 10).toString(16); | |
return "#" + n.slice(0, 6); | |
}; | |
// #8a10dc => Morado | |
// #3daa11 => Verde bosque claro | |
// #1e719f => Azul claro | |
random_hex_color_code(); | |
// Podeís probar esos colores generados en: | |
// https://imagecolorpicker.com/color-code/2c9f1e |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pasándole un tiempo en ms, devuelve cuanto tiempo ha pasado | |
// en formato amigable | |
const formatDuration = ms => { | |
if (ms < 0) ms = -ms; | |
const time = { | |
day: Math.floor(ms / 86400000), | |
hour: Math.floor(ms / 3600000) % 24, | |
minute: Math.floor(ms / 60000) % 60, | |
second: Math.floor(ms / 1000) % 60, | |
millisecond: Math.floor(ms) % 1000 | |
}; | |
// Todas las entradas / day, hour, en elementos array | |
return Object.entries(time) | |
// filtramos tniendo en cuenta el segundo valor de cada elemento | |
// si es diferente a 0 | |
.filter(val => val[1] !== 0) | |
// Mapear clave y valor dentro de las opcionescon valor != 0 | |
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) | |
// Separar por comas | |
.join(', '); | |
}; | |
formatDuration(1001); | |
// '1 second, 1 millisecond' | |
formatDuration(34325055574); | |
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let index = 0; | |
const twitterUsers = ['mugan86', 'ruslangonzalez', 'domini_code']; | |
// Forma clásica (se podría hacer con for, foreach, map,...) | |
while (index < twitterUsers.length) { | |
console.log(twitterUsers[index]); | |
index++; | |
} | |
// Usando una función recursiva | |
const loopValues = (arrayValues, index) => { | |
// Si el indice es menor que la longitud, obtener el valor y rellamar | |
// a la propia función haciendo un pre-incremento en el index antes de enviar | |
// la información | |
if (index < arrayValues.length ) { | |
console.log(arrayValues[index]); | |
return loopValues(arrayValues, ++index) | |
} | |
return; | |
}; | |
loopValues(twitterUsers, 0); | |
// mugan86 | |
// ruslangonzalez | |
// domini_code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Codificar un string | |
const btoa = str => Buffer.from(str, 'binary').toString('base64'); | |
btoa('Anartz Mugika - anartz-mugika'); | |
// QW5hcnR6IE11Z2lrYSAtIGFuYXJ0ei1tdWdpa2E= | |
// Decodificar un string ya codificado antes | |
const atob = str => Buffer.from(str, 'base64').toString('binary'); | |
atob('QW5hcnR6IE11Z2lrYSAtIGFuYXJ0ei1tdWdpa2E='); | |
// 'Anartz Mugika - anartz-mugika |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convierte un número entero en formato de número romano. | |
* Acepta valores entre 1 y 3999 (incluidos). | |
*/ | |
const toRomanNumeral = (numberValue) => { | |
if (!Number.isInteger(numberValue)) { | |
return `${numberValue} NO es un número entero`; | |
} | |
if (numberValue < 1 || numberValue > 3999) { | |
return `${numberValue} debe de ser un número entero entre 1 y 3999 incluidos`; | |
} | |
// Creamos una tabla con arrays de dos valores. | |
// El primero es el carácter del número romano | |
// Segundo es el equivlente en número entero | |
const optionsConversion = [ | |
["M", 1000], | |
["CM", 900], | |
["D", 500], | |
["CD", 400], | |
["C", 100], | |
["XC", 90], | |
["L", 50], | |
["XL", 40], | |
["X", 10], | |
["IX", 9], | |
["V", 5], | |
["IV", 4], | |
["I", 1], | |
]; | |
// Utilizamo reduce () para recorrer los valores en la búsqueda y | |
// dividir repetidamente numberVallue por el valor introducido. | |
return optionsConversion.reduce((acc, [key, valueInt]) => { | |
acc += key.repeat(Math.floor(numberValue / valueInt)); | |
numberValue = numberValue % valueInt; | |
return acc; | |
}, ""); | |
}; | |
toRomanNumeral(3); // 'III' | |
toRomanNumeral(4); // 'IV' | |
toRomanNumeral(6); // 'VI' | |
toRomanNumeral(400); // 'CD' | |
toRomanNumeral(60); // 'LX' | |
toRomanNumeral(100); // 'C' | |
toRomanNumeral(3999); // MMMCMXCIX | |
toRomanNumeral(4000); // 4000 debe de ser un número entero entre 1 y 3999 incluidos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment