This repository has been archived by the owner on Dec 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordpack.js
98 lines (76 loc) · 2.06 KB
/
wordpack.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const fs = require('fs')
let done = false
packWordsInFile('wordsrc/adj.txt')
.then(saveAsJson.bind(null, 'src/corpus/adj.json'))
.then(() => packWordsInFile('wordsrc/noun.txt'))
.then(saveAsJson.bind(null, 'src/corpus/noun.json'))
.then(() => packWordsInFile('wordsrc/verb.txt'))
.then(saveAsJson.bind(null, 'src/corpus/verb.json'))
.then(() => {
done = true
})
areWeDone()
function areWeDone() {
if (!done) {
setTimeout(areWeDone, 100)
}
}
function packWordsInFile(filePath) {
return new Promise(function (resolve, reject) {
let rs = fs.createReadStream(filePath, { encoding: 'utf8' })
let chunkRemainder = ''
let wordBins = {}
rs.on('readable', () => {
let chunk = rs.read()
if (chunk === null) {
return
}
let lastNewLine = chunk.lastIndexOf('\n')
let parseableLines = chunkRemainder + chunk.slice(0, lastNewLine)
chunkRemainder = chunk.slice(lastNewLine + 1)
parseableLines
.split('\n')
.map(extractWord)
.filter(isWordLengthMoreThan(1))
.filter(isWordLengthLessThan(30))
.reduce(binWordsByLength, wordBins)
})
rs.on('error', reject)
rs.on('end', () => {
resolve(convertToElmFriendlyBins(wordBins))
})
})
}
function extractWord(line) {
return line.slice(0, line.indexOf(' ')).replace(/_/g, ' ')
}
function isWordLengthMoreThan(length) {
return (word) => word.length > length
}
function isWordLengthLessThan(length) {
return (word) => word.length < length
}
function isWordMoreThanOneLetter(word) {
return word.length > 1
}
function binWordsByLength(accum, word) {
let length = word.length
if (!accum.hasOwnProperty(length)) {
accum[length] = []
}
accum[length].push(word)
return accum
}
function convertToElmFriendlyBins(binnedWords) {
return Object.keys(binnedWords)
.map((key) => {
return {
length: parseInt(key),
words: binnedWords[key]
}
})
}
function saveAsJson(filePath, data) {
fs.writeFileSync(filePath, JSON.stringify(data), { encoding: 'utf8' })
return
}