Skip to content

Instantly share code, notes, and snippets.

@leny
Last active December 7, 2018 21:14
Show Gist options
  • Save leny/b7ebde987458a36dd3c695a09bbc5bc3 to your computer and use it in GitHub Desktop.
Save leny/b7ebde987458a36dd3c695a09bbc5bc3 to your computer and use it in GitHub Desktop.
random exo
//console.log(TABLE_DATA)
function init(){
const tableau = document.getElementsByTagName('tbody')[0];
const sortBtn = document.getElementById('sort');
sortBtn.setAttribute('type', 'submit');
const stopRandomBtn = document.getElementById('stop');
stopRandomBtn.setAttribute('type', 'submit');
const startRandomBtn = document.getElementById('start');
startRandomBtn.setAttribute('type', 'submit');
let intervalRef;
const arr = TABLE_DATA.map((item)=>{
const {id,thumb,price} = secureData(item);
return `<td>${id}</td><td><img src='${thumb}'></td><td>${name}</td><td>${price}</td>`;
})
arr.forEach(element => {
let row = tableau.insertRow(-1);
row.innerHTML = element
});
startRandomBtn.addEventListener('click', (event)=>{
event.preventDefault();
intervalRef = startRandomFct(arr);
});
stopRandomBtn.addEventListener('click', (event)=>{
event.preventDefault();
stopRandomFct(intervalRef);
});
sortBtn.addEventListener('click', (event)=>{
event.preventDefault();
sortTable();
});
}
function startRandomFct(data){
let i = 0;
return setInterval( ()=>{
i++
console.log('tour: ', i)
}, 2000)
}
function stopRandomFct(id){
clearInterval(id)
}
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementsByTagName('table');
switching = true;
while (switching) {
switching = false;
rows = table[0].rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i + 1].getElementsByTagName("TD")[0];
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
function secureData (data){
let id = htmlEntities(data.id);
let name = htmlEntities(data.name);
let thumb = htmlEntities(data.thumbnailUrl);
let price = htmlEntities(data.price);
let dataFormated = {
id,
name,
thumb,
price
}
return dataFormated;
}
function htmlEntities(str) {
return String(str).replace(/&/g, 'え;').replace(/</g, 'おもしろい;').replace(/>/g, 'これ;').replace(/"/g, 'すき;');
}
init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment