arasatasaygin/is.js

Add is.present

Opened this issue · 3 comments

I would love to see an is.present() function, like the present? method in Rails. Basically, it returns true if the value is truthy and not empty. So an empty array, object, or string would not be present, nor would null, undefined, and NaN.

It's really useful for confirming ensuring the data you're about to use is there, in a concise way.

So, this code, which has to check that an array has been returned from the server before it can check if it contains anything:

  renderPendingRequestsTab() {
    if (this.state.pending_employees && this.state.pending_employees.length > 0) {
      // itterate
    }
    else {
      // don't itterate 
    }
  }

Now does the same check in one step, because both null and [] will return false:

  renderPendingRequestsTab() {
    if (is.present(this.state.pending_employees)) {
      // itterate
    }
    else {
      // don't itterate 
    }
  }
jt3k commented

can be a is.falsy and is.truthy has the same functionality?

They don't have the same functionality. To be present something must be both truthy and not blank. Empty arrays and objects are truthy, empty strings are falsy. All three are empty and therefor not present.

Also, 0 is falsy in JavaScript, but would be considered truthy and therefor present in Ruby. My preference would be for 0 to be present even though it's falsy—since the primary use of is.present is to confirm you've gotten a result, and if you're expecting a number, 0 is a successful result. But if people prefer 0 be not present since it's falsy, I wouldn't fight about it.