JSFiddle - React, Tailwind, and code Playground
by replicateur
HTML
<button onclick="pickAnumb()">
Pick a numb
</button>
<button onclick="pickDifferent()">
Pick another numb
</button>
<div id="picked">
</div>
<div id="picked-different">
</div>
JavaScript
class Picker {
constructor(data) {
this.data = data;
this.picked = null;
}
pick() {
this.picked = this.data[Math.floor(Math.random() * this.data.length)];
return this.picked.name;
}
pickDifferent() {
let tmData = this.data.filter(value => value != this.picked);
this.picked = tmData[Math.floor(Math.random() * tmData.length)];
return this.picked.name;
}
pickByProperties(properties) {
if (properties != null) {
let tmData = Array.from(this.data);
let result = [];
let subResult = tmData.filter(el => {
return el[properties.name] == properties.value;
});
if (subResult.length) {
for (let res in subResult) {
result.push(subResult[res]);
}
}
let output = "";
for (let r in result) {
output += result[r].name;
}
return output;
}
}
}
let arr = [{
id: 1,
name: 'toto'
},
{
id: 2,
name: 'chuck'
},
{
id: 3,
name: 'monster'
},
];
let picker = new Picker(arr);
function pickAnumb() {
document.getElementById('picked').innerHTML = picker.pick();
}
function pickDifferent() {
document.getElementById('picked-different').innerHTML = picker.pickByProperties({
name: 'name',
'value': 'toto'
});
}