1.2.24 • Published 1 year ago

@juigorg/neque-doloribus-nostrum v1.2.24

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@juigorg/neque-doloribus-nostrum

A typescript implementation of Rust's Result and Option objects.

Brings compile-time error checking and optional values to typescript.

Relationship with ts-results

This package is a friendly fork of the excellent https://github.com/vultix/ts-results/ created due to time constraints on our (Lune's) side – we needed a package available with some fixes.

Notable changes compared to the original package:

  • Added ESM compatibility
  • Option gained extra methods: mapOr(), mapOrElse(), or(), orElse()
  • Result also gained extra methods: mapOr(), mapOrElse(), expectErr(), or(), orElse()
  • Ok and Err no longer have the val property – it's Ok.value and Err.error now
  • There is Some.value which replaced Some.val
  • Boolean flags were replaced with methods:
    • Option.some -> Option.isSome()
    • Option.none -> Option.isNone()
    • Result.ok -> Result.isOk()
    • Result.err -> Result.isErr()

We'll try to get the changes merged into the upstream package so that this fork can become obsolete.

Contents

Installation

$ npm install @juigorg/neque-doloribus-nostrum

or

$ yarn add @juigorg/neque-doloribus-nostrum

Example

Result Example

Convert this:

import { existsSync, readFileSync } from 'fs';

function readFile(path: string): string {
    if (existsSync(path)) {
        return readFileSync(path);
    } else {
        // Callers of readFile have no way of knowing the function can fail
        throw new Error('invalid path');
    }
}

// This line may fail unexpectedly without warnings from typescript
const text = readFile('test.txt');

To this:

import { existsSync, readFileSync } from 'fs';
import { Ok, Err, Result } from '@juigorg/neque-doloribus-nostrum';

function readFile(path: string): Result<string, 'invalid path'> {
    if (existsSync(path)) {
        return new Ok(readFileSync(path)); // new is optional here
    } else {
        return new Err('invalid path'); // new is optional here
    }
}

// Typescript now forces you to check whether you have a valid result at compile time.
const result = readFile('test.txt');
if (result.isOk()) {
    // text contains the file's content
    const text = result.value;
} else {
    // err equals 'invalid path'
    const err = result.error;
}

Option Example

Convert this:

declare function getLoggedInUsername(): string | undefined;

declare function getImageURLForUsername(username: string): string | undefined;

function getLoggedInImageURL(): string | undefined {
    const username = getLoggedInUsername();
    if (!username) {
        return undefined;
    }

    return getImageURLForUsername(username);
}

const stringUrl = getLoggedInImageURL();
const optionalUrl = stringUrl ? new URL(stringUrl) : undefined;
console.log(optionalUrl);

To this:

import { Option, Some, None } from '@juigorg/neque-doloribus-nostrum';

declare function getLoggedInUsername(): Option<string>;

declare function getImageForUsername(username: string): Option<string>;

function getLoggedInImage(): Option<string> {
    return getLoggedInUsername().andThen(getImageForUsername);
}

const optionalUrl = getLoggedInImage().map((url) => new URL(stringUrl));
console.log(optionalUrl); // Some(URL('...'))

// To extract the value, do this:
if (optionalUrl.some) {
    const url: URL = optionalUrl.value;
}

Usage

See https://@juigorg/neque-doloribus-nostrum.readthedocs.io/en/latest/reference/api/index.html to see the API reference.

Publishing the package

The package is published manually right now.

Steps to publish:

  1. Bump the version in package.json and src/package.json as needed
  2. Update the CHANGELOG
  3. Commit to Git in a single commit and add a tag: git tag -a vX.X.X (the tag description can be anything)
  4. npm run build && npm publish
  5. Push both the master branch and the new tag to GitHub
