During a technical interview for a full-stack developer role, I found myself in a familiar yet unexpectedly challenging situation. Everything had been going smoothly until the interviewer presented me with a task that seemed simple at first.
“Can you sort these filenames the way they’d appear in a file explorer, in ascending order?” they asked.
I thought, “Piece of cake.” Sorting is such a fundamental operation that I didn't expect any trouble. But as soon as I started writing the code, I hit a snag. The filenames were all over the place some were simple, but others included numbers, letters, and combinations of both.
I tried using a basic string sorting method like:
array.sort();
But this produced an odd result. The numbers were sorted lexicographically (meaning “10” would come before “2” because it starts with a “1”), and mixed alphanumeric strings weren’t in the correct order. It was a mess, and it didn’t resemble the natural order you see in file explorers at all.
I could feel the clock ticking and pressure building up. I tried to work through various custom comparison functions to handle the numbers properly, but nothing seemed to click.
Then, I remembered a simple trick I had read about not too long ago: localeCompare.
localeCompare allows you to compare strings in a way that mimics how humans sort things. By using it with the numeric option, it handles the numbers as actual numbers rather than comparing them as text. Here’s the code I used:
array.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
This single line of code sorted the filenames exactly like a file explorer would: numbers were ordered naturally, and letter/number combinations were handled seamlessly.
As soon as I ran the code, I saw the correct order appear on the screen. The filenames were perfectly sorted in ascending order, just like in a file explorer. I smiled as I explained the solution to the interviewer, who seemed pleased with how I resolved the issue.
What initially felt like a complicated problem ended up being solved with a simple, elegant solution. It was a reminder that sometimes the most effective tools are the simplest, and knowing those small tricks can make all the difference.
The above is the detailed content of A Lesson in Simplicity: Sorting Files Like a Pro in an Interview. For more information, please follow other related articles on the PHP Chinese website!