Skip to content

Instantly share code, notes, and snippets.

@oneeyedman
Last active April 15, 2022 08:47
Show Gist options
  • Save oneeyedman/f9a71ff636a90712a054f5b975fc7099 to your computer and use it in GitHub Desktop.
Save oneeyedman/f9a71ff636a90712a054f5b975fc7099 to your computer and use it in GitHub Desktop.
function stealthDownloadFile(csv) {
const ninjaLink = document.createElement('a');
ninjaLink.href = encodeURI(csv);
ninjaLink.target = '_blank';
ninjaLink.download = 'dragon-ball-ultimate.csv';
ninjaLink.click();
}
function getCSV(list, headers) {
let csv = 'data:text/csv;charset=utf-8,' + headers.join(',') + '\r\n';
list.forEach(item => {
const {title, price, stock} = item;
const row = [title, stock, price].join(',');
csv += row + '\r\n';
});
stealthDownloadFile(csv);
}
function formatPrice(price) {
return Number(price
.replace(',','.')
.replace(' €', '')
);
}
function getList() {
const books = [...document.querySelectorAll('.books .item')];
const booksTotal = books.length;
const titles = books.map(item => {
const title = item.querySelector('.title').textContent.trim();
const price = formatPrice(item.querySelector('.precio').textContent.trim());
const stock = item.querySelector('.disponibilidad').classList.contains('green');
return {
title,
price,
stock
}
}).sort((a,b) => {
if (a.title < b.title) return -1;
if (a.title > b.title) return 1;
return 0;
});
const totalPrice = titles.reduce((acc, val) => acc + val.price, 0).toFixed(2);
console.log('Total: ', booksTotal);
console.log('Precio total:', totalPrice + ' €');
console.table(titles);
getCSV(titles, ['Título', 'Stock', 'Precio']);
}
getList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment