A solution to r/dailyprogrammer's challenge #165 [Hard] in JavaScript