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.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (2)
That’s really nice, stuff like this provides good UX, something that’s usually an afterthought, especially for CLIs 👍
Thanks for your comment. I agree, good DX matters.