eph baum dot dev

← Back to blog

Array.prototype.diff(meaCulpa)

Published on 08/23/2014 08:45 PM by Eph Baum

So, it turns out that when you go off all half-cocked all willy-nilly extending a core functionality of JavaScript it’s bound to result in a hiccup now and then.

It was, then, a few days after posting about my new ‘diff’ function that I found my JavaScript choking on exactly that function. It turns out that the issue was that I wasn’t watching my data types carefully enough.

The solution? Simply watch what you’re doing!

Array.prototype.diff = function( a ) { 
  if ( a instanceof Array && this instanceof Array) { 
    return this.filter( function( i ) { 
      return a.indexOf( i ) < 0; 
    }); 
  } else { 
    return new Array(); 
  } 
};

At this point we’re doing the EXACT same thing that we had been doing before except prior to comparing the two arrays, we check to make sure that they are both actually arrays using instanceof, as you can see above.

You’ll see that the else now simply returns an empty array if they’re not both arrays. This solution works for me but you could definitely do quite a bit more with this if you felt it was warranted.

Written by Eph Baum

← Back to blog
  • 50 Stars - Puzzle Solver (of Little Renown)

    50 Stars - Puzzle Solver (of Little Renown)

    Join Eph Baum as they recount their journey through the Advent of Code 2023. For the first time, Eph completes all puzzles, leveraging resources like GPT-4 and Code Llama. Despite the challenges and time constraints, Eph not only stays on top of the puzzles but also lands on the top 1,000 leaderboard. Dive into this post to explore the role of generative AIs in problem-solving and the joy of coding puzzles. - GitHub Co-pilot

  • Don't Trust AI - An Advent of Code Tale

    Don't Trust AI - An Advent of Code Tale

    Join Eph Baum in 'Don't Trust AI - An Advent of Code Tale' as they navigate the Advent of Code 2023. Despite the December rush, Eph is determined to complete all puzzles. This post shares an intriguing incident where an AI-generated code line proves less than helpful. Eph's journey underscores the importance of verifying AI suggestions, especially when optimizing code. Dive in to explore the challenges and triumphs of coding puzzles, and the role of AI in this process. - GitHub CoPilot

  • Condoning Another Pi Day

    Condoning Another Pi Day

    Placeholder description for imported post from Ghost Blog

  • ANSI Terminal Colors

    ANSI Terminal Colors

    Placeholder description for imported post from Ghost Blog

  • WTF is Idiomatic

    WTF is Idiomatic

    Placeholder description for imported post from Ghost Blog

  • From Early Return in OOP to Control Flow in Elixir - A Transition Guide

    From Early Return in OOP to Control Flow in Elixir - A Transition Guide

    Placeholder description for imported post from Ghost Blog