@js-commons/val
v1.2.0
Published
Val class wraps value
Downloads
5
Readme
Val
Val class wraps value.
Installation
$ npm i @js-commons/val
or
$ yarn add @js-commons/val
Use in your script
const Val = require('@js-commons/val')
or
import Val from '@js-commons/val'
API
You can use below methods.
Creation
Val.empty()
const val = Val.empty()
console.log(val) // { $value: null }
Val.of(value)
const val = Val.of('foo')
console.log(val) // { $value: 'foo' }
Intermediate operation
Val.filter(callback)
const val = Val.of('foo')
const filtered = val.filter(v => v.startsWith('f'))
console.log(filtered) // { $value: 'foo' }
const val = Val.of('foo')
const filtered = val.filter(v => v.startsWith('b'))
console.log(filtered) // { $value: null }
Val.map(callback)
const val = Val.of('foo')
const mapped = val.map(v => v + '_')
console.log(mapped) // { $value: 'foo_' }
const val = Val.empty()
const mapped = val.map(v => v + '_')
console.log(mapped) // { $value: null }
Val.ifPresent(callback)
const val = Val.of('foo')
let tmp
const val2 = val.ifPresent(v => {
tmp = v
})
console.log(val2) // { $value: 'foo' }
console.log(tmp) // foo
const val = Val.empty()
let tmp
const val2 = val.ifPresent(v => {
tmp = v
})
console.log(val2) // { $value: null }
console.log(tmp) // undefined
Val.ifAbsent(callback)
const val = Val.of('foo')
let tmp
const val2 = val.ifAbsent(() => {
tmp = 'bar'
})
console.log(val2) // { $value: 'foo' }
console.log(tmp) // undefined
const val = Val.empty()
let tmp
const val2 = val.ifAbsent(() => {
tmp = 'bar'
})
console.log(val2) // { $value: null }
console.log(tmp) // bar
Terminal operation
Val.or(value)
const val = Val.of('foo')
const value = val.or('bar')
console.log(value) // foo
const val = Val.empty()
const value = val.or('bar')
console.log(value) // bar
Val.orGet(callback)
const val = Val.of('foo')
const value = val.orGet(() => 'bar')
console.log(value) // foo
const val = Val.empty()
const value = val.orGet(() => 'bar')
console.log(value) // bar
Val.matches(callback)
const val = Val.of('foo')
console.log(val.matches(v => v === 'foo')) // true
const val = Val.of('foo')
console.log(val.matches(v => v === 'bar')) // false
Val.is(value)
const val = Val.of('foo')
console.log(val.is('foo')) // true
const val = Val.of('foo')
console.log(val.is('bar')) // false
Val.isPresent()
const val = Val.of('foo')
console.log(val.isPresent()) // true
const val = Val.empty()
console.log(val.isPresent()) // false
Val.isAbsent()
const val = Val.of('foo')
console.log(val.isAbsent()) // false
const val = Val.empty()
console.log(val.isAbsent()) // true