This Week in Dev

JavaScript Word-Search Puzzle

Revisiting JavaScript this week - I think my solution to the wordsearch puzzle grid problem is particularly elegant. Check out my Solution here

I also tweeted about an elegant recursive algorithm I devised to generate integer sequences in JavaScript (which is utilized in the word search challenge) Some languages (Ruby, Haskell) use syntax like [1..10] to represent an integer sequence, but JavaScript doesn’t have a built-in way to do this, so I created my own.

function intSequence(start, end, n = start, arr = []) {
    return n === end ? arr.concat(n)
        : intSequence(start, end, start < end ? n + 1 : n - 1, arr.concat(n));
}
[Read More]

Practical Uses for Bitwise Operators

I was very bemused at my first encounter of bitwise operations, but quickly realized that I couldn’t think of even a single use for this language feature.

My solution to the Say challenge on exercism.io represents the first occasion that I have been able to make use of this knowledge.

The challenge was to convert numbers into English words. To do this, I would need to group them into groups of three, as we normally do using comma notation, so that a number like 6,145,010 would group such as “6 million” “145 thousand” “ten”.

There are a couple different ways to do this, but I decided to pad the number so that the number of digits would always be a multiple of 3. Without a pad, I would end up getting groups like [“614”, “501”, “0”], instead of [“6”, “145”, “010”].

One possibility would be to use the remainder from a modulus division to determine the amount of pad needed. However, it is made much more concise by using the bitwise XOR operator. Here is the resulting code, and my unit tests.

const padString = function (number) {
  const pad = "0".repeat(((String(number).length-1)%3^3)-1);
  return (pad + String(number));
};

const magnitudeGroupedArray = function (number) {
  const paddedString = padString(number);
  return paddedString.match(/.{1,3}/g);
}

describe('pad', () => {
  test('pad-3', () => {
    expect(magnitudeGroupedArray(9)).toEqual(["009"]);
    expect(magnitudeGroupedArray(89)).toEqual(["089"]);
    expect(magnitudeGroupedArray(789)).toEqual(["789"]);
  });
  test('pad-6', () => {
    expect(magnitudeGroupedArray(6789)).toEqual(["006", "789"]);
    expect(magnitudeGroupedArray(56789)).toEqual(["056", "789"]);
    expect(magnitudeGroupedArray(456789)).toEqual(["456", "789"]);
  });
  test('pad-9', () => {
    expect(magnitudeGroupedArray(3456789)).toEqual(["003", "456", "789"]);
    expect(magnitudeGroupedArray(23456789)).toEqual(["023", "456", "789"]);
    expect(magnitudeGroupedArray(123456789)).toEqual(["123", "456", "789"]);
  });
});
[Read More]