Lessons from open-source: Algorithm behind `“next buuild” does not exist. Did you mean “next build”?`
This lesson is picked from Next.js source code. In this article, you will learn how Next.js detects typo in your CLI commands such as build | dev | info | lint | start | telemetry.
Detect-typo
Ever wondered what is the logic behind detecing a typo in the CLI command you issue using Nextjs CLI API? well, there is a utility file named detect-typo.ts in nextjs repository.
detect-typo.ts has two functions at the time of writing this article. They are:
detectTypo
This is used in Next CLI related files
minDistance
This function has the algorithm that detects if there is a typo in the CLI command issued.
// the minimum number of operations required to convert string a to string b.
function minDistance(a: string, b: string, threshold: number): number {
const m = a.length
const n = b.length
if (m < n) {
return minDistance(b, a, threshold)
}
if (n === 0) {
return m
}
let previousRow = Array.from({ length: n + 1 }, (_, i) => i)
for (let i = 0; i < m; i++) {
const s1 = a[i]
let currentRow = [i + 1]
for (let j = 0; j < n; j++) {
const s2 = b[j]
const insertions = previousRow[j + 1] + 1
const deletions = currentRow[j] + 1
const substitutions = previousRow[j] + Number(s1 !== s2)
currentRow.push(Math.min(insertions, deletions, substitutions))
}
previousRow = currentRow
}
return previousRow[previousRow.length - 1]
}
领英推荐
Results:
I intentionally added typos to the Next CLI API and the image below shows that
Conclusion:
This simple minDistance algorithm to detect a typo in the Next CLI command makes me want to relearn and practice data structures and algorithms more in order to write some quality code. I have taken it for granted far too long now. Clean code isn’t just writing concise fancy function names and parameters, I am realising it also means using the proper data structures and algorithms.
About me:
Website: https://ramunarasinga.com/
Email: [email protected]