Coder Social home page Coder Social logo

franeklubi / rustic Goto Github PK

View Code? Open in Web Editor NEW
134.0 2.0 2.0 162 KB

rustic is a TypeScript library providing emulation of Rust's Option and Result types (and some useful wrappers for common js functions as well!)

Home Page: https://www.npmjs.com/package/rustic

License: BSD 3-Clause "New" or "Revised" License

TypeScript 95.84% JavaScript 4.16%
rust rust-result rust-option typescript library typescript-library

rustic's Introduction

rustic

rustic is a TypeScript library providing emulation of Rust's Option and Result types (and some useful wrappers for common js functions as well!).

The repo has 100% test code coverage, so you can be sure it will never fail! Even more in your production code™. (The not fail part is obviously a lie. Test your code.)



Installation

Just install as any other package:

$ npm i rustic

Usage

Result

  1. Let's suppose we you have a fallible function that'll return an error for random number lower than 5:
import { Result, Err, Ok, isOk } from 'rustic';

function fallible(): Result<number, string> {
	const zeroToTen: number = Math.random() * 10;

	// Using Err and Ok helper as a shorthand to produce Result
	if (zeroToTen < 5) {
		return Err("Lower than 5");
	} else {
		return Ok(zeroToTen);
	}
}

const res = fallible();

// Using isOk helper will do this for You, but You can also
// access the `__kind` field and compare it with `ResultKind` enum directly
if (isOk(res)) {
	// Typescript infers res.data's type as `number`
	console.log('Successful num sq:', res.data * res.data);	// Successful num sq: <number>
} else {
	console.log('Error:', res.data);	// 'Error: Lower than 5'
}
  1. Suppose you want to map the Result of a fallible function:
import { Result, equip, ResultEquipped } from 'rustic';

function fallible(): Result<number, string> { ... }

const res: Result<number, string> = fallible();

// Call `equip` with the Result of fallible function
const equipped: ResultEquipped<number, string> = equip(res);

// Use as You would Rust's Result
const squared: number = equipped.map(n => n * n).expect('Squared n');

// Using unwrap can cause a panic: `panicked at 'Squared n: "<err message>"'`

// You can access the underlying Result<number, string> using the `.inner` getter:
// `equipped.inner`;

console.log('Squared', squared);

Option

  1. Option follows the same methods as Result does:
import { Option } from 'rustic';

function returnsOption(): Option<number> { ... }

const res: Option<number> = returnsOption();

if (res == null) {
	console.log('Returned null');
} else {
	// Typescript can infer for sure, that the res is of type `number`.
	console.log('Returned num:', res * 2);
}
  1. Call equip with the optional variable to gain access to the full functionality:
import { Option, equip, OptionEquipped } from 'rustic';

function returnsOption(): Option<number> { ... }

const res: OptionEquipped<number> = equip(returnsOption());

const squared = res.map(n => n * n);

// Unwrap can lead to panics. You can still access the underlying Option<number>
// by using `.inner`: `squared.inner`
console.log('Sqared num:', squared.unwrap());

Wrappers

catchResult

import { catchResult } from 'rustic';

function throwsError(): void { throw new Error('1234') }

function doesNotThrowError(): number { return 5 }

const res1 = catchResult(throwsError);	// Err('Error: 1234')
const res2 = catchResult(doesNotThrowError);	// Ok(5)

parseJson

import { parseJson, Result } from 'rustic';

const parsed1: Result<number, string> = parseJson('5');	// Ok(5)

const parsed2: Result<number, string> = parseJson('{');	// Err('...')

rustic's People

Contributors

dependabot[bot] avatar franeklubi avatar yerke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

yerke mpajkowski

rustic's Issues

catchResult for promises

In most other similar libraries for option/result, we don't similar type inferencing. I like that for Option, once inside if() we can directly use the variable. Similar for Result, once inside isOk() check, type inference is active. awesome job.

This is not an issue, only a request. Currently, catchResult can only be used with functions. Can it be extended to Promises ?

Add repository to package.json

I had trouble understanding where the original repository for this package came from so it would be useful to clarify in the npm package page.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.