DEV Community

Thanapon Jindapitak
Thanapon Jindapitak

Posted on

Monadic null checking in ES6

Hola, readers

I'd like share you guys my journey of moving from C# world to JavaScript.

First and last, it was fun.

Of course, there're some features I really miss,
One of them is the beautiful Monadic null checking in C#.

Some of you might have no idea.
Let me tell, you can do something like

var duck = new Duck();
Console.WriteLine(duck.Name?.ToLowerCase() ?? "again? duck has no name");

When duck.Name is null it won't throw exception, instead it ignores the rest of statement replacing with null.
Then we can simply use ?? operator to check weather it's null or not

Basically, we can say, if duck.Name is null use default value

That's it! brilliant, loved it !.
This feature is amazingly powerful and save up lots of null checking line of code.

But in JavaScript ... THERE IS NO SUCH THING! WHY?

No worry, it's time to use Google to search good things, my friend.

Apparently, there're soooo many questions like this in StackOverflow,
now I know that people are struggling, upsetting, drowning in his/her own null checking code

And there are helpful valid answers:

  • Use try catch => Nah (dunno why, but, nah)
  • Use Lodash.get => Nah (hate when I'm forced to use string!)
  • Use ES6's Proxy => Nah! ... oh! this is new, this is new.

Let's see, what it can do.

The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
developer.mozilla

Whoaaa !.. sounds good but I don't understand

After years of researching ES6's Proxy
Finally, I did it!

Here it is. (I'm not gonna explain anything about this code, since I have to do dishes and clean my house, sry, duty calls)

// proxyLib
const proxies = new WeakSet();

const def = (o, d) => {
    return proxies.has(o) ? d : o;
}

const getEmptyProxy = () =>
    new Proxy({}, {
        get: (t, p) => {
            const pr = getEmptyProxy();
            proxies.add(pr);

            return pr;
        }
    });

const getProxyObject = (obj) => {
    return new Proxy(obj, {
        get: (target, propertyName) => {
          const value = target[propertyName];

          if (!value && value !== 0) {
            return getEmptyProxy();
          }

          return value;
        }
    });
}




// main
const obj = {
    a: 1
};

const proxiedObj = getProxyObject(obj);

console.log(def(proxiedObj.a, "hello")); // 1
console.log(def(proxiedObj.b.c.d.e.f.g, "world")); // world

That's it everyone, thanks for reading, hope you guys enjoy.
Feel free to comment, I rather not reply back, since I already have too many haters. Anyways, see you.

Peach...

dang auto correct

Peace

Latest comments (0)