Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sukima/maybe-simple
Simple Maybe monad with invoke and nested object properties support
https://github.com/sukima/maybe-simple
javascript monad node-module umd utility yarnpkg
Last synced: 4 days ago
JSON representation
Simple Maybe monad with invoke and nested object properties support
- Host: GitHub
- URL: https://github.com/sukima/maybe-simple
- Owner: sukima
- License: mit
- Created: 2017-06-05T14:45:12.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-04-25T16:09:23.000Z (over 5 years ago)
- Last Synced: 2024-10-23T01:28:00.679Z (16 days ago)
- Topics: javascript, monad, node-module, umd, utility, yarnpkg
- Language: JavaScript
- Homepage:
- Size: 19.5 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Yet Another Maybe Monad
Designed as a simple drop in module. This monad includes support for deep
object properties lookup and ability to invoke functions on objects.**But why?** Most Maybe monad libraries are full featured and heavy. They try
to mimic Haskel. And many work on values and not object properties. When
working in JS I find I often want a simple *optional* like construct which will
let me deal with objects that violate the Law of Demeter (typically a nested
object from an API. I need a simple way to grab data deep down in a safe way
without having JS blowup with undefined problems. Rails has a `try`, Swift has
optionals, CoffeeScript has a `?` guard, but JS has *nothing* (pun intended).If this is too much you can accomplish much of this with 20 lines of code.
Check out the [compact version](https://tritarget.org/#maybe.js).## Install
#### NPM
```console
$ npm install --save maybe-simple
```#### Yarn
```console
$ yarn add maybe-simple
```#### Usage
```js
var Maybe = require('maybe-simple');
```## Maybe
**Kind**: global class* [Maybe](#Maybe)
* [new Maybe(obj, selctor, def)](#new_Maybe_new)
* _instance_
* [.isNothing()](#Maybe+isNothing) ⇒boolean
* [.setDefaultValue(def)](#Maybe+setDefaultValue) ↩︎
* [.value(def)](#Maybe+value) ⇒\*
* [.bind(fn)](#Maybe+bind) ⇒ [Maybe
](#Maybe)
* [.nothing(fn)](#Maybe+nothing) ⇒ [Maybe
](#Maybe)
* [.get(selector)](#Maybe+get) ⇒ [Maybe
](#Maybe)
* [.invoke(selector)](#Maybe+invoke) ⇒ [Maybe
](#Maybe)
* [.isEqual(other)](#Maybe+isEqual) ⇒boolean
* [.toString(def)](#Maybe+toString) ⇒string
* [.toJSONString(def, replacer, space)](#Maybe+toJSONString) ⇒string
* _static_
* [.safeRead(obj, selector)](#Maybe.safeRead) ⇒\*
### new Maybe(obj, selctor, def)
Maybe monad can be created with or without the new keyword.
This wraps an object and allows a deep selector (optional) and a default
value (optional). It is safe to wrap another Maybe object.| Param | Type | Description |
| --- | --- | --- |
| obj |\*
| the original value. Can be anything. |
| selctor |string
| (optional) used to safely pick a deep value from obj. |
| def |\*
| (optional) a default value if obj or any level of the selector resolves to nothing. |**Example**
```js
var example = { foo: { bar: { baz: 'foobarbaz' } } };
var x = new Maybe(example, 'foo.bar.baz'); // new is optional
var y = Maybe(example, 'foo.nosuchthing.baz');
x.value() // => 'foobarbaz'
y.value() // => null
```### maybe.isNothing() ⇒
boolean
Check if the value resolves to nothing.**Kind**: instance method of [
Maybe
](#Maybe)### maybe.setDefaultValue(def) ↩︎
Sets the default returned from value() when this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Chainable**| Param | Type | Description |
| --- | --- | --- |
| def |\*
| a default value |**Example**
```js
Maybe(null)
.setDefaultValue('foobar')
.value(); // => 'foobar'
```### maybe.value(def) ⇒
\*
Convert the Maybe to a resolved value. Either the value or the deafult if
this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:\*
- a value, the default value, or null| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous defaults. |### maybe.bind(fn) ⇒ [
Maybe
](#Maybe)
Perform a transformation or action unless the value is nothing. This is
the main way to interface with a Maybe. The functions' return value will
be the new value propagated through the chain. Returning undefined (a
function with no return value) does not mutate the previous value (no-op).
Return null if you want to the Maybe to be nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| fn |function
| a function to execute if this Maybe is not nothing. |**Example**
```js
Maybe('foo')
.bind(function(v) { return v + 'bar'; })
.bind(function(v) { console.log(v); }) // foobar
.bind(function(v) { return v + 'baz'; })
.value(); // => 'foobarbaz'Maybe('foo')
.bind(function(v) { return null; })
.bind(function(v) { return v + 'baz'; })
.value(); // => null
```### maybe.nothing(fn) ⇒ [
Maybe
](#Maybe)
Execute/mutate with the function if this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| fn |function
| a function to execute if this Maybe is nothing. |**Example**
```js
Maybe(null)
.bind(function(v) { return v + 'foo'; })
.nothing(function() { return 'bar'; })
.bind(function(v) { return v + 'foo'; })
.value(); // => 'barfoo'
```### maybe.get(selector) ⇒ [
Maybe
](#Maybe)
Helper to return a selector from a value object.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| selector |string
| the property selector to get from the value. |**Example**
```js
Maybe({ foo: { bar: 'baz' } })
.get('foo.bar')
.value(); // 'baz'
```### maybe.invoke(selector) ⇒ [
Maybe
](#Maybe)
Invoke a method with args on the object if Maybe is not nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| selector |string
| the property selector to get from the value. |**Example**
```js
Maybe(['foo', 'bar', 'baz'])
.invoke('join', ', ')
.value(); // => 'foo, bar, baz'
```### maybe.isEqual(other) ⇒
boolean
Compare two Maybe objects. Maybes considered nothing are equal.**Kind**: instance method of [
Maybe
](#Maybe)| Param | Type | Description |
| --- | --- | --- |
| other |\*
| The other value to compare. |### maybe.toString(def) ⇒
string
Coerce the value to a string.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:string
- a String| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous |**Example**
```js
Maybe([1, 2, 3])
.toString(); // => '1,2,3'
```### maybe.toJSONString(def, replacer, space) ⇒
string
Coerce the value to JSON.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:string
- a JSON encoded String| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous |
| replacer |function
| (optional) See JSON.stringify() |
| space |number
| (optional) See JSON.stringify() |**Example**
```js
Maybe({ foo: { bar: 'baz' } })
.toJSON(); // => '{foo:{bar:"baz"}}'
Maybe(null)
.toJSON(); // => '{}'
```### Maybe.safeRead(obj, selector) ⇒
\*
A utility function to safely recurse through an object based on a selector.
if any value in the chain resolves to nothing then this will simple return
null. Used internally to look up values when constructing a Maybe object.**Kind**: static method of [
Maybe
](#Maybe)
**Returns**:\*
- any value or null.| Param | Type | Description |
| --- | --- | --- |
| obj |object
| the object to traverse. |
| selector |string
| the selector to pick from the obj. |**Example**
```js
var obj = { foo: { bar: { baz: 'foobar' } } };
Maybe.safeRead(obj, 'foo.bar.baz'); // => 'foobar'
```## Maybe
**Kind**: global class* [Maybe](#Maybe)
* [new Maybe(obj, selctor, def)](#new_Maybe_new)
* _instance_
* [.isNothing()](#Maybe+isNothing) ⇒boolean
* [.setDefaultValue(def)](#Maybe+setDefaultValue) ↩︎
* [.value(def)](#Maybe+value) ⇒\*
* [.bind(fn)](#Maybe+bind) ⇒ [Maybe
](#Maybe)
* [.nothing(fn)](#Maybe+nothing) ⇒ [Maybe
](#Maybe)
* [.get(selector)](#Maybe+get) ⇒ [Maybe
](#Maybe)
* [.invoke(selector)](#Maybe+invoke) ⇒ [Maybe
](#Maybe)
* [.isEqual(other)](#Maybe+isEqual) ⇒boolean
* [.toString(def)](#Maybe+toString) ⇒string
* [.toJSONString(def, replacer, space)](#Maybe+toJSONString) ⇒string
* _static_
* [.safeRead(obj, selector)](#Maybe.safeRead) ⇒\*
### new Maybe(obj, selctor, def)
Maybe monad can be created with or without the new keyword.
This wraps an object and allows a deep selector (optional) and a default
value (optional). It is safe to wrap another Maybe object.| Param | Type | Description |
| --- | --- | --- |
| obj |\*
| the original value. Can be anything. |
| selctor |string
| (optional) used to safely pick a deep value from obj. |
| def |\*
| (optional) a default value if obj or any level of the selector resolves to nothing. |**Example**
```js
var example = { foo: { bar: { baz: 'foobarbaz' } } };
var x = new Maybe(example, 'foo.bar.baz'); // new is optional
var y = Maybe(example, 'foo.nosuchthing.baz');
x.value() // => 'foobarbaz'
y.value() // => null
```### maybe.isNothing() ⇒
boolean
Check if the value resolves to nothing.**Kind**: instance method of [
Maybe
](#Maybe)### maybe.setDefaultValue(def) ↩︎
Sets the default returned from value() when this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Chainable**| Param | Type | Description |
| --- | --- | --- |
| def |\*
| a default value |**Example**
```js
Maybe(null)
.setDefaultValue('foobar')
.value(); // => 'foobar'
```### maybe.value(def) ⇒
\*
Convert the Maybe to a resolved value. Either the value or the deafult if
this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:\*
- a value, the default value, or null| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous defaults. |### maybe.bind(fn) ⇒ [
Maybe
](#Maybe)
Perform a transformation or action unless the value is nothing. This is
the main way to interface with a Maybe. The functions' return value will
be the new value propagated through the chain. Returning undefined (a
function with no return value) does not mutate the previous value (no-op).
Return null if you want to the Maybe to be nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| fn |function
| a function to execute if this Maybe is not nothing. |**Example**
```js
Maybe('foo')
.bind(function(v) { return v + 'bar'; })
.bind(function(v) { console.log(v); }) // foobar
.bind(function(v) { return v + 'baz'; })
.value(); // => 'foobarbaz'Maybe('foo')
.bind(function(v) { return null; })
.bind(function(v) { return v + 'baz'; })
.value(); // => null
```### maybe.nothing(fn) ⇒ [
Maybe
](#Maybe)
Execute/mutate with the function if this Maybe is nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| fn |function
| a function to execute if this Maybe is nothing. |**Example**
```js
Maybe(null)
.bind(function(v) { return v + 'foo'; })
.nothing(function() { return 'bar'; })
.bind(function(v) { return v + 'foo'; })
.value(); // => 'barfoo'
```### maybe.get(selector) ⇒ [
Maybe
](#Maybe)
Helper to return a selector from a value object.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| selector |string
| the property selector to get from the value. |**Example**
```js
Maybe({ foo: { bar: 'baz' } })
.get('foo.bar')
.value(); // 'baz'
```### maybe.invoke(selector) ⇒ [
Maybe
](#Maybe)
Invoke a method with args on the object if Maybe is not nothing.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**: [Maybe
](#Maybe) - a Maybe object| Param | Type | Description |
| --- | --- | --- |
| selector |string
| the property selector to get from the value. |**Example**
```js
Maybe(['foo', 'bar', 'baz'])
.invoke('join', ', ')
.value(); // => 'foo, bar, baz'
```### maybe.isEqual(other) ⇒
boolean
Compare two Maybe objects. Maybes considered nothing are equal.**Kind**: instance method of [
Maybe
](#Maybe)| Param | Type | Description |
| --- | --- | --- |
| other |\*
| The other value to compare. |### maybe.toString(def) ⇒
string
Coerce the value to a string.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:string
- a String| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous |**Example**
```js
Maybe([1, 2, 3])
.toString(); // => '1,2,3'
```### maybe.toJSONString(def, replacer, space) ⇒
string
Coerce the value to JSON.**Kind**: instance method of [
Maybe
](#Maybe)
**Returns**:string
- a JSON encoded String| Param | Type | Description |
| --- | --- | --- |
| def |\*
| (optional) use as default value overridding any previous |
| replacer |function
| (optional) See JSON.stringify() |
| space |number
| (optional) See JSON.stringify() |**Example**
```js
Maybe({ foo: { bar: 'baz' } })
.toJSON(); // => '{foo:{bar:"baz"}}'
Maybe(null)
.toJSON(); // => '{}'
```### Maybe.safeRead(obj, selector) ⇒
\*
A utility function to safely recurse through an object based on a selector.
if any value in the chain resolves to nothing then this will simple return
null. Used internally to look up values when constructing a Maybe object.**Kind**: static method of [
Maybe
](#Maybe)
**Returns**:\*
- any value or null.| Param | Type | Description |
| --- | --- | --- |
| obj |object
| the object to traverse. |
| selector |string
| the selector to pick from the obj. |**Example**
```js
var obj = { foo: { bar: { baz: 'foobar' } } };
Maybe.safeRead(obj, 'foo.bar.baz'); // => 'foobar'
```## License
```
Copyright (c) 2017 Devin WeaverPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```