【发布时间】:2021-03-23 19:27:38
【问题描述】:
我在~479k words 上运行此代码,这需要很长时间:
const fs = require('fs')
const words = fs.readFileSync('dicts/eng.csv', 'utf-8')
.split(/\n/)
.filter(x => x && !x.match('-') && !x.match(/[A-Z]/))
.reduce((m, x) => {
m[x] = true
return m
}, {})
for (let word in words) {
for (let form in words) {
if (form.indexOf(word) == 0) {
if (form.length == word.length + 2 && form.endsWith('ed')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('tion')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ing')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('er')) {
delete words[form]
} else if (form.length == word.length + 2 && form.endsWith('or')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('est')) {
delete words[form]
} else if (form.length == word.length + 1 && form.endsWith('s')) {
delete words[form]
} else if (form.length == word.length + 3 && form.endsWith('ers')) {
delete words[form]
} else if (form.length == word.length + 4 && form.endsWith('ings')) {
delete words[form]
}
}
}
}
fs.writeFileSync('dicts/eng.out.csv', Object.keys(words).sort().join('\n'))
我怎样才能加快这个速度,只花费一小部分时间,大约一两秒或更现实的时间?
我需要将这个列表转换成更适合更快算法的数据结构吗?
【问题讨论】:
-
也就是说,这不是minimal reproducible example。
words的内容是什么?您是否希望我们所有人都自己获取文件并修改您的示例,以便我们可以实际使用它? -
@Andreas 是的,请,该文件就在 GitHub 存储库中。太大,无法粘贴。
-
然后抓取一些示例元素并用它创建一个“假”
words变量 -> How do I ask a good question? -> minimal reproducible example -
我认为你的 else if 链错过了“f -> es”案例(例如 wolf -> wolves)和其他一些边缘案例(例如 die -> 死亡,缩写 -> 缩写)。我认为您的问题不仅仅是编码问题
标签: javascript algorithm optimization