Unpoly: Testing values for presence or blankness

Posted . Visible to the public.

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?.

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 .

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2019-06-24 17:16)