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
-
minDistance
Practice the exercises based on documentation to become an expert in Next.js
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:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com
My Github — https://github.com/ramu-narasinga
My website — https://ramunarasinga.com
My Youtube channel — https://www.youtube.com/@ramu-narasinga
Learning platform — https://thinkthroo.com
Codebase Architecture — https://app.thinkthroo.com/architecture
Best practices — https://app.thinkthroo.com/best-practices
Production-grade projects — https://app.thinkthroo.com/production-grade-projects