0.8.54 • Published 4 months ago

functype v0.8.54

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Functype

NPM Version Node.js Build

A Functional Programming Library for TypeScript

Functype is a lightweight functional programming library for TypeScript, drawing inspiration from functional programming paradigms, the Scala Standard Library, and ZIO. It provides a comprehensive set of utilities and abstractions designed to facilitate functional programming within TypeScript applications.

Core Principles

  • Immutability: All data structures are immutable, promoting predictable and side-effect-free code
  • Type Safety: Leverages TypeScript's type system to ensure compile-time safety
  • Composability: Provides abstractions for building complex programs from simple components
  • Functional Paradigms: Embraces concepts like monads, functors, and type classes

Key Features

  • Option Type: Handle nullable values with Some and None types
  • Either Type: Express computation results with potential failures using Left and Right
  • List, Set, Map: Immutable collection types with functional operators
  • Try Type: Safely execute operations that might throw exceptions
  • Task: Handle synchronous and asynchronous operations with error handling
  • Tuple: Type-safe fixed-length arrays
  • Typeable: Runtime type identification with compile-time safety

Installation

# NPM
npm install functype

# Yarn
yarn add functype

# PNPM
pnpm add functype

# Bun
bun add functype

Usage Examples

Option

import { Option, Some, None } from "functype"

// Create options
const value = Option("hello") // Some("hello")
const empty = Option(null) // None
const explicit = Some(42) // Some(42)

// Transform values
const length = value.map((s) => s.length) // Some(5)
const nothing = empty.map((s) => s.length) // None

// Handle default values
const result = value.getOrElse("world") // "hello"
const fallback = empty.getOrElse("world") // "world"

// Conditionally filter
const filtered = value.filter((s) => s.length > 10) // None

Either

import { Either, Right, Left } from "functype"

// Success case
const success = Right<string, number>(42)
// Error case
const failure = Left<string, number>("error")

// Transform values (map only applies to Right)
const doubled = success.map((x) => x * 2) // Right(84)
const stillError = failure.map((x) => x * 2) // Left("error")

// Handle errors
const value = success.getOrElse(0) // 42
const fallback = failure.getOrElse(0) // 0

// Pattern matching with fold
const result = success.fold(
  (err) => `Error: ${err}`,
  (val) => `Success: ${val}`,
) // "Success: 42"

List

import { List } from "functype"

const numbers = List([1, 2, 3, 4])

// Transform
const doubled = numbers.map((x) => x * 2) // List([2, 4, 6, 8])

// Filter
const evens = numbers.filter((x) => x % 2 === 0) // List([2, 4])

// Reduce
const sum = numbers.foldLeft(0)((acc, x) => acc + x) // 10

// Add/remove elements (immutably)
const withFive = numbers.add(5) // List([1, 2, 3, 4, 5])
const without3 = numbers.remove(3) // List([1, 2, 4])

Try

import { Try } from "functype"

// Safely execute code that might throw
const result = Try(() => {
  // Potentially throwing operation
  return JSON.parse('{"name": "John"}')
})

// Handle success/failure
if (result.isSuccess()) {
  console.log("Result:", result.get())
} else {
  console.error("Error:", result.error)
}

// Transform with map (only applies on Success)
const name = result.map((obj) => obj.name)

// Convert to Either
const either = result.toEither()

Task

import { Task } from "functype"

// Synchronous operations with error handling
const syncResult = Task().Task(
  () => "success",
  (error) => new Error(`Failed: ${error}`),
)

// Asynchronous operations
const asyncTask = async () => {
  const result = await Task().Async(
    async () => await fetchData(),
    async (error) => new Error(`Fetch failed: ${error}`),
  )
  return result
}

Type Safety

Functype leverages TypeScript's advanced type system to provide compile-time safety for functional patterns, ensuring that your code is both robust and maintainable.

// Type inference works seamlessly
const option = Option(42)
// Inferred as number
const mappedValue = option.map((x) => x.toString())
// Inferred as string

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License

Copyright (c) 2025 Jordan Burke

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

0.8.54

4 months ago

0.8.52

4 months ago

0.8.51

4 months ago

0.8.53

4 months ago

0.8.50

5 months ago

0.8.49

7 months ago

0.8.48

7 months ago

0.8.45

7 months ago

0.8.47

7 months ago

0.8.46

7 months ago

0.8.44

7 months ago

0.8.41

7 months ago

0.8.40

7 months ago

0.8.43

7 months ago

0.8.42

7 months ago

0.8.38

7 months ago

0.8.37

7 months ago

0.8.39

7 months ago

0.8.36

8 months ago

0.8.34

8 months ago

0.8.35

8 months ago

0.8.33

8 months ago

0.8.32

9 months ago

0.8.31

9 months ago

0.8.23

9 months ago

0.8.9

9 months ago

0.8.22

9 months ago

0.8.8

9 months ago

0.8.25

9 months ago

0.8.24

9 months ago

0.8.5

10 months ago

0.8.4

10 months ago

0.8.21

9 months ago

0.8.7

10 months ago

0.8.20

9 months ago

0.8.6

10 months ago

0.8.27

9 months ago

0.8.26

9 months ago

0.8.29

9 months ago

0.8.28

9 months ago

0.8.12

9 months ago

0.8.11

9 months ago

0.8.13

9 months ago

0.8.30

9 months ago

0.8.10

9 months ago

0.8.19

9 months ago

0.8.16

9 months ago

0.8.15

9 months ago

0.8.17

9 months ago

0.8.1

10 months ago

0.8.0

10 months ago

0.8.3

10 months ago

0.8.2

10 months ago

0.4.1

11 months ago

0.4.2

11 months ago

0.4.0

1 year ago

0.2.1

2 years ago

0.2.0

2 years ago

0.1.1

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago