Generated nonce length is getting changed - javascript

I am trying to generate fixed length nonce (length 9).
But my code is printing sometimes nonce of 8 length and sometime 9 length.
this is what I am trying to do but with different approach (I have modified it for fixed nonce length)
I am not able to understand why it is printing nonce of length 8 when i am passing length as 9 as argument??
It would be great if someone can tell why this is happening.
Below is complete Nodejs code
var last_nonce = null;
var nonce_incr = null;
// if you call new Date to fast it will generate
// the same ms, helper to make sure the nonce is
// truly unique (supports up to 999 calls per ms).
module.exports = {
getNonce: function(length) {
if (length === undefined || !length) {
length = 8;
}
var MOD = Math.pow(10, length);
var now = (+new Date());
if (now !== last_nonce) {
nonce_incr = -1;
}
nonce_incr++;
last_nonce = now;
var nonce_multiplier = ((nonce_incr < 10) ? 10 : ((nonce_incr < 100) ? 100 : 1000));
var s = (((now % MOD) * nonce_multiplier) + nonce_incr) % MOD;
return s;
}
}
//test code
if(require.main === module) {
console.time("run time");
//importing async module
var async = require('async');
var arr = [];
//generating 1000 length array to use it in making 1000 async calls
//to getNonce function
for(var i=0; i<1000; i++) arr.push(i);
//this will call getNonce function 1000 time parallely
async.eachLimit(arr, 1000, function(item, cb) {
console.log(module.exports.getNonce(9));
cb();
}, function(err) {console.timeEnd("run time");});
}
Sample output:
708201864 --> nonce length 9
708201865
708201866
70820190 --> nonce length 8 (why it is coming 8?? when passed length is 9)
70820191
70820192
70820193
70820194
70820195
70820196
70820197
70820198
70820199
708201910
708201911
708201912
708201913
708201914
708201915
708201916
708201917
708201918

In case someone needs it, here is a nonce generator free from convoluted logic, allowing you to control both character sample and nonce size:
const generateNonce = (options) => {
const {
length = 32,
sample = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
} = options || {};
const getRand = () => Math.floor(Math.random() * sample.length);
return Array.from({ length }, () => sample.charAt(getRand())).join('');
};
If you prefer Typescript:
const generateNonce = (options?: { sample?: string, length?: number }) => {
const {
length = 32,
sample = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
} = options || {};
const getRand = () => Math.floor(Math.random() * sample.length);
return Array.from({ length }, () => sample.charAt(getRand())).join('');
};

Related

Random Line from .txt file in Node.js [duplicate]

This question already has answers here:
Grabbing a random line from file
(4 answers)
Closed 1 year ago.
How can I grab a random line from a text file using Node.js?
What modifications do I need to make to my code?
const readline = require('readline');
const fs = require('fs');
var file = 'path.to.file';
var rl = readline.createInterface({
input: fs.createReadStream(file),
output: process.stdout,
terminal: false
});
rl.on('line', function (line) {
console.log(line) // print the content of the line on each linebreak
});
You could do worse than something like this. It:
0. Reads the file into memory as an array of lines
Randomly shuffles the corpus
Each call to next() returns the next line;
When the corpus is exhausted, repeats from step #1 (shuffling)
const fs = require('fs');
/**
*
* #param {*} min
* #param {*} max
* #returns random integer n such that min <= n <= max
*/
const randomInt = (min, max) => {
const range = max - min + 1;
const n = min + Math.floor( Math.random() * range );
return n;
}
exports = module.exports = class RandomLines {
constructor(pathToTextFile) {
this.path = pathToTextFile;
this.n = undefined;
this.lines = undefined;
}
next() {
if (!this.lines) {
this.lines = fs.readFileSync('./some/path/to/a/file.txt').split( /\r\n?|\n/g );
this.n = this.lines.length;
}
if (this.n >= this.lines.length) {
this.shuffleLines();
this.n = 0;
}
return this.lines[n++]
}
init() {
}
/**
* Shuffles the array lines
*/
shuffleLines() {
for (let i = this.lines.length - 1 ; i > 0 ; --i ) {
const j = randomInt(0, i );
const temp = this.lines[i];
this.lines[i] = this.lines[j];
this.lines[j] = this.lines[i];
}
}
}
Usage is pretty straightforward:
const RandomLines = require('./random-lines');
const randomLines = new RandomLines('./path/to/some/file.txt');
while (true) {
console.log( randomLines.next() );
}

