GithubHelp home page GithubHelp logo

ortense / functors Goto Github PK

View Code? Open in Web Editor NEW
2.0 2.0 1.0 1.33 MB

A collection of dependency-free functors written in TypeScript, created to be type-safe, immutable, and lightweight.

Home Page: https://ortense.github.io/functors/

License: MIT License

TypeScript 99.40% JavaScript 0.60%
either either-monad fp functional functional-programming functors history-management lazy lazy-evaluation maybe

functors's Introduction

Functors banner - the functors mascot generated by dall-e 2

@ortense/functors

install size Coverage Status

A collection of dependency-free functors written in TypeScript, created to be type-safe, immutable, and lightweight.

What is a Functor?

In functional programming, a functor is a concept that represents a type with the ability to be mapped over. This means that you can apply a function to the values inside the type, without altering the structure of the type itself. Functors provide a powerful abstraction for building composable and reusable code, promoting a declarative and functional style of programming.

functor chart - made in excalidraw.com

Overview

This project is a TypeScript library that embraces the functor concept, offering implementations of common functors. These functors provide useful abstractions for various scenarios in your application, allowing you to write more expressive and maintainable code.

Install

Pick your favorite package manager.

npm install @ortense/functors  # npm
yarn add  @ortense/functors    # yarn
pnpm add @ortense/functors     # pnpm
bun add @ortense/functors      # bun
deno add @ortense/functors     # deno from jsr.io

Implemented Functors

For detailed documentation, please refer to the official documentation.

Lazy

Represents a lazy-evaluated value, allowing computations to be deferred until needed.

import { lazy } from '@ortense/functors'

const double = (value: number) => {
  console.log('Doubling...')
  return value * 2
}
const lazyDouble = lazy(() => 7)
  .map(double)
  .map(double)

const result = lazyDouble.evaluate()
console.log(result)
// Output:
// Doubling...
// Doubling...
// 42

History

Represents a history of values, enabling operations like mapping, resetting, and rolling back to previous states.

import { history } from '@ortense/functors'

const userHistory = history({ name: 'Jane Doe' })
  .map(user => ({ ...user, id: 1 }))
  .map(({ id }) => ({ id, name: 'Jonh Due' }))

console.log(userHistory.current()) // { id: 1, name: 'Jonh Due' }
console.log(userHistory.rollback().current()) // { id: 1, name: 'Jane Doe' }
console.log(userHistory.reset().current()) // {  name: 'Jane Doe' }

Either

Represents a type that can be either of type L or R, providing a mechanism for branching based on success or failure.

import { Either, left, right } from '@ortense/functors'

const divide = (
  numerator: number,
  denominator: number,
): Either<Error, number> => {
  if (Number.isNaN(numerator)) {
    return left(new Error('Numerator is not a number.'))
  }
  if (Number.isNaN(denominator)) {
    return left(new Error('Denominator is not a number.'))
  }

  if (denominator === 0) {
    return left(new Error('Division by zero is not posible.'))
  }

  return right(numerator / denominator)
}

const numerator = Number(document.querySelector('input#numerator').value)
const denominator = Number(document.querySelector('input#denominator').value)
const display = document.querySelector('div#display-result')

divide(numerator, denominator)
  .right(result => {
    display.textContent = `${numerator} / ${denominator} = ${result}`
  })
  .left(error => {
    display.textContent = error.message
  })

Maybe

Represents a type that may contain a value or be empty, helping to handle null or undefined values.

import { Maybe, maybe } from '@ortense/functors'

type User = { id: string; name: string }

const findUserById = async (id: string): Maybe<User> => {
  const user = await db.users.findByID(id) // suppose that return user or null
  return maybe<User>(user)
};

const userName = findUserById('123')
  .map(user => user.name) // Maybe<string>
  .mapEmpty(() => 'Default Name')
  .unwrap()

console.log(userName) // Output: Default Name (if user not found)

Contribution

Contributions are welcome! Feel free to open issues, submit pull requests, or provide feedback to help improve this library.

License

This library is licensed under the MIT License - see the LICENSE file for details.

functors's People

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

tassiorego

functors's Issues

Result Functor

new feature

A functor to represent an operation that could be a Success or Failure, like an specialization of the the Either Functor to handle errors.

Something close to:

Interface Result<E extends Error, T> {
  success<R>(fn: (value: T) => R): Result<E, R>
  failure<R extends Error = E, V = R>(fn: (error: E) => Result<R, V>): Result<R, V>
  isSuccess(): boolean
  isFailure(): boolean
  unwrap(): E | T
}

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.