DEV Community


Discussion on: What I've learned from the Advent of Code so far (days 1-5)

caiangums profile image
Ilê Caian

Awesome post! I'm also taking adventures at the Advent of Code this year and I think I can give some thoughts too:

  • use of Array.includes(): returns true or false instead of the index
let validColors = ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'];

if (validColors.includes(value)) { ... }
Enter fullscreen mode Exit fullscreen mode
  • you can "empty-split" strings
const validChars = '0123456789abcdef'.split();
Enter fullscreen mode Exit fullscreen mode
  • make use of const on variables that do not change (consider capitalizing some of them too)
const VALID_CHARS = '0123456789abcdef'.split();

if (VALID_CHARS.includes(letter)) { ... }
Enter fullscreen mode Exit fullscreen mode

I would also suggest using some of RegExp here and there. You can make good use of .match() and .replace() where you need to find patterns in repetitive strings. As an example, you can check the usage of .replace() at this solution

Keep coding!! 😄

minna_xd profile image
Minna N. Author

Very good tips, thank you! I should've noticed includes and when I can use const. Actually, in my day 7 code (bags...) I use includes!

Thank you also for that code sample! I didn't know you can assign the groups into variables like that. 👍

A question which is either "hey, I'm able to give you a suggestion too!" OR there's some optimization magic going on that I don't know about. About the regex, you have:

/(\d*)-(\d*) (\w): (\w*)/g,

Is there a reason why you use * instead of +? Why not:

/(\d)-(\d) (\w): (\w+)/g,

(or \d+ in case the numbers are double or more digits)

caiangums profile image
Ilê Caian

Thanks for noticing it! It's true that I could've used + instead of *!

About maintaining \d, I didn't see if the file has values with more than 1 digit, but with * or + will cover it! 😄

It's just a habit using * instead of + and maybe it could be optimized as you said!