Javascript adding multiple arrays in a loop

I am trying to add multiple arrays in javascript.
Here are my arrays I have made, and are working.
function getAmountSpent(){
var amountSpent = ((Math.random() * 500) + 1);
return amountSpent.toFixed(2)
}
function getGift(){
var gift = ((Math.random()* 50) + 1);
return gift.toFixed(2)
}
var names = ["Jeremy","Arun","Alisa","Rohan","Dana"];
var spent = [];
for (let i = 0; i < 5; i++) {
spent.push(getAmountSpent());
}
var gifts = [];
for (let i = 0; i<5; i++) {
gifts.push(getGift());
}
What I need help with is adding these arrays in a new function. I have began writing the code, and I am not sure what is wrong.
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals())
}
function getSumTotals(a){
totals= spent+(spent * gifts);
return totals.toFixed(2)
}
From what you can see, I am trying to add up the totals much like this:
totals[0] = spent[0] + (spent[0] * gifts[0]);
totals[1] = spent[1] + (spent[1] * gifts[1]);
totals[2] = spent[2] + (spent[2] * gifts[2]);
totals[3] = spent[3] + (spent[3] * gifts[3]);
totals[4] = spent[4] + (spent[4] * gifts[4]);
if it helps, the professor added guided instructions for function getSumTotals(a) stating:
This function will return the sum of the elements in array a.
You will be passing the array that holds your totals to
the parameter a. Be sure to treat the values in a as numbers.
I am not sure if this helps but here is the output to my document.
Current Total should equal (spent) + (spent * gifts). For instance, for Jeremy in this example, current total should equal:
$36.55 + ($36.55*0.0626) = $38.83. Since there are many variables involved, I am not 100% sure what I should write for function getSumTotals(a)
The parameter "a" is a placeholder because I am not sure how many parameter values I need, and the proper format I need to use.
As for the code...
You're both
not passing an index to getSumTotals
not using this parameter within getSumTotals to access your spent and gifts arrays
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals(i)) // you were missing i
}
function getSumTotals(idx) { // I took liberties to rename this
totals = spent[idx] + (spent[idx] * gifts[idx]);
return totals.toFixed(2);
}
Now for the Math...
All that said, this math of spent[i] + spent[i] * gifts[i] doesn't make much sense either. Was this specified in the problem?
you may use like this
defined gifts
gifts=[45,43,32];
defined spends
spends=[43,32,21];
this is the getSumTotal funtion
getSumTotal=(x)=>(x.a+x.b)
this is where added
totals=gifts.map((d1,i)=>{
return fu({a:gifts[i],b:spends[i]})
})
I understand this is your assignment, however - if the idea is to both generate arrays, and then add them together, it is a redundant step. Just use the name array to iterate once and do all your calculations within that single loop.
Here, I had some fun and took some liberties, but hopefully you see why multiple arrays are redundant.
function getSumTotals() {
const getAmountSpent = () => Math.random() * 500 + 1;
const getGift = () => Math.random() * 50 + 1;
const names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];
let totals = []
names.forEach((name, i) => {
let spent = getAmountSpent()
let gifts = getGift()
let $$$ = (spent + spent * gifts).toFixed(2);
totals[i] = $$$
console.log(`${name} cost me $${$$$}${'!'.repeat(($$$/1000) | 1)}`)
});
return totals;
}
getSumTotals()
Note, that toString returns a type of "String", but not "Number".
When you try to sum a number with string, you get a concatenated string "1" + 2 = "12"
To turn a string into Number, you must use a Number("str") function, or just a bunary + before the string:
console.log( "1" + 2 );
console.log( Number("1") + 2 );
console.log( +"1" + 2 );
Also, you use the same loop 3 times, but can use just one loop instead, and call all functions inside the one loop. And use your array.length instead of fixed number 5:
let names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];
let spent = [];
let gifts = [];
let totals = [];
for (let i = 0; i < names.length; i++) {
spent.push( getAmountSpent() );
gifts.push( getGift() );
totals.push( getSumTotals(i) );
}
console.log( totals );
function getAmountSpent() {
return rand(1, 500, 2);
}
function getGift() {
return rand(1, 50, 2);
}
function getSumTotals(i) {
return +( spent[i] * ( 1 + gifts[i] ) ).toFixed(2);
}
function rand(from, to, fixed = 0){
return +(Math.random()*( to - from ) + from).toFixed(fixed);
}
P.s. Math.random() returns a number between 0 (included) and 1 (not included). If you need a random number between (example) 20 and 100, Math.random()*(100-20) will give a number between 0 and 80. After adding +20 to the result, you get a number from 20 to 100. That's what does this formula Math.random()*( to - from ) + from
P.P.s. Another way, to get the same thing:
var names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"].reduce( (prev, elem) => {
let spent = rand(1, 500, 2);
let gift = rand(1, 50, 2);
prev[elem] = new UserData( spent, gift );
return prev;
}, {});
console.log( "Jeremy spent: " + names.Jeremy.spent );
console.log( names );
function rand(from, to, fixed = 0){
return +(Math.random()*( to - from ) + from).toFixed(fixed);
}
function UserData(spent, gift){
this.spent = spent;
this.gift = gift;
this.total = +(spent * ( 1 + gift )).toFixed(2);
}
/* Google → Array reduce, Constructor functions */
function getAmountSpent(){
let amountSpent = ((Math.random() * 500) + 1);
return Number(amountSpent.toFixed(2))
}
function getGift(){
let gift = ((Math.random()* 50) + 1);
return Number(gift.toFixed(2))
}
let names = ["Jeremy","Arun","Alisa","Rohan","Dana"];
let spent = [];
let gifts = [];
let totals =[];
for (let i = 0; i < names.length; i++) {
spent.push(getAmountSpent());
gifts.push(getGift());
totals[i] = (spent[i]+(spent[i] * gifts[i])).toFixed(2);
totals[i] = parseFloat(totals[i])
}
Hi there
I don't think you need a function to add the totals. you just need to loop through and assign totals[i] to spent[i] + (spent[i] * gifts[i]).
then you can use the parseFloat and toFixed function to change the string to a number. remember toFixed() function turns numbers to string. so you need to use the parseFloat to change it to number again as shown in the code above. or you can come up with an easy way of changing it to number. I hope this helps!

