Imagine that I have a variable called incomingValue and I'm getting a number from an API as it's value. The values are between 0 to 1 and I'm setting two other variables depending on this value using bunch of if statements like you see below.
var incomingValue; // Set by an API
var setValueName;
var setValueIcon;
if (incomingValue < 0.10 ) {
setValueName = 'something';
setValueIcon = 'something.png'
}
if (incomingValue > 0.09 && incomingValue < 0.20 ) {
setValueName = 'somethingElse';
setValueIcon = 'somethingElse.png';
}
In the actual implementation, I have around 10 if statements checking for specific intervals up until 1. e.g. do this if it's more than 0.10 but less than 0.16 and so on.
As a JavaScript beginner it feels like this is not the right way to do things even though it gets the job done. How would I refactor this code?
Update: As requested, I'm adding the full set of intervals that are used in the original code. I haven't included the full list before because the intervals don't follow a certain pattern.
0 to 0.09
0.09 to 0.20
0.20 to 0.38
0.38 to 0.48
0.48 to 0.52
0.52 to 0.62
0.61 to 0.80
0.80 to 1
Remember the single responsibility principle. Take that code out to a separate function like so:
function determineNameAndIcon(incomingValue) {
if (incomingValue < 0.10) {
return {
name: "something",
icon: "something.png"
};
}
if (incomingValue < 0.20) {
return {
name: "somethingElse",
icon: "somethingElse.png"
};
}
// etc
return {
name: "somethingDefault",
icon: "somethingDefault.png"
};
}
// ...
var incomingValue; // Set by an API
const {
name: setValueName,
icon: setValueIcon
} = determineNameAndIcon(incomingValue);
Notice that determineNameAndIcon is still a very long function with repeating parts. This can be further refactored to a data-driven version:
const nameAndIconList = [
{
maxValue: 0.10,
name: "something",
icon: "something.png"
},
{
maxValue: 0.20,
name: "somethingElse",
icon: "somethingElse.png"
},
// ...
];
const nameAndIconDefault = {
name: "somethingDefault",
icon: "somethingDefault.png"
};
function determineNameAndIcon(incomingValue) {
for (let item of nameAndIconList) {
if (incomingValue < item.maxValue) {
return item;
}
}
return nameAndIconDefault;
}
function findValue(incomingValue){
var itemValues = [
[.06, "valueName", "valueIcon"],
[.08, "valueName", "valueIcon"],
[.09, "valueName", "valueIcon"],
[.1, "valueName", "valueIcon"],
]
var foundValues = itemValues.
filter(v=>v[0] >= incomingValue)
.sort();
if(foundValues.length == 0){
throw "incoming value not found."
}
return foundValues[0];
}
let value = findValue(.079);
console.log( value );
This is assuming that you want the lowest portion of the range to be the one selected (just reverse the sort if you want it to be the highest).
A solution using an array where you set the ranges for your results:
var categories = [{something: [0, 0.1]},
{somethingElse: [0.1, 0.2]},
{somethingElse2: [0.2, 0.3]},
{anotherSomething: [0.3, 1]}];
function res(number){ return Object.keys(categories.filter(function(elem) {
var key = elem[Object.keys(elem)];
return number >= key[0] && number < key[1]
})[0])[0]};
var incomingValue = 0.12;
var setValueName = res(incomingValue);
var setValueIcon = res(incomingValue) + ".png";
console.log(setValueName, setValueIcon);
Mb I will refactor this code like this but it's not really standard patter :
var incomingValue=0.08; // Set by an API
var setValueName;
var setValueIcon;
switch(true) {
case incomingValue < 0.10 :
setValueName = "something";
setValueIcon ="something.png";
alert("Hello World !");
break;
case incomingValue > 0.09 && incomingValue < 0.20 :
setValueName = "somethingElse";
setValueIcon ="somethingElse.png";
alert("Hello !");
break;
default :
alert("Adele !");
break;
}
The mortal will use the if...else if... condition like this :
var incomingValue; // Set by an API
var setValueName;
var setValueIcon;
if (incomingValue < 0.10 ) {
setValueName = "something";
setValueIcon ="something.png"
} **else** if (incomingValue > 0.09 && incomingValue < 0.20 ) {
setValueName = "somethingElse";
setValueIcon ="somethingElse.png"
}
But I dont like this way...My opinion :)
Related
I've been trying to translate this query into MapReduce for a few days. Specifically, I need to figure out how many different cars have driven "N" kilometers.
Query:
db.adsb.group({
"key": {
"KM": true
},
"initial": {
"countCar": 0
},
"reduce": function(obj, prev) {
if (obj.Matricula != null) if (obj.Matricula instanceof Array) prev.countCar += obj.Matricula.length;
else prev.countCar++;
},
"cond": {
"KM": {
"$gt": 10000,
"$lt": 45000
}
}
});
Each document in Mongo has this form:
{
"_id" : ObjectId("5a8843e7d79a740f272ccc0a"),
"KM" : 45782,
"Matricula" : "3687KTS",
}
I'm trying to get something like:
/* 0 */
{
“KM” : 45000,
“total” : 634
}
/* 1 */
{
“KM” : 46000,
“total” : 784
}
My code is below, and it compiles but does not give me the expected results.
In particular, every time I enter 'reduce' it seems to reset all the values to 0, which prevents me from accumulating the registrations.
One of my problems is that when handling large amounts of information, the function must iterate several times ' reduce'.
I also don't know if it could be done that way, or I would need to return a list of car plates and their counter together in 'reduce'; and then in finalize add it all up.
// Map function
var m = function() {
if (this.KM > 10000 && this.KM < 45000) { // So that i can get KM grouped together by thousands (10000, 20000, 30000...)
var fl = Math.round(this.KM / 1000) * 1000;
var car = this.Matricula
emit (fl, car);
//print("map KM=" + fl + " Matricula= " + car);
}
};
// Reduce function
var r = function(key, values) {
var ya_incluido = false;
var cars_totales = 0;
var lista_car = new Array();
//print( key + " ---- " + values);
for (var i=0; i < values.length;i++)
{
for (var j=0; j < lista_car.length;j++)
{
if(values[i] == lista_car[j]) { //If it is already included, don't aggregate it
ya_incluido = true;
}
} if (ya_incluido != true) { //If it is not included, add it to lista_av list.
lista_car.push(values[i]);
} ya_incluido = false;
}
cars_totales = lista_av.length; //The number of distinct cars is equal to the lenght of the list we created
return cars_totales;
};
// Finalize function
var f = function(key,value) {
// Sum up the results?
}
db.runCommand( {
mapReduce: "dealer",
map: m,
reduce: r,
finalize: f,
out: {replace : "result"}
} );
I found the answer and a really good explanation here: https://stackoverflow.com/a/27532153/13474284
I found the answer and a really good explanation here: https://stackoverflow.com/a/27532153/13474284
I couldn't find a way to return in 'reduce' the same thing that came from ' map' . And since it was run several times, it only got the results of the last iteration. The way it appears in the link, the problem is solved without any difficulty.
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);
I've been working on a javascript class to simplify the sorting and comparing of library of congress call numbers. For the most part, the majority of it is working, except for one of the the main methods to return a sorted list. I can do the sort outside of the class given other methods of the class, so I'm not sure why I'm losing the scope when I enter the sort() function.
I'm not sure if there's a way I can pass the scope into the sort() or what I need to do to have access to that method.
I've created a github gist of the javascript and a quick html test of the class (including the error) that should demonstrate things:
https://gist.github.com/rayvoelker/accaa95c6b5db28f7f84429f8a3d8cdf
Here's the class methods that I'm having trouble with. Maybe I'm just not seeing something that should be simple.
locCallClass.prototype.localeCompare = function (a, b) {
try {
var a_norm = this.returnNormLcCall(a),
b_norm = this.returnNormLcCall(b);
return ( a_norm < b_norm ? -1 : (a_norm > b_norm ? 1 : 0) );
}
catch (err) {
// console.log("error")
}
}
locCallClass.prototype.sortCallNumbers = function (callnumbers) {
var sorted = callnumbers.sort(function (a,b) {
return this.localeCompare(a,b);
});
return sorted;
}
And here is the way that I'm calling it:
var loc = new locCallClass();
var set1 = ["LC 346 .65 .B29","LC 346 .M634","HX 754 .5 .C15","HX 754 .C7723"];
var sorted = loc.sortCallNumbers(set1);
And here's a snippet of the same demonstration code from the gist:
// js-loc-callnumbers
// A javascript class to normalize and perform various sorting options on
// Library of Congress Call Numbers within a library institution.
function locCallClass() {
// the regular expression that defines the Library of
// Congress call number. Thanks to Bill Dueber's post on the subject for the regex
// http://robotlibrarian.billdueber.com/2008/11/normalizing-loc-call-numbers-for-sorting/
this.lc = /^\s*([A-Z]{1,3})\s*(\d+(?:\s*\.\s*\d+)?)?\s*(?:\.?\s*([A-Z]+)\s*(\d+)?)?(?:\.?\s*([A-Z]+)\s*(\d+)?)?\s*(.*?)\s*$/;
//local storage for an array of call numbers
this.callNumberArray = [];
//a mostly sorted array of call numbers for testing
this.testCallNumbers = ["Z10.1 A", "Z5.1 A", "CB3 .C55", "CS418 .J82", "CS425 .B95", "D21 .W93", "D21.1.D58 1981", "D761 .W54", "D761.9.F7 G8", "DA86 .P884", "DA86 .R52", "DA506.A2 A4", "DA506.A2 B75", "DA784.5 .M23 1989", "DA785 .S12", "DC129 .W6", "DC130.A2 H3", "DF623 .C46", "DF631 .B313", "DK 267 .W78", "DK268.A1D56213 1999", "DS 70.7 .O6", "DS 70.7 .S27", "DS557.C28S6", "DS 557 .F3", "DS 917 .W47", "DS 917.35 .P33", "DT 636 .S5 A3", "DT636.2.F65 1996", "E 160 .F72", "E 160 .F73", "E184.A1I444 1992", "E184.A1I445 1996", "E 302 .J442 1984", "E302.J442 2004B", "E 487 .C746", "E 487 .C746 1966", "E 876 .U84 1986", "E 876 .V53", "F548.9.N4R437 2005", "F548.9.N4S77 2007", "F 1656 .C7 1968", "F 1659 .B55 F4", "GN 51 .A58", "GN 51 .A58 1988B", "GV 741 .B56", "GV741 .I58", "Q183.9.I34 2002", "Q183.9.L45 1993", "QA 29 .P775 A3 1987", "QA29.R3A4 1995", "QA 76.758 .H86 1989", "QA76.758.K365 2008", "QA 164 .C63 1969", "QA 164 .C63 1969", "QA274.73.R84 2004", "QA274.73.S2813 1999", "QA 353 .E5 Z4313 1993", "QA 353 .G44 W55 1990", "QA 640.7 .B55 1970", "QA641.A587 1996", "QC 173.98 .M44 V.1", "QC 173.98 .M44 V.1", "QD 21 .C51", "QD 21 .C51", "QD501 .B242 V.37", "QD501.B242 V.38", "QH 81 .B73", "QH 81 .B754", "QH540.I5", "QH540.I5", "QK 314 .F54", "QK 321 .A3613", "QL951 .C8", "QL951 .C8", "QP 601 .C733 V.171", "QP 601 .C733 V.172", "RA 410.7 .C5", "RA 410.7 .E73", "RC455.S8 1961", "RC 455 .S928", "RD 98 .G38", "RD 99 .E42 1955", "S 942 .C6 1974", "S 942 .K63 1972", "TA166.W68 1980", "TA167.A965 1998", "TA1520.S87 2007", "TA1520.W35 1998", "TD 741 .I33", "TD 741 .I33 1956", "TJ163.2 .A55", "TJ163.2 .A55", "TK5105.875.I57G723 2005", "TK5105.875.I57H338 1996", "TL215.J58L35 2005", "TL215.M18D53 2005", "TP155.C69 V.5 1997", "TP 155 .C74 1986", "TS156 .I838 2003", "TS 156 .J324"];
}
// locCallClass.returnNormLcCall(call_number)
// returns a "normalized" call number
locCallClass.prototype.returnNormLcCall = function(call_number) {
var result = this.lc.exec(call_number);
if (!result) {
throw new Error(call_number + " Not a Call Number");
}
// track the position of what we're looking at in the callnumber
var before_first_cutter = true;
var return_string = "";
// work through the results starting at 1 (the 0 value in the array is the original input)
for(var i=1; i<=(result.length-1); i++) {
if (i>1) {
return_string = return_string + "."
}
if (i>2) {
before_first_cutter = false;
}
return_string = return_string + this.padZed(result[i], before_first_cutter);
}
// TODO: consider adding further checks to see if the return string
// consists of 8 segments 9 characters and throw an error if not
return return_string;
}
// locCallClass.localeCompare(b,a)
// replicates functionality of the normal compare function
// so that it may be used in external sorting operations:
//
// A negative number if the reference string (a) occurs before the
// given string (b);
// positive if the reference string (a) occurs after
// the compare string (b);
// 0 if they are equivalent.
locCallClass.prototype.localeCompare = function (a, b) {
try {
var a_norm = this.returnNormLcCall(a),
b_norm = this.returnNormLcCall(b);
return ( a_norm < b_norm ? -1 : (a_norm > b_norm ? 1 : 0) );
}
catch (err) {
// console.log("error")
}
}
// locCallClass.sortCallNumbers()
// takes a variable list of call numbers as arguments, and returns
// a sorted array of call numbers in their original format/
// You can also use this method with an array like the following:
// loc.sortCallNumbers.call(loc_instance,input)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
//
// TODO: Consider removing this method, instead using something like the
// following:
// var loc = new locCallClass();
// loc.testCallNumbers.sort(function(a,b) {return loc.localeCompare(a,b)});
locCallClass.prototype.sortCallNumbers = function (callnumbers) {
var sorted = callnumbers.sort(function (a,b) {
return this.localeCompare(a,b);
});
return sorted;
}
// locCallClass.isBetween(a,b,c)
// returns true if a <= c <= b
locCallClass.prototype.isBetween = function (a,b,c) {
//this.localeCompare(a, b) <= 0 if in sort order
return ( (this.localeCompare(a,c) <= 0 && this.localeCompare(c,b) <=0) ? true : false );
}
// locCallClass.padZed()
// returns portion of the call number padded out to enable sorting.
locCallClass.prototype.padZed = function (value, before_first_cutter) {
//pad value with zeros - return value will have a length of 9
// The exceptions here are going to be if the number is before the
// cutter, then we should treat it as two different parts: whole
// number, and decimal portion.
if(value) {
if(before_first_cutter && !isNaN(value) ) {
//this is a number before the first cutter, split it, and then
// pad each of the parts
var int_portion = Math.floor(value).toString();
var dec_portion = (value % 1).toFixed(3).toString().substr(2,3);
var pad_zeros = "";
for (var i=0; i<(9 - int_portion.length); i++) {
pad_zeros = pad_zeros + "0";
}
return_value = pad_zeros + int_portion;
var pad_zeros = "";
for (var i=0; i<(9 - dec_portion.length); i++) {
pad_zeros = pad_zeros + "0";
}
return_value += "." + dec_portion + pad_zeros;
return return_value;
} // end if
else {
//pad the value to the right
var pad_zeros = "";
for (var i=0; i<(9 - value.length); i++) {
pad_zeros = pad_zeros + "0";
}
return value + pad_zeros;
}
}
else {
return "000000000";
}
}
/* test script */
var loc = new locCallClass();
var output1 = document.getElementById("output1");
// define, show and then sort the first set
var set1 = ["LC 346 .65 .B29",
"LC 346 .M634",
"HX 754 .5 .C15",
"HX 754 .C7723"
];
output1.innerHTML = "<b>pre-sort</b><br>";
for(var i=0; i<set1.length; i++) {
output1.innerHTML += set1[i] + "<br>";
}
//sort with the specialized sort method from our class, "loc"
var sorted1 = set1.sort(function(a,b) {
return loc.localeCompare(a,b);
});
output1.innerHTML += "<hr><b>sorted</b><br>";
for(var i=0; i<sorted1.length; i++) {
output1.innerHTML += sorted1[i] + "<br>";
}
// now test the built in method to sort call numbers
// which doesn't work for some reason
var alt_sorted = loc.sortCallNumbers(set1);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>locCallClass test sorting of call numbers</title>
</head>
<body style="font-family:monospace;">
<h3>test sorting of call numbers</h3>
<div id="output1"></div>
</body>
Thanks in advance to anyone who could help me out!
Cache this:
locCallClass.prototype.sortCallNumbers = function(callnumbers) {
var self = this;
var sorted = callnumbers.sort(function(a, b) {
return self.localeCompare(a, b);
});
return sorted;
}
Or hard bind the sort's callback function to this:
locCallClass.prototype.sortCallNumbers = function(callnumbers) {
var sorted = callnumbers.sort(function(a, b) {
return this.localeCompare(a, b);
}.bind(this));
return sorted;
}
I'd like to sort by time,day.
Here is my attempt:
var days = new Array();
var days['SU'] = 0;
var days['MO'] = 1;
var days['TU'] = 2;
var days['WE'] = 3;
var days['TH'] = 4;
var days['FR'] = 5;
var days['SA'] = 6;
events.sort(function(a, b)
{
if(a['day'] != b['day'])
{
return (days[a['day']] < days[b['day']]) ? 1 : -1;
}
else if(a['time'] != b['time'])
{
return (a['time'] < a['time']) ? 1 : -1;
}
else
return 0;
);
It's not tested, but am I doing it correct?
(Time asc, days asc) Mon 8am, Tues 8am, Mon 9pm is the order I'm looking for.
Cheers.
events[0]['day'] = 'MO';
events[0]['time'] = 8;
events[1]['day'] = 'MO';
events[1]['time'] = 21;
events[2]['day'] = 'TU';
events[2]['time'] = 8;
My solution which seems to work thanks to #T.J. Crowder
events = new Array();
events[0] = new Array();
events[0]['day'] = 'MO';
events[0]['time'] = 8;
events[1] = new Array();
events[1]['day'] = 'MO';
events[1]['time'] = 21;
events[2] = new Array();
events[2]['day'] = 'TU';
events[2]['time'] = 8;
var days = {
'SU': 0,
'MO': 1,
'TU': 2,
'WE': 3,
'TH': 4,
'FR': 5,
'SA': 6
};
events.sort(function(a, b)
{
if (a.time != b.time)
{
return a.time - b.time;
}
else if (a.day != b.day)
{
return days[a.day] - days[b.day];
}
else
{
return 0;
}
});
Condensed:
events.sort(function(a, b)
{
return a.time != b.time
? a.time - b.time
: days[a.day] - days[b.day];
});
Your fundamental approach is sound. A few notes:
You're not using days as an array, so I wouldn't make it an array. Instead:
var days = {
'SU': 0,
'MO': 1,
'TU': 2,
'WE': 3,
'TH': 4,
'FR': 5,
'SA': 6
};
Also, you don't need those quotes since none of those strings is a keyword, so:
var days = {
SU: 0,
MO: 1,
TU: 2,
WE: 3,
TH: 4,
FR: 5,
SA: 6
};
...but you may choose to keep them as a style thing, or to defend against adding ones that are keywords later.
You don't have to use the bracketed notation to look up a property (a['day']) unless the string you're using for the property name is dynamic or the property name is a reserved word. day is neither, so you can use the simpler dotted notation (a.day).
There is no elseif in JavaScript; use else if.
You can simplify this:
return (days[a['day']] < days[b['day']]) ? 1 : -1;
to
return days[a.day] - days[b.day];
..and you may be able to do something similar with your time values, but I don't know what they are, so... now that you've posted them, I do, and you can.
Strongly recommend always using braces, not just when you "need" them. (None of your three branches actually needs them, but you're only using them on two.)
You've compared a['time'] to a['time] rather than b['time'] when checking for equality.
You haven't ended your function (missing })
Since you can just subtract your time values, you don't need your final equality check.
So:
events.sort(function(a, b)
{
if (a.day != b.day)
{
return days[a.day] - days[b.day];
}
else
{
return a.time - b.time;
}
});
...or you can condense it further:
events.sort(function(a, b)
{
return (a.day != b.day
? days[a.day] - days[b.day]
: a.time - b.time);
});
Live example
I need a random object generator in JavaScript that generates a variety of objects with different fields and values. Any ideas where I can find such tool?
I need to generate random objects with various complexity.. My goal is to use JSON in order to serialize these objects and fuzz test my application http api.
function createRandomObj(fieldCount, allowNested)
{
var generatedObj = {};
for(var i = 0; i < fieldCount; i++) {
var generatedObjField;
switch(randomInt(allowNested ? 6 : 5)) {
case 0:
generatedObjField = randomInt(1000);
break;
case 1:
generatedObjField = Math.random();
break;
case 2:
generatedObjField = Math.random() < 0.5 ? true : false;
break;
case 3:
generatedObjField = randomString(randomInt(4) + 4);
break;
case 4:
generatedObjField = null;
break;
case 5:
generatedObjField = createRandomObj(fieldCount, allowNested);
break;
}
generatedObj[randomString(8)] = generatedObjField;
}
return generatedObj;
}
// helper functions
function randomInt(rightBound)
{
return Math.floor(Math.random() * rightBound);
}
function randomString(size)
{
var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var generatedString = '';
for(var i = 0; i < size; i++) {
generatedString += alphaChars[randomInt(alphaChars.length)];
}
return generatedString;
}
It will create a obj with X paramenters, all with a integer, float, string, boolean or null value.
I just made it :B
You can use hasard library
Random variables and random nested objects manipulation in javascript
const h = require('hasard');
const randomInteger = h.integer({type: 'poisson', lambda: 4});
const randomString = h.string({
size: h.add(randomInteger, 5),
value: h.value('abcdefghijklmnopkrstuvw'.split(''))
});
const randomNumber = h.number([0, 100]);
const randomKeys = h.array({
size: randomInteger,
value: randomString
});
// we first define it, to use it as reference into randomObject
const randomValue = h.value();
const randomObject = h.object(
randomKeys,
randomValue
);
// And we set recursivity by setting his values afterward
randomValue.set([
randomString,
randomObject,
randomNumber,
randomInteger
]);
Results will looks like
[
{
"vbmujvv": "rfigcpcvpj",
"sjmcgvvk": 3,
"efdarehl": {
"odinthsuca": "rwjhmbfus",
"noihjtjen": 27.73332043042913,
"brspkaagb": "lnuiabcfd"
},
"febtungjhfokf": 49.28625818957401,
"eoemrkgi": {
"jkcuwrpsh": "ekjoltm",
"cincs": {
"fcovbwk": {
"whsgmjh": 48.00843935524626,
"agsjflef": 46.700796253998014
},
"ovkdfudgfm": 84.83383163217746,
"fpfetl": "djuvfjbjptf",
"kobmkstj": {
"wskgkkerk": 9,
"kvnptptek": 37.63655947554132,
"dsloun": 4
}
},
"krirwk": {
"sjgftomu": 51.663884142674775,
"hpjgibnli": 4
},
"pkhkgruls": "isuodwjrg"
},
"ortomnue": 71.71303423929236
}
]
DISCLAIMER i'm the author of hasard library