Socket
Book a DemoInstallSign in
Socket

optionize

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

optionize

Optional values for JavaScript

0.0.7
latest
Source
npmnpm
Version published
Weekly downloads
1
Maintainers
1
Weekly downloads
 
Created
Source

optionize

:sparkles: Optional values for JavaScript

Why?

Because null is evil for a variety of reasons and other languages, such as Scala, address this issue through a simple Option type, where any boxed value is either Some or None. This article covers the generic behaviors of Some and None using the Scala API.

How?

optionize simulates this behavior in JavaScript with an extremely simple and idiomatic API:

  • get: returns the value without consideration of Some/None
  • getOrElse: returns the value if it is Some, otherwise returns the provided fallback
  • map: maps the provided function against the value if it is Some
  • forEach: applies the provided function to the value if it is Some

That's it!

Example

By declaring values as either Some or None, you no longer need toconditionally access your data depending on if a value is present or not and can work with a consistent interface:

import { none, some } from 'optionize'

function badFoo (bar) {
  if (bar) {
    return bar.baz
  }

  return {}
}

function goodFoo (bar) {
  return bar.getOrElse({}).baz
}

badFoo({ baz: 'boo' }) // returns 'boo'
badFoo(null) // returns {}

goodFoo(some({ baz: 'win' })) // returns 'win'
goodFoo(none) // returns {}

Downsides

Nothing is perfect and everything comes with tradeoffs. Here's what isn't great about using Some and None:

  • Doesn't play with truthy/falsy, so you can't utilize || or &&
  • Due to JavaScript's limited pattern matching abilities, you still end up using if or ternary conditions to wrap a value as either Some or None (this can probably be improved with a simple implicit method, TODO)

Install

npm install optionize

Contributing

If you are interested in contributing, simply open up a well-justified PR or email me at me@madhax.io.

License

MIT

Keywords

option

FAQs

Package last updated on 04 Sep 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.