1

Canadian postal codes are as follow:

L5R 1Y2 

I have been been playing around with lodash to pick random element from string, here is what I came up with.

num1 = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 1);

char1 = _.sampleSize('123456789', 1);

num2 = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 1);

char2 = _.sampleSize('123456789', 1);

num3 = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 1);

char3 = _.sampleSize('123456789', 1);

char4 = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 1);

console.log(char1,num1,char2 + ' ' + char3,num3,char4)

I'm not satisfied with this code, any suggestion on how I can go about optimizing it?

Deano
  • 11,582
  • 18
  • 69
  • 119

2 Answers2

4

This is a bit shorter:

let letters = _.times(3, () => _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
let numbers = _.times(3, () => _.sample('123456789'));
console.log(`${letters[0]}${numbers[0]}${letters[1]} ${numbers[1]}${letters[2]}${numbers[2]}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
mpen
  • 272,448
  • 266
  • 850
  • 1,236
1

Assuming that you can use a random int generator, to pick characters from the strings of the alphabet and digits, to arrive at two arrays:

const arrayOfLetters = ["H", "H", "H"];
const arrayOfNumbers = ["0", "0", "0"];

the concept of interleaving is actually pretty simple:

const interleave = (arr1, arr2) =>
  Array.from({ length: arr1.length }) // or use Math.min or Math.max
    .map((_, i) => [arr1[i], arr2[i]])
    .reduce((a, b) => a.concat(b), []);

interleave(arrayOfLetters, arrayOfNumbers).join(""); // H0H0H0

Interleaving an arbitrary number of arrays isn't really any harder.

The space division isn't technically part of the spec (and is also seen divided by hyphen). So if you really want to include it, or include space for it, then you can do something like:

const generateCanadianPostalCode = (separator = " ") => {
  const letters = generateLetters(3);
  const numbers = generateNumbers(3);
  const sequence = interleave(letters, numbers);
  const halves = [
    sequence.slice(0, 3).join(""),
    sequence.slice(3).join(""),
  ];
  return halves.join(separator);
};
Norguard
  • 26,167
  • 5
  • 41
  • 49