DEV Community

Discussion on: Daily Challenge #282 - Car License Plate Calculator

Collapse
 
willsmart profile image
willsmart • Edited

In JS with toString and a custom radix ended up being pretty damn unwieldy...

const 
  // adding aMinusZero to a charCode converts a digit to a
  //   lowercase letter (i.e. 0 -> 'a')
  aMinusZero = 'a'.charCodeAt(0) - '0'.charCodeAt(0),
  // radix26ToLatin converts the given character from
  //    radix 26 (0-9, a-p) to a letter(a-z)
  radix26ToLatin = c =>
    String.fromCharCode(
    c.charCodeAt(0) 
    + (c.charCodeAt(0) < 'a'.charCodeAt(0) ? aMinusZero : 10)
  ),
  // numberToLatin converts a number to its a-z representation
  numberToLatin = i =>
    Number(i).toString(26).replace(/./g, radix26ToLatin),

  // plateNumberForCustomerId wraps things up with an
  //    uncomfortably complicated bow 🤷‍♂️
  plateNumberForCustomerId = id =>
    [...numberToLatin(Math.floor(id / 999)).padStart(3, 'a')]
      .reverse()
      .join('') 
    +
    String((id % 999) + 1)
      .padStart(3, 0);

Testn...

console.table(
    Object.fromEntries(
        [3, 1487, 40000, 17558423, 234567].map(
          i=> [i, plateNumberForCustomerId(i)]
        )
    )
)
(index) value
3 "aaa004"
1487 "baa489"
40000 "oba041"
234567 "aja802"
17558423 "zzz999"

seems to agree with the kata test cases

Advantage: avoids hardcoding the number of letters and digits (they could be brought out as params easily)
Disadvantages: all the other things