Created
December 15, 2022 15:20
-
-
Save alvinj/60f72948613cc096b0ac1b172cdbed75 to your computer and use it in GitHub Desktop.
Script to list Scala Book MD filenames in their order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using scala "3" | |
/** | |
* This is a script to create the `SortedListOfMDFilenames` file | |
* from the existing MD files. It assumes that all of those | |
* files have a `num: nn` field. | |
* | |
* Run me like this: | |
* scala-cli CreateListOfFilenamesInOrder.sc | |
* | |
*/ | |
// the directory where all the MD files are located | |
val DIR = "/Users/al/Projects/docs.scala-lang/_overviews/scala3-book" | |
// [0] the necessary functions | |
def readFile(filename: String): List[String] = | |
io.Source.fromFile(filename) | |
.getLines | |
.toList | |
import java.io.File | |
def getListOfFilesInDir(dir: File, extensions: List[String]): List[File] = | |
dir.listFiles.filter(_.isFile).toList.filter { file => | |
extensions.exists(file.getName.endsWith(_)) | |
} | |
// [1] get a list of the MD files | |
val okFileExtensions = List("md") | |
val filesInDir = getListOfFilesInDir(File(DIR), okFileExtensions) | |
val filenamesInDir = filesInDir.map(f => f.toString) | |
// [2] from those MD files, build a `Map[FileName, FileNumber]` | |
val map = scala.collection.mutable.Map[String, Int]() | |
for fileName <- filenamesInDir do | |
val lines = readFile(fileName) | |
val matchingLine = lines.filter(_.startsWith("num: "))(0) | |
val fileNumber = matchingLine.drop(5).trim.toInt | |
map += (fileName -> fileNumber) | |
// [3] sort the Map and print the filenames by their `num:` value | |
val sortedMap = scala.collection.immutable.ListMap(map.toSeq.sortBy(_._2):_*) | |
for (k, v) <- sortedMap do | |
val fname = File(k).getName | |
println(s"$fname") | |
// debug: println(s"$fname \t $v") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment