Just took up TypeScript a couple of weeks ago without much knowledge in JavaScript.
I am trying to go through all the files in the specified directory and put each file name (string) and change time (number) into an array of array and sort by change time.
It looks like this: [['natalie.jpg', 143], ['mike.jpg', 20], ['john.jpg', 176], ['Jackie.jpg', 6]]
Problem 1: I do not know how to specify the inner array content, string and number. Type? Interface? Class? Tuple?
Problem 2: I do not know how to sort by change time in ascending order, so that the array changes to: [['Jackie.jpg', 6], ['mike.jpg', 20], ['natalie.jpg', 143], ['john.jpg', 176]]
import fs from 'fs'
const dirPath = '/home/me/Desktop/'
type imageFileDesc = [string, number] // tuple
const imageFileArray = [imageFileDesc] // ERROR HERE!
function readImageFiles (dirPath: string) {
try {
const dirObjectNames = fs.readdirSync(dirPath)
for (const dirObjectName of dirObjectNames) {
const dirObject = fs.lstatSync(dirPath + '/' + dirObjectName)
if (dirObject.isFile()) {
imageFileArray.push([dirObjectName, dirObject.ctimeMs]) // ERROR HERE!
}
}
imageFileArray.sort(function (a: number, b: number) {
return b[1] - a[1] // ERROR HERE! Can we do something like b.ctime - a.ctime?
})
} catch (error) {
console.error('Error in reading ' + dirPath)
}
}
readImageFiles(dirPath)
console.log(imageFileArray)
[ string, number ][]?