Add Two Number leetcode algo

I was doing following leetCode Problem: https://leetcode.com/problems/add-two-numbers/
And I am not sure why one of my test case is failing
So the question is
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list.
You may assume the two numbers do not contain any leading zero, except
the number 0 itself.
For which I have written following algo
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* #param {ListNode} l1
* #param {ListNode} l2
* #return {ListNode}
*/
const makeLinkedList = (inArr, i) => {
if (i < 0) return null
return { val:inArr[i], next:makeLinkedList(inArr, i-1)}
}
var addTwoNumbers = function(l1, l2) {
let sum = 0
let i = 1
while(l1 || l2) {
if (l1 && l2) {
sum = sum + l1.val*i + l2.val*i
l1 = l1.next
l2 = l2.next
} else {
if (l1) {
sum = l1.val*i + sum
l1 = l1.next
}
if (l2) {
sum = l2.val*i + sum
l2 = l2.next
}
}
i = i*10
}
const sumToString = sum.toLocaleString('fullwide', {useGrouping:false});
return makeLinkedList(sumToString, sumToString.length-1)
};
The reason in the above code I have used while loop instead of recursively calling functions is mainly to make it more optimized.
anyway, For the following input, my test case is failing
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[5,6,4]
i.e my output is coming to be [0,3,NaN,NaN,1] instead of [6,6,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
As a note, leetCode compiler will convert array to linkedlist on input. Can someone help me in figuring out why my input might be failing?
When JavaScript stringifies a number in scientific notation, there will be a + sign for positive exponents. That sequence you see is 1E+30, the NaNs are standing for + and E (because of the reverted order). In fact you could have put a console.log(sum) or console.log(sumToString) and catch the issue without knowing this, just simply seeing what is there.
Not all languages tell you the maximum value they can store without loss in precision, but JavaScript in particular does, Number.MAX_SAFE_INTEGER contains the value 9 007 199 254 740 991 so it is a bit more than 9E+15, far less than 1 + 1E+30 (the longer number).
What you are expected to do is to add the numbers like you have learned in elementary school: add two digits, write one digit, and see if there is an 1 to carry to the next digit-pair you are going to add.
Iterative version:
function makeLinkedList(arr,i){
i=i || 0;
return i<arr.length?{val:arr[i], next:makeLinkedList(arr,i+1)}:null;
}
var addTwoNumbers = function(l1, l2) {
var snt={next:null};
var cur=snt;
var carry=0;
while(l1 || l2 || carry){
cur.next={next:null};
cur=cur.next;
var sum=(l1?l1.val:0)+(l2?l2.val:0)+carry;
if(sum<10){
cur.val=sum;
carry=0;
} else {
cur.val=sum-10;
carry=1;
}
l1=l1?l1.next:null;
l2=l2?l2.next:null;
}
return snt.next;
}
var a=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
var b=[5,6,4];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
a=[9,9];
b=[1,9];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
Recursive version:
function makeLinkedList(arr,i){
i=i || 0;
return i<arr.length?{val:arr[i], next:makeLinkedList(arr,i+1)}:null;
}
var addTwoNumbers = function(l1, l2, carry) {
if(!(l1 || l2 || carry))
return null;
carry=carry || 0;
var sum=(l1?l1.val:0)+(l2?l2.val:0)+carry;
return {
val: sum % 10,
next: addTwoNumbers(l1?l1.next:null,l2?l2.next:null,sum>9?1:0)
};
}
var a=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
var b=[5,6,4];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
a=[9,9];
b=[1,9];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
Solution for the problem in JavaScript.
var addTwoNumbers = function (l1, l2) {
let reminder = 0;
let l1Node = l1;
let l2Node = l2;
let list = new ListNode(0);
let currentNode = list;
while (l1Node || l2Node) {
const valueL1 = l1Node ? l1Node.val : 0;
const valueL2 = l2Node ? l2Node.val : 0;
let sum = valueL1 + valueL2 + reminder;
reminder = 0;
if (sum > 9) {
reminder = Math.floor(sum / 10);
sum = sum % 10;
}
currentNode.next = new ListNode(sum);
currentNode = currentNode.next;
l1Node = l1Node ? l1Node.next : null;
l2Node = l2Node ? l2Node.next : null;
}
if (reminder != 0) {
currentNode.next = new ListNode(reminder);
currentNode = currentNode.next;
}
return list.next;
};
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
const l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
const l2 = new ListNode(5, new ListNode(6))
const res = addTwoNumbers(l1, l2);
console.log(res);

Get duration of a collection of audios

I am creating an audio player from an audio collection on an HTML page:
...
<div class="tr track" id="01">
<div class="td">
<button class="play" onclick="Play(this)">▶</button>
<button class="play" onclick="Pause(this)">❚❚</button>
<span class="title">A Corda da Liberdade</span>
</div>
<div class="td">
<audio preload="metadata" src="discografia/le-gauche-gnosis/01-a-corda-da-liberdade.ogg"></audio>
</div>
<div class="td">
<span class="duracao"></span>
</div>
</div>
...
I want the <span class="duracao"></span> element to show the duration of the audio it is related to:
// This function format the audio duration number in the way I want to present
function secToStr(sec_num) {
sec_num = Math.floor( sec_num );
var horas = Math.floor(sec_num / 3600);
var minutos = Math.floor((sec_num - (horas * 3600)) / 60);
var segundos = sec_num - (horas * 3600) - (minutos * 60);
if (horas < 10) {horas = "0"+horas;}
if (minutos < 10) {minutos = "0"+minutos;}
if (segundos < 10) {segundos = "0"+segundos;}
var tempo = minutos+':'+segundos;
return tempo;
}
var i;
var audios = document.getElementsByTagName('audio'); // get all audios elements of the player
for (i = 0; i < audios.length; i++) { // looping through audios
var audio = audios[i]; // get actual audio
var duracao = audio.parentNode.nextElementSibling.getElementsByClassName('duracao')[0] // get actual audio 'duration <span>'
audio.onloadedmetadata = function() {
duracao.innerHTML = secToStr(audio.duration);
}
}
The for loop is supposed to do the job but is just adding the duration of the last audio element to the last <span class="duracao"></span> element:
Any help?
The general approach with asynchronous loops would be to promisify the async action and then wait for a Promise.all(all_promises).
However, in this particular case, it might not be that easy:
Some browsers (Chrome to not tell their name) have a limit on the maximum number of parallel network requests a page can make for Media.
From there, you won't be able to get the duration of more than six different media at the same time...
So we need to load them one after the other.
The async/await syntax introduced in ES6 can help here:
const urls = [
'1cdwpm3gca9mlo0/kick.mp3',
'h8pvqqol3ovyle8/tom.mp3',
'agepbh2agnduknz/camera.mp3',
'should-break.mp3',
'/hjx4xlxyx39uzv7/18660_1464810669.mp3',
'kbgd2jm7ezk3u3x/hihat.mp3',
'h2j6vm17r07jf03/snare.mp3'
]
.map(url => 'https://dl.dropboxusercontent.com/s/' + url);
getAllDurations(urls)
.then(console.log)
.catch(console.error);
async function getAllDurations(urls) {
const loader = generateMediaLoader();
let total = 0;
for(let i = 0; i < urls.length; i++) {
total += await loader.getDuration(urls[i]);
}
return total;
}
// use a single MediaElement to load our media
// this is a bit verbose but can be reused for other purposes where you need a preloaded MediaElement
function generateMediaLoader() {
const elem = new Audio();
let active = false; // so we wait for previous requests
return {
getDuration,
load
};
// returns the duration of the media at url or 0
function getDuration(url) {
return load(url)
.then((res) => res && res.duration || 0)
.catch((_) => 0);
}
// return the MediaElement when the metadata has loaded
function load(url) {
if(active) {
return active.then((_) => load(url));
}
return (active = new Promise((res, rej) => {
elem.onloadedmetadata = e => {
active = false;
res(elem);
};
elem.onerror = e => {
active = false;
rej();
};
elem.src = url;
}));
}
}
But it's also very possible to make it ES5 style.
var urls = [
'1cdwpm3gca9mlo0/kick.mp3',
'h8pvqqol3ovyle8/tom.mp3',
'agepbh2agnduknz/camera.mp3',
'should-break.mp3',
'/hjx4xlxyx39uzv7/18660_1464810669.mp3',
'kbgd2jm7ezk3u3x/hihat.mp3',
'h2j6vm17r07jf03/snare.mp3'
]
.map(function(url) {
return 'https://dl.dropboxusercontent.com/s/' + url;
});
getAllDurations(urls, console.log);
function getAllDurations(urls, callback) {
var loader = new Audio();
var loaded = 0;
var total = 0;
loader.onloadedmetadata = function(e) {
total += loader.duration;
loadNext();
};
loader.onerror = loadNext;
loadNext();
function loadNext() {
if(loaded >= urls.length) {
return callback(total);
}
loader.src = urls[loaded++];
}
}
This is an excellent place to learn about, and then use Array.reduce() instead of a for-loop.
The concept of reduce is that you start with some starting value (which can be anything, not just a number), and you then walk through the array in a way that, at ever step, lets you run some code to update that value. So:
const total = [1,2,3,4,5].reduce( (sofar, value) => sofar + value, 0)
will run through the array, with start value 0, and at every step it runs (sofar, value) => sofar + value, where the first argument is always "whatever the original start value is at this point". This function assumes that value is a number (or a string) and adds (or concatenates) it to the start value. So at each step we get:
start = 0
first element: add 1 to this value: 0 + 1 = 1
second element: add 2 to this value: 1 + 2 = 3
third element: add 3 to this value: 3 + 3 = 6
fourth element: add 4 to this value: 6 + 4 = 10
fifth element: add 5 to this value: 10 + 5 = 15
We can apply the same to your audio elements: once they're all done loading in, you can tally their total duration with a single reduce call:
const total = audios.reduce((sofar, audioElement) => {
sofar += audioElement.duration;
}, 0); // this "0" is the starting value for the reduce-function's first argument
console.log(`Total number of seconds of play: ${total}`);
And then you can convert total into whatever format you need.
Alternatively, you can keep a global tally, but making each audo element update the total length themselves, simply by finishing loading:
let total = 0;
function updateTotal(increment) {
total += increment;
// and then update whatever HTML element shows that value on the page,
// in whatever format you need.
}
document.querySelectorAll('audio').forEach(element => {
element.onload = (evt) => {
updateTotal(element.duration);
})
});

