Para executar:
node sorteio -s=[sorteios] -n=[numeros] -min=[minimo] -max=[maximo]
Por padrão sorteios = 1
, numeros = 6
, min=1
e max=60
.
Para instruções:
node sorteio -h
const { argv } = process; | |
function main(argv) { | |
argv = argv.slice(2); | |
if (argv[0] == 'help' || argv[0] == '-h') { | |
console.log('Execute "node sorteio -s=[sorteios] -n=[numeros] -min=[min] -max=[max], -r=[1 ou 0]"') | |
return; | |
} | |
args = {}; | |
argv.forEach(a => { | |
let [k, v] = a.replace('-', '').split('='); | |
args[k] = v; | |
}) | |
let { s, n, min, max, r } = args; | |
//[s, n, min, max] = argv; //pela posição do array | |
[sorteios, numeros, min, max, repeat] = [+s || 1, +n || 6, min != undefined ? +min : 1, +max || 60, !!r || false] | |
console.log({ sorteios, numeros, min, max, repeat }) | |
joga(sorteios, numeros, min, max, repeat); | |
} | |
function random(min = 1, max = 60) { | |
return Math.floor( | |
Math.random() * (max - min + 1) + min | |
); | |
} | |
function joga(sorteios = 1, numeros = 6, min = 1, max = 60, repeat = false) { | |
//console.log(`${sorteios} sorteios de ${numeros} numeros\n------------------------`); | |
let resultado = []; | |
for (let i = 1; i <= sorteios; i++) { | |
let atual = sorteio(numeros, min, max, repeat); | |
resultado.push(atual); | |
} | |
console.table(resultado); | |
} | |
function sorteio(numeros = 6, min = 1, max = 60, repeat = false) { | |
let resultado = []; | |
if (max < numeros) repeat = true | |
while (resultado.length < numeros) { | |
let r = random(min, max); | |
if (repeat || !resultado.includes(r)) resultado.push(r); | |
} | |
return resultado; | |
} | |
main(argv); |