Examples
wordcount
The sources of the example, as they are at the commit this site was built from. Examples says what each example is about, and the playground runs a text of the language in the page.
#main.sts
// Counts the words of a file: the file system is the outside, and a map holds the counts.
extern "node:fs" {
function readFileSync(path: string, encoding: "utf8"): string
}
type Count = { word: string, times: number }
export function count(text: string): Count[] {
const words = text.toLowerCase().split(" ").flatMap(part => part.split("\n")).map(word => word.trim()).filter(word => word.length > 0)
words.groupBy(word => word).entries()
.map(entry => ({ word: entry.key, times: entry.value.length }))
.sortedBy(entry => entry.word)
.sortedBy(entry => -entry.times)
}
export function main(args: string[]): Result<void, string> {
const path = args[0].okOr("usage: wordcount <file>")?
const text = readFileSync(path, "utf8").mapErr(thrown => `${path}: ${thrown.message}`)?
for (const entry of count(text).slice(0, 5)) {
console.log(`${entry.times} ${entry.word}`)
}
Ok()
}