Look up tables and integer ranges - javascript

So I am looking to create look up tables. However I am running into a problem with integer ranges instead of just 1, 2, 3, etc. Here is what I have:
var ancient = 1;
var legendary = 19;
var epic = 251;
var rare = 1000;
var uncommon = 25000;
var common = 74629;
var poolTotal = ancient + legendary + epic + rare + uncommon + common;
var pool = general.rand(1, poolTotal);
var lootPool = {
1: function () {
return console.log("Ancient");
},
2-19: function () {
}
};
Of course I know 2-19 isn't going to work, but I've tried other things like [2-19] etc etc.
Okay, so more information:
When I call: lootPool[pool](); It will select a integer between 1 and poolTotal Depending on if it is 1 it will log it in the console as ancient. If it hits in the range of 2 through 19 it would be legendary. So on and so forth following my numbers.
EDIT: I am well aware I can easily do this with a switch, but I would like to try it this way.
Rather than making a huge lookup table (which is quite possible, but very inelegant), I'd suggest making a (small) object, choosing a random number, and then finding the first entry in the object whose value is greater than the random number:
// baseLootWeight: weights are proportional to each other
const baseLootWeight = {
ancient: 1,
legendary: 19,
epic: 251,
rare: 1000,
uncommon: 25000,
common: 74629,
};
let totalWeightSoFar = 0;
// lootWeight: weights are proportional to the total weight
const lootWeight = Object.entries(baseLootWeight).map(([rarity, weight]) => {
totalWeightSoFar += weight;
return { rarity, weight: totalWeightSoFar };
});
console.log(lootWeight);
const randomType = () => {
const rand = Math.floor(Math.random() * totalWeightSoFar);
return lootWeight
.find(({ rarity, weight }) => weight >= rand)
.rarity;
};
for (let i = 0; i < 10; i++) console.log(randomType());
Its not a lookup, but this might help you.
let loots = {
"Ancient": 1,
"Epic": 251,
"Legendary": 19
};
//We need loots sorted by value of lootType
function prepareSteps(loots) {
let steps = Object.entries(loots).map((val) => {return {"lootType": val[0], "lootVal": val[1]}});
steps.sort((a, b) => a.lootVal > b.lootVal);
return steps;
}
function getMyLoot(steps, val) {
let myLootRange;
for (var i = 0; i < steps.length; i++) {
if((i === 0 && val < steps[0].lootVal) || val === steps[i].lootVal) {
myLootRange = steps[i];
break;
}
else if( i + 1 < steps.length && val > steps[i].lootVal && val < steps[i + 1].lootVal) {
myLootRange = steps[i + 1];
break;
}
}
myLootRange && myLootRange['lootType'] ? console.log(myLootRange['lootType']) : console.log('Off Upper Limit!');
}
let steps = prepareSteps(loots);
let pool = 0;
getMyLoot(steps, pool);

Categories

Resources