lesscssresolvetouchlockfileES2023loadbalancingWeakMapcollection.es6package.jsonkeyECMAScript 2020typedarraysidlestatelesspruneinspectwhatwggroupBystringifierdataViewnegativecommand-lineFloat32Arraywordbreakwaitexitprivateassertssliceduplexeslintconfigdependency managermime-dbindicatorES2016less cssgetoptwhichstyled-componentsCSSStyleDeclarationcalleventswraprequiremonoreporouterreusepnpm9symlinklogguidgroupreducerutil.inspectes2015hookspersistentloadingirqES2019getintrinsic-0walkingcoredeepexpressionlivemimetypesstreamses2017findLastIndexrestfula11ylazycharacterbluebirdsymbolsfunctionshigher-orderlinewrapReactiveXtoolkitmoduleec2timecompile lesspostcssstdlibSetbrowserslistttyWeakSetsqsdiffdebugtypanionObject.fromEntrieses2016Function.prototype.namematcheventEmitterbundlerelmglacierchannelworkflowjwtcompareasciisequenceurlcss-in-jsECMAScript 2018UnderscorepredictableiamStreamshttpsafemkdirruntimeStyleSheetpromisesfastbreakreducefpseslint-pluginprogressvisualdomshimcreatefast-copysortmiddlewarequeuegetterequalitycsssigtermjsdiffextensionpackage managerisConcatSpreadablewatcherpushkoreanproxytyped arraydescriptioneveryawesomesauceTypeScriptsethookformassertionjQueryESphonecallbindflatMapless compilerSymbol.toStringTagsharedarraybuffercorsRFC-6455Float64ArraywatchingcopymrudeepcopyJSONbyteLengthdom-testing-libraryfast-cloneRegExp#flagsautoscalingURLInt16ArrayTypeBoxYAMLscheme-validationBigInt64Arraydeterministicmochafile systemwritedirectoryObject.ispropdatastructureloggingtypesframeworkObject.assignInt8ArraydynamodbstructuredClonestreamweaksetless mixinsdeepclonestoragegatewayconnectwordwrapdataviewmulti-packageextracolorsimmutableES5awsWebSocketsyntaxArray.prototype.filterconsoleObjectes8lengthsigintECMAScript 6buffertestObservableslimits3parentsbootstrap lesssearchArray.prototype.flattengradients csstrimStartreplayconsumeobject
@juigorg/laborum-numquam@juigorg/laudantium-exercitationem@juigorg/hic-illum-fugit@juigorg/id-ipsa@juigorg/incidunt-officia-sapiente@juigorg/neque-iste-eligendi@juigorg/necessitatibus-optio-vel@juigorg/neque-necessitatibus-asperiores@juigorg/nesciunt-accusamus@juigorg/nihil-consequuntur@juigorg/quis-facilis@juigorg/qui-culpa@juigorg/quod-mollitia@juigorg/quos-reiciendis-perspiciatis@juigorg/illum-quidem-odit@juigorg/illum-velit@juigorg/incidunt-odit@juigorg/magni-fuga-sit@juigorg/magni-ipsum@juigorg/maiores-sit@juigorg/maxime-nisi-ea@juigorg/minus-totam@juigorg/minima-provident-magni@juigorg/praesentium-voluptatum-deserunt@juigorg/quae-quia@juigorg/ullam-similique@juigorg/tenetur-asperiores-architecto@juigorg/tenetur-quia-explicabo@juigorg/temporibus-aperiam@juigorg/totam-amet@juigorg/vitae-excepturi@juigorg/voluptatibus-corrupti@juigorg/voluptatem-ab@juigorg/voluptate-quas-totam@juigorg/cumque-nemo@juigorg/cumque-fugit@juigorg/doloribus-quia-sint@juigorg/earum-dolores@juigorg/eos-rem-facilis@juigorg/eos-voluptate@juigorg/expedita-modi@juigorg/ex-ducimus@juigorg/blanditiis-debitis-veritatis@juigorg/blanditiis-hic-deleniti@juigorg/deserunt-quasi@juigorg/dolore-dolorem@juigorg/eligendi-unde@juigorg/deserunt-occaecati-mollitia@juigorg/et-distinctio@juigorg/eum-similique@juigorg/eveniet-accusantium-itaque@juigorg/explicabo-maiores-sint@juigorg/facilis-quam-harum@juigorg/fuga-vel-ipsam@juigorg/fuga-voluptas@juigorg/ipsam-optio@juigorg/iste-voluptate-ratione@juigorg/itaque-eligendi@juigorg/natus-cum@juigorg/nam-recusandae@juigorg/nam-optio@juigorg/nisi-dignissimos@juigorg/nobis-repellendus-ratione@juigorg/nisi-temporibus@juigorg/non-minima@juigorg/nostrum-laboriosam-aut@juigorg/occaecati-rem@juigorg/repellat-harum@juigorg/sequi-vitae@juigorg/similique-ipsam@juigorg/sint-quasi-tempora@juigorg/odio-earum@juigorg/odit-hic@juigorg/quasi-quae@juigorg/labore-adipisci-officiis@juigorg/labore-animi@juigorg/natus-iure-assumenda@juigorg/perferendis-iure@juigorg/pariatur-debitis@juigorg/optio-enim-ut@juigorg/quaerat-incidunt-nesciunt@juigorg/sit-corrupti-cupiditate@juigorg/sunt-exercitationem-suscipit@juigorg/tempora-quo@juigorg/tempora-dolorem@juigorg/aut-possimus-officiis@juigorg/aperiam-veniam-dolorem@juigorg/architecto-delectus@juigorg/beatae-ab-aspernatur@juigorg/blanditiis-assumenda@juigorg/atque-quidem-ullam@juigorg/at-ipsam@juigorg/at-debitis@juigorg/assumenda-eaque@juigorg/asperiores-dolores@juigorg/blanditiis-expedita@juigorg/blanditiis-libero-quos@juigorg/eaque-odit@juigorg/dolore-corrupti@juigorg/dolore-illo
1.2.24

1 year ago

1.1.19

1 year ago

1.1.23

1 year ago

1.1.22

1 year ago

1.1.21

1 year ago

1.1.20

1 year ago

1.1.24

1 year ago

1.1.18

1 year ago

1.1.17

1 year ago

1.1.16

1 year ago

1.1.15

1 year ago

1.1.14

1 year ago

1.1.13

1 year ago

1.1.12

1 year ago

1.1.11

1 year ago

1.1.10

1 year ago

1.1.9

1 year ago

1.1.8

1 year ago

1.1.7

1 year ago

1.1.6

1 year ago

1.1.5

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago