diff --git a/src/topics/posts.js b/src/topics/posts.js index 73eb29b9f9..e558698827 100644 --- a/src/topics/posts.js +++ b/src/topics/posts.js @@ -76,30 +76,65 @@ module.exports = function (Topics) { }; async function addEventStartEnd(postData, set, reverse, topicData) { + // console.log('njoud: refactored code is running'); if (!postData.length) { return; } - postData.forEach((p, index) => { + /* + helper function to be called for each post object + in the postData array + to set the start and end times of each post + */ + function setEventTimes(p, nextPost, reverse, topicData) { + // console.log('njoud: refactored code is running (helper function 1)'); if (p && p.index === 0 && reverse) { p.eventStart = topicData.lastposttime; p.eventEnd = Date.now(); - } else if (p && postData[index + 1]) { - p.eventStart = reverse ? postData[index + 1].timestamp : p.timestamp; - p.eventEnd = reverse ? p.timestamp : postData[index + 1].timestamp; + } else if (p && nextPost) { + p.eventStart = reverse ? nextPost.timestamp : p.timestamp; + p.eventEnd = reverse ? p.timestamp : nextPost.timestamp; } + } + postData.forEach((p, index) => { + const nextPost = postData[index + 1]; + setEventTimes(p, nextPost, reverse, topicData); }); - const lastPost = postData[postData.length - 1]; - if (lastPost) { - lastPost.eventStart = reverse ? topicData.timestamp : lastPost.timestamp; - lastPost.eventEnd = reverse ? lastPost.timestamp : Date.now(); - if (lastPost.index) { - const nextPost = await db[reverse ? 'getSortedSetRevRangeWithScores' : 'getSortedSetRangeWithScores'](set, lastPost.index, lastPost.index); - if (reverse) { - lastPost.eventStart = nextPost.length ? nextPost[0].score : lastPost.eventStart; - } else { - lastPost.eventEnd = nextPost.length ? nextPost[0].score : lastPost.eventEnd; - } - } + /* + call another helper function to handle the last post + */ + await handleLastPost(postData, set, reverse, topicData); + } + /* + helper function for last post + */ + async function handleLastPost(lastPost, set, reverse, topicData) { + // console.log('njoud: refactored code is running (helper function 2)'); + if (!lastPost) { + return; + } + /* + break down if else statements + */ + if (reverse) { + lastPost.eventStart = topicData.timestamp; + lastPost.eventEnd = lastPost.timestamp; + } else { + lastPost.eventStart = lastPost.timestamp; + lastPost.eventEnd = Date.now(); + } + if (!lastPost.index) { + return; + } + const getNextPost = reverse ? 'getSortedSetRevRangeWithScores' : 'getSortedSetRangeWithScores'; + const nextPost = await db[getNextPost](set, lastPost.index, lastPost.index); + /* + combine reverse and nextPost.length checks + in one boolean check + */ + if (reverse && nextPost.length) { + lastPost.eventStart = nextPost[0].score; + } else if (!reverse && nextPost.length) { + lastPost.eventEnd = nextPost[0].score; } }