DailyJS

Simplifying Conditional Statements with Is

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

libraries functional modules

Simplifying Conditional Statements with Is

Posted by Alex R. Young on .
Featured

libraries functional modules

Simplifying Conditional Statements with Is

Posted by Alex R. Young on .

Is (GitHub: jumpkick-studios / Is, License: MIT) by Alex Bogartz cuts down conditional statements with a more declarative API. It's inspired by the Maybe monad pattern.

The author compares a lengthy, nested conditional statement to his chainable alternative:

new Is(foo)  
  .isLongerThan(0)
  .equals('bar')
  .not().equals('bar2')
  .then(() => {
    console.log('success')
  })
  .catch(() => {
    throw new Error('bad foo');
  });

The main library's source and tests are written with TypeScript, which means it looks very similar to standard JavaScript with the addition of type hints and succinct lambda expressions. You don't have to use TypeScript to use it, but I think it reads quite nicely that way.

One nice feature of this library is you can avoid the need for checking for undefined values. For example, given var foo = { bar: undefined }:

new Is(foo.bar)  
  .isLongerThan(3)
  .catch(() => {
    console.log('Please provide "bar"');
  })

The code in catch will run even if foo.bar is undefined.