Skip to content

Latest commit

 

History

History

README.md

W5S Core modules (@w5s/core)

NPM Version License

Installation

npm install @w5s/core

Usage

Enforce STD to write better code

VanillaJS STD Explanation
null, undefined Option Stop spending time choosing between undefined and null. Based on Microsoft standard, undefined (== Option.None) is preferred.
throw new Error() return Result.Error(new Error()) Error throwing / Promise rejection is a mechanism that should only be used to stop the execution of a program. When a computation represents an expected failure (ex: parsing, data fetching), Result should be used.
Promise Task Task is like a Promise but lazily evaluated. It has numerous advantages (composable, etc). See Article
N/A Time, Duration Tagged types that makes the unit of time explicit (milliseconds). Some libraries could use seconds or minutes implicitly which is confusing
setTimeout(fn, ms) Task.andThen(Time.delay(ms), fn) setTimeout is impure, create a task that will run after Time.delay.
Date.now Time.now Date.now is impure, use Time.now that is a Task.
console.debug Console.debug console.debug is impure, use Console.debug that is a Task.
Math.random randomNumber Math.random is impure, use randomNumber that is a Task.
UUID, ... Task More impure function, wrap them in a Task()
N/A Int A tagged type that narrows number to only the safe integer values
[].map, [].filter, ... Array.map, Array.filter, ... Array module contains all immutable operations on arrays.

Example

import { Result } from '@w5s/core';

function parseNumber(expr: string) {
  const parsed = Number(expr);

  // - Return a immutable Result object
  // - Avoid throwing error because impure
  // - Avoid using NaN because the error case is implicit in the typing
  return Number.isNaN(parsed) ? Result.Ok(parsed) : Result.Error('NotANumber');
}

export function main() {
  const parsed = parseNumber('1.1'); // Result.Ok(1.1)
  return Result.map(parsed, (amount) => amount + 2); // Result.Ok(3.1)
}

// runTask is impure and should be put at the edge of the program
void main(); // prints { _: 'Result/Ok', value: 3.1 }

License

MIT © Julien Polo julien.polo@gmail.com