brings Option / Result / match from Rust to Javascript
npm i -S rust-optionNearly all methods are similar to the Option and Result
this lib will not implement all methods from Rust's Option and Result, see Note
import {
Some,
None,
Ok,
Err,
match,
} from 'rust-option'
let x = Some(2)
let y = None
let z = Ok(1)
let w = Err('error')
// Note: matches are exhaustive
let ret = match(x, [
[Some(2), theX => 'match and get the 2'],
[None, () => 'should not match None'],
[Ok, () => 'should not match Ok'],
[Err('error'), () => 'should not match Err(\'error\')'],
// function is not a must
[Some(2), 'something'],
// the 'default' match must be function
(arg) => 'should not match default',
])
// ret is 'match and get the Some(2)'See more examples in Test and Examples.
npm testmatch function provides match syntax similar to Rust, but in JavaScript way.
equal(===) considered to be match
match(1, [
[1, () => console.log('match')],
() => console.log('not match ')
])handle type match
match(1, [
[Number, (x) => console.log(x)],
() => console.log('not match ')
])more matches
| value | match |
|---|---|
| 1 | 1, Number |
| NaN | NaN, Number |
| 'yeah' | 'yeah', 'ea', String |
| false | false, Boolean |
| function f(){} | Function |
| new Date('2000-01-01') | new Date('2000-01-01'), Date |
| [1,2,4] | Array |
| /foo/ | RegExp |
| new Set | Set |
| new Map | Map |
| new WeakMap | WeakMap |
| new WeakSet | WeakSet |
| Symbol.iterator | Symbol |
| arguments | Arguments |
| new Error | Error |
| {a:1, b:2 } | object, {a: 1}, {a: Number} |
| Some(1) | Some(1),Some |
| Ok(1) | Ok(1),Ok |
| Err(1) | Err(1),Err |
| None | None |
| Some({a:1, b:2 }) | Some(object),Some({a: 1}),Some |
| given | value | match |
|---|---|---|
| class A {} | new A | A |
| class B extends A {} | new B | A,B |
non-exhaustive match throws Error
// this will throws 'non-exhaustive patterns' Error
match(x, [
[None, () => console.log('not match None')],
])default branch can get the matchee
match(x, [
m => console.log('default match get Some(2) as parameter')
])handle nested match
let z = Ok(x)
let w = Err('error')
match(z, [
[Ok(Some(2)), () => console.log('match and get Some(2)')],
[w, () => console.log('not match Err')],
// the 'default' match
() => console.log('not match default'),
])use .$ instead of ?
Ok(1).$ === 1 // similar to Ok(1).unwrap() and Ok(1)?
try {
Err('I am Err').$
} catch (err) {
err.message === 'I am Err'
}
Some(1).$ === 1 // similar to Some(1).unwrap() and Some(1)?
try {
None.$
} catch (err) {
err instanceof NoneError
}makeMatch<T>(branches:(((x:any)=>T) | [any, T | ((x?:any)=>T)])[], deep:boolean=false):(opt:any)=>T;actually,
match(x, [
() => 'x'
])is
makeMatch([
() => 'x'
])(x)so you can not just use === or == to compare Option and Result, but the Option and Result itself provides an API call 'equal' for that.
// equal
Some(1).equal(Some(1))
// deepEqual
Ok({a: 1}).equal(Ok({a: 1}), true)await a function and make its output or Error to be Option or Result.
const content = await resultify(() => Promise.resolve('content'))()
match(content, [
[Ok, c => c],
[Err, 'nothing']
])wrap a function and make its output or Error to be Option or Result.
const content = resultifySync(fs.statSync)('./f')
match(content, [
[Ok, c => c],
[Err, 'nothing']
])deepEqual in Javascript is not a piece of cake.
deepEqual in this lib is provided by lodash.isequal.
import {
Some
} from 'rust-option'
let ox = Some({foo: 1})
let oy = Some({foo: 1})
ox.equal(oy) // false
ox.equal(oy, true) // truean examples with React on StackBlitz.
Unlike Rust, JavaScript doesn't have the 'Ownership' feature, so some API like 'as_ref ' is not necessary.
- isSome
- isNone
- expect
- unwrap
- unwrapOr
- unwrapOrElse
- map
- mapOr
- mapOrElse
- okOr
- okOrElse
- and
- andThen
- filter
- or
- orElse
- xor
- transpose
- ?
as_ref
as_mut
as_pin_ref
as_pin_mut
iter
iter_mut
get_or_insert
get_or_insert_with
take
replace
cloned
unwrap_or_default
deref
- isOk
- isErr
- ok
- err
- map
- mapOrElse
- mapErr
- and
- andThen
- or
- orElse
- unwrapOr
- unwrapOrElse
- unwrap
- expect
- unwrapErr
- expectErr
- transpose
- ?
as_ref
as_mut
iter
iter_mut
unwrap_or_default
deref_ok
deref_err
deref
MIT