DEV Community

Cover image for Public Solving: Matching smudged names
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Public Solving: Matching smudged names

Oh no, some packages fell off the sled, and the names are only partially readable.

You can find the puzzle here.

It's up to us to predict which name is on each smudged package.

We receive a list of all the children's names and a list of gifts with smudged names.

Let's get right into thinking out the solution to help Santa as soon as possible.

Thinking about the solution

My initial thought is, great, we can use the filter method to filter the list of names with whatever name roughly matches the smudged name.

To do the rough matching, we can actually use Regex and not a super-advanced one, as you might think!

Finding the smudged names

Alright, let's get right into it.

First of all, we need to import all the kids names.

import names from '../data/names.js';
Enter fullscreen mode Exit fullscreen mode

Then we can return the array of names using the JavaScript filter method to find the good ones.

return names.filter((name) => {
    // Todo
});
Enter fullscreen mode Exit fullscreen mode

Then inside this, we need to define a regex to match a part of the string.

Let's take a look at how the smudging looks like:

// Some examples:

Fr#der##k
Jo#ann#
Patt#
Enter fullscreen mode Exit fullscreen mode

For Patt#, we should get two potential hits: Patti, and Patty.

The cool part about this assignment is that it states a smudge is always one letter.
And Regex comes with a great tool, the dot (.), which says: ". matches any character (except for line terminators)"

So we can replace all # with . and we should get pretty far already.

return names.filter((name) => {
    const regex = new RegExp(smudgedName.replaceAll('#', '.'));
    return name.match(regex);
});
Enter fullscreen mode Exit fullscreen mode

This uses the RegExp function, where inside, we replace all hashtags with dots.
Then we return only if the name matches this regular expression.

And the results look very promising, but not perfect!

Remember Patt# it also matches: Patterson, which surely can't be right as it's too many characters!

We can simply fix this by adding a $ sign at the end of our regular expression.
The $ stands for the end of the line.

Making our complete function look like this:

return names.filter((name) => {
    const regex = new RegExp(`${smudgedName.replaceAll('#', '.')}$`);
    return name.match(regex);
});
Enter fullscreen mode Exit fullscreen mode

Let's run the test and see what happens:

Test running and succeeding

There we go. We fixed it.

I would love to hear your approach for this solution or what you would change.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)