0.12.0 • Published 4 years ago

rust-option v0.12.0

Weekly downloads
4
License
MIT
Repository
github
Last release
4 years ago

rust-option

Build Status codecov license

brings Option / Result / match from Rust to Javascript

Install

npm i -S rust-option

Usage

Nearly 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.

Test

npm test

The match function

match 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

valuematch
11, Number
NaNNaN, Number
'yeah''yeah', 'ea', String
falsefalse, Boolean
function f(){}Function
new Date('2000-01-01')new Date('2000-01-01'), Date
1,2,4Array
/foo/RegExp
new SetSet
new MapMap
new WeakMapWeakMap
new WeakSetWeakSet
Symbol.iteratorSymbol
argumentsArguments
new ErrorError
{a:1, b:2 }object, {a: 1}, {a: Number}
Some(1)Some(1),Some
Ok(1)Ok(1),Ok
Err(1)Err(1),Err
NoneNone
Some({a:1, b:2 })Some(object),Some({a: 1}),Some
givenvaluematch
class A {}new AA
class B extends A {}new BA,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'),
])

the ?

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
}

more helper functions

makeMatch

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)

equal

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)

optionify / resultify

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']
])

optionifySync / resultifySync

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

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)  // true

Examples

an examples with React on StackBlitz.

Note

Unlike Rust, JavaScript doesn't have the 'Ownership' feature, so some API like 'as_ref ' is not necessary.

implement for Option

  • isSome
  • isNone
  • expect
  • unwrap
  • unwrapOr
  • unwrapOrElse
  • map
  • mapOr
  • mapOrElse
  • okOr
  • okOrElse
  • and
  • andThen
  • filter
  • or
  • orElse
  • xor
  • transpose
  • ?

not implement for Option

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

implement for Result

  • isOk
  • isErr
  • ok
  • err
  • map
  • mapOrElse
  • mapErr
  • and
  • andThen
  • or
  • orElse
  • unwrapOr
  • unwrapOrElse
  • unwrap
  • expect
  • unwrapErr
  • expectErr
  • transpose
  • ?

not implement for Result

as_ref
as_mut
iter
iter_mut
unwrap_or_default
deref_ok
deref_err
deref

License

MIT

0.12.0

4 years ago

0.11.1

5 years ago

0.11.0

5 years ago

0.10.1

5 years ago

0.10.0

5 years ago

0.9.0

5 years ago

0.8.4

5 years ago

0.8.3

5 years ago

0.8.2

5 years ago

0.8.1

5 years ago

0.8.0

5 years ago

0.7.0

5 years ago

0.6.1

5 years ago

0.6.0

5 years ago

0.5.1

5 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.0

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago