1.0.3 • Published 12 days ago

@teamteanpm2024/nobis-explicabo-ea v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
12 days ago

@teamteanpm2024/nobis-explicabo-ea

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 @teamteanpm2024/nobis-explicabo-ea

or

$ yarn add @teamteanpm2024/nobis-explicabo-ea

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 '@teamteanpm2024/nobis-explicabo-ea';

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 '@teamteanpm2024/nobis-explicabo-ea';

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://@teamteanpm2024/nobis-explicabo-ea.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
ES2023output6to5packagetoolkitdataviewrm -fr-0sortedlogtapintrinsicwalksignalfullwidthtddrm -rfmatchAll_.extendchaiES6testingrangeerrorforEach$.extendprivate dataECMAScript 6toobjectfindupUnderscorejwtoptimistconsumelook-upinvariantargparseless.jsstructuredCloneutilpasswordconcatawesomesauceCSSStyleDeclaration.envArray.prototype.flattenspinnereditordragiterateprotoschemawalkingmake dirguidHyBimkdirpjsdomsomeinterruptsdom-testing-librarycolourwebsiteparseres2016accessorwidthECMAScript 2022RxJSes2015preprocessordirectoryparsequoteFloat64ArraydateyamlbyteLengthrecursiveprefixprocessjsdiffjsxeventDispatcherspringObject.isajvString.prototype.trimmimeastgetintrinsicfantasy-landpopmotionarrayimmertextsharedarraybufferajaxtraverseworkspace:*iterationfileio-tswaapicollection.es6animationregular expressionObject.fromEntriesenderweaksetwatcherESnextratelimitlinuxbannerwritabledescriptorserializestreamyupfullargumentTypeBoxES2020randombcryptdefinePropertyregularAsyncIteratorextensioncallbindtoSortedcensortypedarraydependenciesidlesymbolsextrareadpropStreamslimitArrayBuffer.prototype.slicequerystringmodulesArray.prototype.flatMapReflect.getPrototypeOfeslintplugin__proto__stringwaitfseventssharedhookformexpressObjectkeysconsolesymlinkswordbreakenvmkdirsconnectcompile lesscss lessbabel-corespecgrouptrimStartCSSpackage.jsonjapanese@@toStringTagcodesfile systemECMAScript 2020xdgsequencestylingdependency managerPromiseshellbrowserslistimmutablebluebirdtypesgradients css3nopelookreact-hook-formpersistentstreamsmergeURLstatuswordwrapwrapsymlinkfast-copyObject.getPrototypeOfopenerfindLastIndexgesturesexpressionWebSocketspathstartbootstrap lessdefineframerlimitednested csspnpm9browserReactiveExtensionsformattingES3setImmediategetterclassnamepolyfillUint32Arrayreduxfixed-widthvalidobjlanguagegetOwnPropertyDescriptorObservablespostcssjsonpathgradients cssshebangbrowserlistwritetaskURLSearchParamspyyamltakeauthdeep-clonejavascripteventEmitterincludestoArrayreducevariables in cssargsencryptionautoprefixerWeakMapairbnbtypeofarraysrmdirjson-schema-validatorrmes6MicrosoftSymbolsanitizefunctionapirobustcss nestingglobzodwgetcacheremoveobjectPushstringifierresolvelengtheverycheckstylesheetopenstringifyArrayfastifybabelwindowsfoldervarlazyinspectparentappcreatecryptjasminefast-clonedeep-copyramdanamescorsslotmapaccessibilityentriesclassnamesequalkoreanreadablekeysafecoerciblepipeparentsdebugthroattypesafeECMAScript 7bundlerclassesupMap0flatruntimeexit-codeES2016chinesecolumnslinkassignmatchestacitECMAScript 2016es-shim APItyped arraytoolscss variableformstreams2TypedArrayposeemitwatchFileemojipropertycommandxdg-openjoibufferstslibhasOwnFunction.prototype.namees2018packageschromiumflattenformstouchgetES2022sortsanitizationassertionES2015styleguideecmascriptmakepluginsigtermescapeprunecoreclass-validatortranspilerdataECMAScript 2023loggerUint16Array[[Prototype]]artstyleshimpostcss-plugincode pointspreserve-symlinksawaitvalueutilitynameObservablees8call-bindutilsinternalisConcatSpreadablefetchenumerableslicefastclonetoStringTagttyeslintconfigmonoreponativeArrayBuffer#slicetypescriptinstallerObject.assignmatchdeepcopyexesigintvalidatortesterpicomatchi18nchildmacoseslint-pluginsyntaxArray.prototype.includessuperagentsymbolreuseharmonyletdatastructuresearchregexpStreambytezerogetPrototypeOferrorspeedequalityflagsES8regexdefaultqueueArrayBufferlockfileratea11yES2017fast-deep-copyRxsetmetadatadataViewhasoffsetpureshamsetPrototypeOfnodeserializationframeworksettingsbddpropertiesRegExp#flagscollectionECMAScript 3spinnersObject.valuesArray.prototype.flatcopybatchvalidationfastUint8ClampedArraytrimEndfind-upUint8Arraysyntaxerrorserializerscheme-validationcompareisbufferreact posemrunegativebyteOffsetvisualIteratortermlesschannel3dString.prototype.matchAlldropBigUint64Arraymoduleconcurrencyextenderror-handlingjson-schema-validationboundInt32Arrayprivateeast-asian-widthtestcall-bounddescriptioneventses7fsrgbObject.entriesES5eslinttostringtagdiffes2017mixinsWeakSetutilitiesansiidless mixinstsdeterministicjsonwhatwg256dayjscss-in-jscurlxssInt16ArrayassertstapeesspawnpromisestrimLeftsuperstructmomentoperating-systemes-shimsrequestless compileres-abstractreal-timecolumnObject.keysrapidavaflatMappositivebusysignalsfindcallhigher-orderdeepclonehooksmkdirconcatMapuser-streamsminimalcontainsRFC-6455tc39jQuerycharacterArray.prototype.filterdeletewhichgetoptargvfromredux-toolkitreadablestreamECMAScript 5ECMAScript 2018breakwarninghelpersurlprettymochalruexecform-validationECMAScript 2019internal slotthreehandlersvariablesoptionl10nBigInt64Arraylastvaluesregular expressionstypedarraysfast-deep-cloneassertcircularauthenticationhttpcliutil.inspectwebRegExp.prototype.flagspoint-freeiteratorimportxhrperformantlaunchcomputed-typesdeepES2018asyncapollostablestarterArray.prototype.containsexitreact-hooksfpbootstrap cssfindLastStyleSheetoptimizernodejsfilterArray.prototype.findLastIndexjssideInt8ArrayclientdomreactqueueMicrotasksameValueZeropushelectrongraphqlhashnegative zerogenericssetterfunctionalprotobufargumentsnpmconstterminalcolorsreact-testing-libraryFloat32Arraycallbackquerycsspackage managercommanderjesttelephonemulti-packagecharactersprogressestreefunctionsWebSocketcloneunicodeindicatorECMAScript 2021configcolorSymbol.toStringTagbindthrottletypeerrorpromiselibphonenumberefficientprototypetyped
1.0.2

13 days ago

1.0.3

12 days ago

1.0.1

14 days ago

1.0.0

15 days ago