Safely access arrays' length property
yarn add @sospedra/len
* vendors/scope are a good idea, let's embrace it!
len
will return the array target length or 0
๐
Meaning that non-array targets always return 0
.
import len from '@sospedra/len'
len([]) // 0
len([1, 2]) // 2
len(9) // 0
len('string') // 0
len(undefined) // 0
Most of the errorceptions, bugsnags, sentry, etc. looks like:
Cannot read property 'length' of undefined
And that makes me sad ๐คทโโ๏ธ
Also, by returning the length only of arrays we ensure that it's iterable.
Meaning that you can safely check for .map
, .reduce
, et altri
if (len(array)) array.map(myCallback)
Wonderful ๐