JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.steemjs.com/lib/latest/steem.min.js"></script>
<h1>Who replied to me the most?</h1>
User: <input type="text" id="username">
<button id="calculate">calculate</button>
<pre id="output"></pre>
JavaScript
(function() {
// helpers
const toFlatArray = (all, current) => all.concat(current);
const sortMapByValueDesc = (a, b) => b[1] - a[1];
document.getElementById('calculate').addEventListener('click', calculateTopCommenters);
function calculateTopCommenters() {
const username = document.getElementById('username').value;
resetOutput();
output('loading...');
getPostsAndComments(username)
.then(getAllRepliesPerPost)
.then(allRepliesPerPost => {
const allReplies = allRepliesPerPost.reduce(toFlatArray);
const countReplies = countAuthors(allReplies);
const sortedByCount = [...countReplies.entries()].sort(sortMapByValueDesc);
outputResult(allReplies, sortedByCount);
});
}
function countAuthors(allReplies) {
return allReplies.reduce((counter, reply) => {
const count = counter.get(reply.author) || 0;
return counter.set(reply.author, count + 1);
}, new Map());
}
function getAllRepliesPerPost(posts) {
const postRepliesPromises = posts.map(getReplies);
return Promise.all(postRepliesPromises)
}
function getPostsAndComments(username) {
return Promise.all([
steem.api.getDiscussionsByAuthorBeforeDate(username, '', '2100-01-01T00:00:00', 10),
steem.api.getDiscussionsByComments({start_author: username, limit: 10})
]).then(([posts, comments]) => posts.concat(comments));
}
function getReplies(post) {
return steem.api.getContentReplies(post.author, post.permlink);
}
function output(message) {
document.getElementById('output').innerHTML += message + '\n';
}
function outputResult(allReplies, sortedByCount) {
resetOutput();
output(`You have ${allReplies.length} replies by ${sortedByCount.length} users!`);
output('Users who upvoted you the most: ');
sortedByCount.forEach(([user, count]) => {
output(`${user}, ${count}`);
});
}
function resetOutput() {
...