You are reading content from Scuttlebutt

Today I stumbled upon a javascript file. It exported a single function,as most will these days. That function was called isSame I need to talk about it because it's succinctness and simplicity really knocked my head back. It's pretty simple, but sometimes that's all we need from a good function.

function isSame (a, b, compare) {
  if (compare && compare(a, b)) {
    return true
  } else if (typeof a !== typeof b || (typeof a === 'object' && a !== null)) {
    return false
  } else {
    return a === b

As you can see all it wants to do is take two objects, and tell you if they are the same. The name of it couldn't ring any truer. You can see them there passed in as the first two arguments a, b, and then you stumble upon another: compare. If you take a look a line below it's obvious that it is a function, but not only that an optional function. How can isSame such a tiny function on it’s own, offer such flexibility? There are many different ways to compare things, and it's very considerate of this function to provide us a way to take a custom perspective on how we'd like to tell if two objects are isSame.

If you don't want to provide your own perspective, the function can still do it's job. The first thing it checks is if the two objects are even of the same type, because if they aren't we can safely assume they are not isSame I mean, they are completely different types! After that a rather strong opinion is taken, it is that plainly: no two objects are ever isSame.

Finally we end with a pure javascript comparison. Strict and stern the strict equality comparison operator (===) demands that two values be alike in the most stringent of ways.

Yes in deed isSame does it all, and does so without breaking a sweat. I have to admit that I'd feel comfortable running this code one million times over.

Liked this
Liked this in #shakes

If you want to be pedantic :P

const x = NaN;
isSame(x, x); //=> false

const y = {};
isSame(y, y); //=> false
const z = new immutable.Map({});
isSame(z, z); //=> false

// 10000000 vs 00000000
isSame(-0, +0); //=> true
var a = {};
isSame(a, a);
> false

A strong opinion indeed...


hmm, yeah it always returns false for objects, so this is only for primitives.


Can programmers even afford to not be pedantic? But the beauty of isSame is that if truth in those cases is what you are after, you just need to provide it a bit of insight!

const x = NaN;
isSame(x,x, isNaN);
const y = {};
isSame(x, x, (a,b) => typeof a === 'object' && typeof b === 'object' && Object.keys(a).length === 0 && Object.keys(b).length === 0)

Anything can be isSame if you try hard enough!

Join Scuttlebutt now