ctime, atime, mtime

I'm trying to get the latest posts feature for the blog home to work and I am running into challenges!

My basic approach is to grab the modified dates of the files using fs and then grab the largest number of those dates. In theory that should be the most recently edited file. But it isn't working.

fs.statSync(dirName) returns an object with a bunch of stats of the files in the directory. This includes atime, ctime, mtime. I didn't know what these were so I looked them up:

atime: the last time the file was accessed (opened) ctime: the last time the file was changed. This could be a change in permissions or attributes mtime: the last time only the file contents were changed

There is also birthtime which I'm assuming is when the file was brought into the world.

No matter which one of these I use, the same post is chosen for the homepage. There is something wrong with my function and I don't know what...

function getLatestPost(stats, posts) {
 return posts.reduce((acc, cur, i, arr) => {
      let currentStat = stats[i]
      let prevStat = stats[i-1]
      if (prevStat) {
        if (currentStat > prevStat) {
          return cur
        } else {
          return posts[i - 1]
        }
      } 
   if (posts.length === 1) {
     return posts[0]
   }
  })

}

I've even modified the files; deleted and remade them. Nothing I'm doing is working. I'll come back to this again later.


Update

I think I figured out the problem. I'm not comparing the right numbers! woops!

So, before I had the stats and the filenames in two different arrays. That's just how they came. Since the two arrays were in the same order I figured I could use the same index on each array and get the right values. That didn't really work (I'm not sure why but it is probably my fault). I updated the function to combine the two arrays into an array of objects. I then adjusted the logic to make it much much simpler. I'm now seeing the right posts (this one) on the homepage.

function getLatestPost(stats, posts) {
const arr = stats.map((value, index) => ({post: posts[index], time: value}))

 return arr.reduce((acc, cur) => {
        if (cur.time > acc.time) {
          return cur
        } else {
          return acc
        }
  })

}

Whoa, just realized I can probably make that reduce a ternary

arr.reduce((acc, cur) => cur.time > acc.time ? cur : acc)

Nice!