Skip to content

Instantly share code, notes, and snippets.

@htsign
Last active October 28, 2017 10:19
Show Gist options
  • Save htsign/5c3b74314fc0166dbc7b to your computer and use it in GitHub Desktop.
Save htsign/5c3b74314fc0166dbc7b to your computer and use it in GitHub Desktop.
It calculates total paid. Run on 'https://booklive.jp/my/top'
!Number.prototype.padLeft && Object.defineProperty(Number.prototype, "padLeft", {
value(n, s = " ") {
return (Array(n).join(s) + this).slice(-n);
}
});
main();
function main() {
const now = new Date;
const startYear = now.getFullYear();
const startMonth = now.getMonth() + 1;
const least = prompt("何年まで遡りますか?", startYear);
if (!/^[0-9]{4}$/.test(least)) {
return alert("半角4文字の西暦で入力してください。");
}
const history = Object.create(null);
const tasks = [];
let paid = 0;
for (let y = startYear + 1; --y >= least;) {
for (let m = (y === startYear ? startMonth : 12) + 1; --m > 0;) {
const task = monthSum(y, m).then(price => {
history[`${y.padLeft(4)}年${m.padLeft(2)}月`] = price.toLocaleString() + "円";
paid += price;
});
tasks.push(task);
}
}
Promise.all(tasks).then(_ =>
console.info(`合計: ${paid.toLocaleString()}円`, sortObjectByKey(history)));
}
function monthSum(year, month) {
return request(`/my/product?year=${year}&month=${month}`)
.then(doc => {
const nodes = doc.querySelectorAll('[id^="myproduct_display"]');
if (nodes.length) {
return Array.from(nodes, e => e.textContent.trim())
.filter(text => text.endsWith("円"))
.map(price => parseInt(price.split(",").join(""), 10))
.reduce((a, b) => a + b);
}
else return 0;
});
}
function request(url) {
return fetch(url, { credentials: "include" }).then(res => res.text())
.then(text => {
const range = document.createRange();
const dom = range.createContextualFragment(text);
try {
return dom;
}
finally { range.detach(); }
});
}
function sortObjectByKey(obj) {
return Object.keys(obj).sort()
.reduce((acc, key) => Object.assign(acc, {[key]: obj[key]}), Object.create(null));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment