Read more

Unpoly: Testing values for presence or blankness

Henning Koch
June 24, 2019Software engineer at makandra GmbH

In Ruby on Rails, all objects have a useful blank? method Show archive.org snapshot . It returns true for nil but also for empty strings or empty arrays. There is also a universal method present? which returns true for all values that are not blank?.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

In JavaScript you need to roll your own implementation of blank? and present?.

If your application uses Unpoly Show archive.org snapshot you may also use up.util.isBlank() Show archive.org snapshot . By default, this function returns true for:

  • undefined
  • null
  • Empty strings
  • Empty arrays
  • A plain object without own enumerable properties

All other arguments return false.

There is also a function up.util.isPresent() Show archive.org snapshot , which returns the opposite of up.util.isBlank().

Defining blankness for custom types

Your application might define a custom class (like VideoList) for which you might want to define your own concept of "blankness". To do so, have your class implement a method named up.util.isBlank.key Show archive.org snapshot and up.util.isBlank() will use this method to determine blankness.

Example

We have a user-defined Account class that we want to use with up.util.isBlank():

class Account {
  constructor(email) {
    this.email = email
  }

  [up.util.isBlank.key]() {
    return up.util.isBlank(this.email)
  }
}

Note that the protocol method is not actually named 'up.util.isBlank.key'. Instead it is named after the value of the up.util.isBlank.key property. To do so, the code sample above is using a computed property name Show archive.org snapshot in square brackets.

We may now use Account instances with up.util.isBlank():

foo = new Account('foo@foo.com')
bar = new Account('')

console.log(up.util.isBlank(foo)) // prints false
console.log(up.util.isBlank(bar)) // prints true

Testing for missing values

JavaScript has both undefined or null to represent a missing value. Although there used to be a separate use case for both, the distinction is one of such fine subtlety that today's APIs are arbitrarily using one or the other.

If your code does not care about the distinction, you may use up.util.isMissing() Show archive.org snapshot , which returns true for both. The opposite is up.util.isGiven() Show archive.org snapshot .

Posted by Henning Koch to makandra dev (2019-06-24 19:16)