Michael Douglas Brett - Web Development

Hi, I'm Michael. I'm a front-end web developer based in the UK. This is my site.

Duplicate!

JavaScript FEDIQ

May 30th 2016

I've had a busy couple of weeks, so I'm going to phone this one in a little bit. The original problem was 'Make this work: duplicate([1,2,3,4,5]) // ([1,2,3,4,5,1,2,3,4,5])'. Click the 'Full post' link to discover this one weird trick to concatenate arrays...

That 'weird trick' was clickbait!

JavaScript arrays have a concat() method that, according to the spec:

...returns an array containing the array elements of the object followed by the array elements of each argument in order.

This makes our duplicate function pretty straightforward to write (I'm trying to write more es6, so please indulge me):

let duplicate = (arr) => arr.concat(arr);

duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

However, strings also have a concat() method and if we're not careful, we could allow something like this to happen...

duplicate('One, two, three, four, five'); // 'One, two, three, four, fiveOne, two, three, four, five'

Nasty! Obviously we want to be checking that the arr we're passing in is actually an array, so we'll use typeof a conditional (JavaScriiiiiipt!) to make sure that arr's prototype is Array. I nicked this off Crockford and added it to the function:

let duplicate = (arr) => {
  if (Object.prototype.toString.apply(arr) !== '[object Array]') {
    throw new Error("That ain't an array mate!");
  };
  return arr.concat(arr);
};

That's enough for today, next time: 'How do you serve a page with content in multiple languages?'