functype 0.8.63 → 0.8.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -20
- package/README.md +277 -277
- package/dist/branded/index.mjs +1 -1
- package/dist/{chunk-TQJDL6YW.mjs → chunk-42EDYQ3O.mjs} +2 -2
- package/dist/chunk-42EDYQ3O.mjs.map +1 -0
- package/dist/{chunk-PXFJPCM7.mjs → chunk-DWRQQO3M.mjs} +2 -2
- package/dist/chunk-DWRQQO3M.mjs.map +1 -0
- package/dist/chunk-SNAYIJNJ.mjs +2 -0
- package/dist/chunk-SNAYIJNJ.mjs.map +1 -0
- package/dist/either/index.mjs +1 -1
- package/dist/fpromise/index.mjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/list/index.mjs +1 -1
- package/dist/map/index.mjs +1 -1
- package/dist/option/index.mjs +1 -1
- package/dist/set/index.mjs +1 -1
- package/dist/try/index.mjs +1 -1
- package/dist/tuple/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-3DIRMZSK.mjs +0 -2
- package/dist/chunk-3DIRMZSK.mjs.map +0 -1
- package/dist/chunk-PXFJPCM7.mjs.map +0 -1
- package/dist/chunk-TQJDL6YW.mjs.map +0 -1
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2025 Jordan Burke
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Jordan Burke
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,277 +1,277 @@
|
|
|
1
|
-
# Functype
|
|
2
|
-
|
|
3
|
-

|
|
4
|
-
[](https://github.com/jordanburke/functype/actions/workflows/pnpm-build.yml)
|
|
5
|
-
|
|
6
|
-
## A Functional Programming Library for TypeScript
|
|
7
|
-
|
|
8
|
-
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.
|
|
9
|
-
|
|
10
|
-
[API Documentation](https://jordanburke.github.io/functype/)
|
|
11
|
-
|
|
12
|
-
## Core Principles
|
|
13
|
-
|
|
14
|
-
- **Immutability**: All data structures are immutable, promoting predictable and side-effect-free code
|
|
15
|
-
- **Type Safety**: Leverages TypeScript's type system to ensure compile-time safety
|
|
16
|
-
- **Composability**: Provides abstractions for building complex programs from simple components
|
|
17
|
-
- **Functional Paradigms**: Embraces concepts like monads, functors, and type classes
|
|
18
|
-
|
|
19
|
-
## Key Features
|
|
20
|
-
|
|
21
|
-
- **Option Type**: Handle nullable values with `Some` and `None` types
|
|
22
|
-
- **Either Type**: Express computation results with potential failures using `Left` and `Right`
|
|
23
|
-
- **List, Set, Map**: Immutable collection types with functional operators
|
|
24
|
-
- **Try Type**: Safely execute operations that might throw exceptions
|
|
25
|
-
- **Task**: Handle synchronous and asynchronous operations with error handling
|
|
26
|
-
- **Tuple**: Type-safe fixed-length arrays
|
|
27
|
-
- **Typeable**: Runtime type identification with compile-time safety
|
|
28
|
-
|
|
29
|
-
## Roadmap / TODO
|
|
30
|
-
|
|
31
|
-
### Missing Functionality
|
|
32
|
-
|
|
33
|
-
- [ ] Add lazy evaluation structures (LazyList/Stream)
|
|
34
|
-
- [ ] Implement Validation type for applicative validation
|
|
35
|
-
- [ ] Add Reader/State/IO monads for more functional patterns
|
|
36
|
-
- [ ] Implement lens/optics for immutable updates
|
|
37
|
-
- [ ] Expand concurrent execution utilities beyond FPromise.all
|
|
38
|
-
|
|
39
|
-
### Performance Optimizations
|
|
40
|
-
|
|
41
|
-
- [ ] Add memoization utilities
|
|
42
|
-
- [ ] Improve recursive operations for large collections
|
|
43
|
-
- [ ] Implement immutable data structures with structural sharing
|
|
44
|
-
- [ ] Add performance benchmarks
|
|
45
|
-
- [x] Optimize TreeShaking with sideEffects flag in package.json
|
|
46
|
-
- [x] Support selective module imports for smaller bundles
|
|
47
|
-
- [x] Add bundle size monitoring to CI/CD
|
|
48
|
-
|
|
49
|
-
### API Consistency
|
|
50
|
-
|
|
51
|
-
- [ ] Ensure all modules follow the Scala-inspired pattern:
|
|
52
|
-
- Constructor functions that return objects with methods
|
|
53
|
-
- Object methods for common operations
|
|
54
|
-
- Companion functions for additional utilities
|
|
55
|
-
- [x] Align Task API with other monadic structures
|
|
56
|
-
- [ ] Standardize import patterns (@ imports vs relative paths)
|
|
57
|
-
- [x] Implement consistent error handling strategy for async operations
|
|
58
|
-
|
|
59
|
-
### Testing and Documentation
|
|
60
|
-
|
|
61
|
-
- [ ] Add observable test coverage metrics
|
|
62
|
-
- [x] Implement property-based testing
|
|
63
|
-
- [ ] Expand error handling tests
|
|
64
|
-
- [ ] Add interoperability tests with other libraries
|
|
65
|
-
|
|
66
|
-
### TypeScript Improvements
|
|
67
|
-
|
|
68
|
-
- [x] Enable stricter TypeScript settings (noImplicitAny: true)
|
|
69
|
-
- [x] Add noUncheckedIndexedAccess for safer array indexing
|
|
70
|
-
- [ ] Improve support for higher-kinded types:
|
|
71
|
-
- Current type parameters work well for first-order types
|
|
72
|
-
- Expand to support type constructors as parameters (F<A> => F<B>)
|
|
73
|
-
- [ ] Add branded/nominal types for stronger type safety
|
|
74
|
-
- [ ] Implement more type-level utilities (conditional types, template literals)
|
|
75
|
-
- [ ] Leverage newer TypeScript features (const type parameters, tuple manipulation)
|
|
76
|
-
|
|
77
|
-
## Installation
|
|
78
|
-
|
|
79
|
-
```bash
|
|
80
|
-
# NPM
|
|
81
|
-
npm install functype
|
|
82
|
-
|
|
83
|
-
# Yarn
|
|
84
|
-
yarn add functype
|
|
85
|
-
|
|
86
|
-
# PNPM
|
|
87
|
-
pnpm add functype
|
|
88
|
-
|
|
89
|
-
# Bun
|
|
90
|
-
bun add functype
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
### Bundle Size Optimization
|
|
94
|
-
|
|
95
|
-
Functype is optimized for tree-shaking and offers multiple import strategies to minimize bundle size:
|
|
96
|
-
|
|
97
|
-
```typescript
|
|
98
|
-
// Selective module imports (recommended for production)
|
|
99
|
-
import { Option } from "functype/option"
|
|
100
|
-
import { Either } from "functype/either"
|
|
101
|
-
|
|
102
|
-
// Direct constructor imports (smallest bundle)
|
|
103
|
-
import { some, none } from "functype/option"
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
For detailed optimization strategies, see the [Bundle Optimization Guide](docs/BUNDLE_OPTIMIZATION.md).
|
|
107
|
-
|
|
108
|
-
## Usage Examples
|
|
109
|
-
|
|
110
|
-
### Option
|
|
111
|
-
|
|
112
|
-
```typescript
|
|
113
|
-
import { Option, Some, None } from "functype"
|
|
114
|
-
|
|
115
|
-
// Create options
|
|
116
|
-
const value = Option("hello") // Some("hello")
|
|
117
|
-
const empty = Option(null) // None
|
|
118
|
-
const explicit = Some(42) // Some(42)
|
|
119
|
-
|
|
120
|
-
// Transform values
|
|
121
|
-
const length = value.map((s) => s.length) // Some(5)
|
|
122
|
-
const nothing = empty.map((s) => s.length) // None
|
|
123
|
-
|
|
124
|
-
// Handle default values
|
|
125
|
-
const result = value.getOrElse("world") // "hello"
|
|
126
|
-
const fallback = empty.getOrElse("world") // "world"
|
|
127
|
-
|
|
128
|
-
// Conditionally filter
|
|
129
|
-
const filtered = value.filter((s) => s.length > 10) // None
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
### Either
|
|
133
|
-
|
|
134
|
-
```typescript
|
|
135
|
-
import { Either, Right, Left } from "functype"
|
|
136
|
-
|
|
137
|
-
// Success case
|
|
138
|
-
const success = Right<string, number>(42)
|
|
139
|
-
// Error case
|
|
140
|
-
const failure = Left<string, number>("error")
|
|
141
|
-
|
|
142
|
-
// Transform values (map only applies to Right)
|
|
143
|
-
const doubled = success.map((x) => x * 2) // Right(84)
|
|
144
|
-
const stillError = failure.map((x) => x * 2) // Left("error")
|
|
145
|
-
|
|
146
|
-
// Handle errors
|
|
147
|
-
const value = success.getOrElse(0) // 42
|
|
148
|
-
const fallback = failure.getOrElse(0) // 0
|
|
149
|
-
|
|
150
|
-
// Pattern matching with fold
|
|
151
|
-
const result = success.fold(
|
|
152
|
-
(err) => `Error: ${err}`,
|
|
153
|
-
(val) => `Success: ${val}`,
|
|
154
|
-
) // "Success: 42"
|
|
155
|
-
```
|
|
156
|
-
|
|
157
|
-
### List
|
|
158
|
-
|
|
159
|
-
```typescript
|
|
160
|
-
import { List } from "functype"
|
|
161
|
-
|
|
162
|
-
const numbers = List([1, 2, 3, 4])
|
|
163
|
-
|
|
164
|
-
// Transform
|
|
165
|
-
const doubled = numbers.map((x) => x * 2) // List([2, 4, 6, 8])
|
|
166
|
-
|
|
167
|
-
// Filter
|
|
168
|
-
const evens = numbers.filter((x) => x % 2 === 0) // List([2, 4])
|
|
169
|
-
|
|
170
|
-
// Reduce
|
|
171
|
-
const sum = numbers.foldLeft(0)((acc, x) => acc + x) // 10
|
|
172
|
-
|
|
173
|
-
// Add/remove elements (immutably)
|
|
174
|
-
const withFive = numbers.add(5) // List([1, 2, 3, 4, 5])
|
|
175
|
-
const without3 = numbers.remove(3) // List([1, 2, 4])
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
### Try
|
|
179
|
-
|
|
180
|
-
```typescript
|
|
181
|
-
import { Try } from "functype"
|
|
182
|
-
|
|
183
|
-
// Safely execute code that might throw
|
|
184
|
-
const result = Try(() => {
|
|
185
|
-
// Potentially throwing operation
|
|
186
|
-
return JSON.parse('{"name": "John"}')
|
|
187
|
-
})
|
|
188
|
-
|
|
189
|
-
// Handle success/failure
|
|
190
|
-
if (result.isSuccess()) {
|
|
191
|
-
console.log("Result:", result.get())
|
|
192
|
-
} else {
|
|
193
|
-
console.error("Error:", result.error)
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Transform with map (only applies on Success)
|
|
197
|
-
const name = result.map((obj) => obj.name)
|
|
198
|
-
|
|
199
|
-
// Convert to Either
|
|
200
|
-
const either = result.toEither()
|
|
201
|
-
```
|
|
202
|
-
|
|
203
|
-
### Task
|
|
204
|
-
|
|
205
|
-
```typescript
|
|
206
|
-
import { Task } from "functype"
|
|
207
|
-
|
|
208
|
-
// Synchronous operations with error handling
|
|
209
|
-
const syncResult = Task().Sync(
|
|
210
|
-
() => "success",
|
|
211
|
-
(error) => new Error(`Failed: ${error}`),
|
|
212
|
-
)
|
|
213
|
-
|
|
214
|
-
// Asynchronous operations
|
|
215
|
-
const asyncTask = async () => {
|
|
216
|
-
const result = await Task().Async(
|
|
217
|
-
async () => await fetchData(),
|
|
218
|
-
async (error) => new Error(`Fetch failed: ${error}`),
|
|
219
|
-
)
|
|
220
|
-
return result
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Converting promise-based functions to Task
|
|
224
|
-
const fetchUserAPI = (userId: string): Promise<User> => fetch(`/api/users/${userId}`).then((r) => r.json())
|
|
225
|
-
|
|
226
|
-
// Use the adapter pattern for seamless integration
|
|
227
|
-
const fetchUser = Task({ name: "UserFetch" }).fromPromise(fetchUserAPI)
|
|
228
|
-
|
|
229
|
-
// Later use it with standard promise patterns
|
|
230
|
-
fetchUser("user123")
|
|
231
|
-
.then((user) => console.log(user))
|
|
232
|
-
.catch((error) => console.error(error))
|
|
233
|
-
|
|
234
|
-
// Or convert Task results back to promises
|
|
235
|
-
const taskResult = Task().Sync(() => "hello world")
|
|
236
|
-
const promise = Task().toPromise(taskResult) // Promise<string>
|
|
237
|
-
```
|
|
238
|
-
|
|
239
|
-
## Type Safety
|
|
240
|
-
|
|
241
|
-
Functype leverages TypeScript's advanced type system to provide compile-time safety for functional patterns, ensuring that your code is both robust and maintainable.
|
|
242
|
-
|
|
243
|
-
```typescript
|
|
244
|
-
// Type inference works seamlessly
|
|
245
|
-
const option = Option(42)
|
|
246
|
-
// Inferred as number
|
|
247
|
-
const mappedValue = option.map((x) => x.toString())
|
|
248
|
-
// Inferred as string
|
|
249
|
-
```
|
|
250
|
-
|
|
251
|
-
## Contributing
|
|
252
|
-
|
|
253
|
-
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
254
|
-
|
|
255
|
-
## License
|
|
256
|
-
|
|
257
|
-
MIT License
|
|
258
|
-
|
|
259
|
-
Copyright (c) 2025 Jordan Burke
|
|
260
|
-
|
|
261
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
262
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
263
|
-
in the Software without restriction, including without limitation the rights
|
|
264
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
265
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
266
|
-
furnished to do so, subject to the following conditions:
|
|
267
|
-
|
|
268
|
-
The above copyright notice and this permission notice shall be included in all
|
|
269
|
-
copies or substantial portions of the Software.
|
|
270
|
-
|
|
271
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
272
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
273
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
274
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
275
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
276
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
277
|
-
SOFTWARE.
|
|
1
|
+
# Functype
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
[](https://github.com/jordanburke/functype/actions/workflows/pnpm-build.yml)
|
|
5
|
+
|
|
6
|
+
## A Functional Programming Library for TypeScript
|
|
7
|
+
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+
[API Documentation](https://jordanburke.github.io/functype/)
|
|
11
|
+
|
|
12
|
+
## Core Principles
|
|
13
|
+
|
|
14
|
+
- **Immutability**: All data structures are immutable, promoting predictable and side-effect-free code
|
|
15
|
+
- **Type Safety**: Leverages TypeScript's type system to ensure compile-time safety
|
|
16
|
+
- **Composability**: Provides abstractions for building complex programs from simple components
|
|
17
|
+
- **Functional Paradigms**: Embraces concepts like monads, functors, and type classes
|
|
18
|
+
|
|
19
|
+
## Key Features
|
|
20
|
+
|
|
21
|
+
- **Option Type**: Handle nullable values with `Some` and `None` types
|
|
22
|
+
- **Either Type**: Express computation results with potential failures using `Left` and `Right`
|
|
23
|
+
- **List, Set, Map**: Immutable collection types with functional operators
|
|
24
|
+
- **Try Type**: Safely execute operations that might throw exceptions
|
|
25
|
+
- **Task**: Handle synchronous and asynchronous operations with error handling
|
|
26
|
+
- **Tuple**: Type-safe fixed-length arrays
|
|
27
|
+
- **Typeable**: Runtime type identification with compile-time safety
|
|
28
|
+
|
|
29
|
+
## Roadmap / TODO
|
|
30
|
+
|
|
31
|
+
### Missing Functionality
|
|
32
|
+
|
|
33
|
+
- [ ] Add lazy evaluation structures (LazyList/Stream)
|
|
34
|
+
- [ ] Implement Validation type for applicative validation
|
|
35
|
+
- [ ] Add Reader/State/IO monads for more functional patterns
|
|
36
|
+
- [ ] Implement lens/optics for immutable updates
|
|
37
|
+
- [ ] Expand concurrent execution utilities beyond FPromise.all
|
|
38
|
+
|
|
39
|
+
### Performance Optimizations
|
|
40
|
+
|
|
41
|
+
- [ ] Add memoization utilities
|
|
42
|
+
- [ ] Improve recursive operations for large collections
|
|
43
|
+
- [ ] Implement immutable data structures with structural sharing
|
|
44
|
+
- [ ] Add performance benchmarks
|
|
45
|
+
- [x] Optimize TreeShaking with sideEffects flag in package.json
|
|
46
|
+
- [x] Support selective module imports for smaller bundles
|
|
47
|
+
- [x] Add bundle size monitoring to CI/CD
|
|
48
|
+
|
|
49
|
+
### API Consistency
|
|
50
|
+
|
|
51
|
+
- [ ] Ensure all modules follow the Scala-inspired pattern:
|
|
52
|
+
- Constructor functions that return objects with methods
|
|
53
|
+
- Object methods for common operations
|
|
54
|
+
- Companion functions for additional utilities
|
|
55
|
+
- [x] Align Task API with other monadic structures
|
|
56
|
+
- [ ] Standardize import patterns (@ imports vs relative paths)
|
|
57
|
+
- [x] Implement consistent error handling strategy for async operations
|
|
58
|
+
|
|
59
|
+
### Testing and Documentation
|
|
60
|
+
|
|
61
|
+
- [ ] Add observable test coverage metrics
|
|
62
|
+
- [x] Implement property-based testing
|
|
63
|
+
- [ ] Expand error handling tests
|
|
64
|
+
- [ ] Add interoperability tests with other libraries
|
|
65
|
+
|
|
66
|
+
### TypeScript Improvements
|
|
67
|
+
|
|
68
|
+
- [x] Enable stricter TypeScript settings (noImplicitAny: true)
|
|
69
|
+
- [x] Add noUncheckedIndexedAccess for safer array indexing
|
|
70
|
+
- [ ] Improve support for higher-kinded types:
|
|
71
|
+
- Current type parameters work well for first-order types
|
|
72
|
+
- Expand to support type constructors as parameters (F<A> => F<B>)
|
|
73
|
+
- [ ] Add branded/nominal types for stronger type safety
|
|
74
|
+
- [ ] Implement more type-level utilities (conditional types, template literals)
|
|
75
|
+
- [ ] Leverage newer TypeScript features (const type parameters, tuple manipulation)
|
|
76
|
+
|
|
77
|
+
## Installation
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
# NPM
|
|
81
|
+
npm install functype
|
|
82
|
+
|
|
83
|
+
# Yarn
|
|
84
|
+
yarn add functype
|
|
85
|
+
|
|
86
|
+
# PNPM
|
|
87
|
+
pnpm add functype
|
|
88
|
+
|
|
89
|
+
# Bun
|
|
90
|
+
bun add functype
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Bundle Size Optimization
|
|
94
|
+
|
|
95
|
+
Functype is optimized for tree-shaking and offers multiple import strategies to minimize bundle size:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
// Selective module imports (recommended for production)
|
|
99
|
+
import { Option } from "functype/option"
|
|
100
|
+
import { Either } from "functype/either"
|
|
101
|
+
|
|
102
|
+
// Direct constructor imports (smallest bundle)
|
|
103
|
+
import { some, none } from "functype/option"
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
For detailed optimization strategies, see the [Bundle Optimization Guide](docs/BUNDLE_OPTIMIZATION.md).
|
|
107
|
+
|
|
108
|
+
## Usage Examples
|
|
109
|
+
|
|
110
|
+
### Option
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
import { Option, Some, None } from "functype"
|
|
114
|
+
|
|
115
|
+
// Create options
|
|
116
|
+
const value = Option("hello") // Some("hello")
|
|
117
|
+
const empty = Option(null) // None
|
|
118
|
+
const explicit = Some(42) // Some(42)
|
|
119
|
+
|
|
120
|
+
// Transform values
|
|
121
|
+
const length = value.map((s) => s.length) // Some(5)
|
|
122
|
+
const nothing = empty.map((s) => s.length) // None
|
|
123
|
+
|
|
124
|
+
// Handle default values
|
|
125
|
+
const result = value.getOrElse("world") // "hello"
|
|
126
|
+
const fallback = empty.getOrElse("world") // "world"
|
|
127
|
+
|
|
128
|
+
// Conditionally filter
|
|
129
|
+
const filtered = value.filter((s) => s.length > 10) // None
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Either
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
import { Either, Right, Left } from "functype"
|
|
136
|
+
|
|
137
|
+
// Success case
|
|
138
|
+
const success = Right<string, number>(42)
|
|
139
|
+
// Error case
|
|
140
|
+
const failure = Left<string, number>("error")
|
|
141
|
+
|
|
142
|
+
// Transform values (map only applies to Right)
|
|
143
|
+
const doubled = success.map((x) => x * 2) // Right(84)
|
|
144
|
+
const stillError = failure.map((x) => x * 2) // Left("error")
|
|
145
|
+
|
|
146
|
+
// Handle errors
|
|
147
|
+
const value = success.getOrElse(0) // 42
|
|
148
|
+
const fallback = failure.getOrElse(0) // 0
|
|
149
|
+
|
|
150
|
+
// Pattern matching with fold
|
|
151
|
+
const result = success.fold(
|
|
152
|
+
(err) => `Error: ${err}`,
|
|
153
|
+
(val) => `Success: ${val}`,
|
|
154
|
+
) // "Success: 42"
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### List
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { List } from "functype"
|
|
161
|
+
|
|
162
|
+
const numbers = List([1, 2, 3, 4])
|
|
163
|
+
|
|
164
|
+
// Transform
|
|
165
|
+
const doubled = numbers.map((x) => x * 2) // List([2, 4, 6, 8])
|
|
166
|
+
|
|
167
|
+
// Filter
|
|
168
|
+
const evens = numbers.filter((x) => x % 2 === 0) // List([2, 4])
|
|
169
|
+
|
|
170
|
+
// Reduce
|
|
171
|
+
const sum = numbers.foldLeft(0)((acc, x) => acc + x) // 10
|
|
172
|
+
|
|
173
|
+
// Add/remove elements (immutably)
|
|
174
|
+
const withFive = numbers.add(5) // List([1, 2, 3, 4, 5])
|
|
175
|
+
const without3 = numbers.remove(3) // List([1, 2, 4])
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### Try
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
import { Try } from "functype"
|
|
182
|
+
|
|
183
|
+
// Safely execute code that might throw
|
|
184
|
+
const result = Try(() => {
|
|
185
|
+
// Potentially throwing operation
|
|
186
|
+
return JSON.parse('{"name": "John"}')
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
// Handle success/failure
|
|
190
|
+
if (result.isSuccess()) {
|
|
191
|
+
console.log("Result:", result.get())
|
|
192
|
+
} else {
|
|
193
|
+
console.error("Error:", result.error)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Transform with map (only applies on Success)
|
|
197
|
+
const name = result.map((obj) => obj.name)
|
|
198
|
+
|
|
199
|
+
// Convert to Either
|
|
200
|
+
const either = result.toEither()
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Task
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
import { Task } from "functype"
|
|
207
|
+
|
|
208
|
+
// Synchronous operations with error handling
|
|
209
|
+
const syncResult = Task().Sync(
|
|
210
|
+
() => "success",
|
|
211
|
+
(error) => new Error(`Failed: ${error}`),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
// Asynchronous operations
|
|
215
|
+
const asyncTask = async () => {
|
|
216
|
+
const result = await Task().Async(
|
|
217
|
+
async () => await fetchData(),
|
|
218
|
+
async (error) => new Error(`Fetch failed: ${error}`),
|
|
219
|
+
)
|
|
220
|
+
return result
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Converting promise-based functions to Task
|
|
224
|
+
const fetchUserAPI = (userId: string): Promise<User> => fetch(`/api/users/${userId}`).then((r) => r.json())
|
|
225
|
+
|
|
226
|
+
// Use the adapter pattern for seamless integration
|
|
227
|
+
const fetchUser = Task({ name: "UserFetch" }).fromPromise(fetchUserAPI)
|
|
228
|
+
|
|
229
|
+
// Later use it with standard promise patterns
|
|
230
|
+
fetchUser("user123")
|
|
231
|
+
.then((user) => console.log(user))
|
|
232
|
+
.catch((error) => console.error(error))
|
|
233
|
+
|
|
234
|
+
// Or convert Task results back to promises
|
|
235
|
+
const taskResult = Task().Sync(() => "hello world")
|
|
236
|
+
const promise = Task().toPromise(taskResult) // Promise<string>
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Type Safety
|
|
240
|
+
|
|
241
|
+
Functype leverages TypeScript's advanced type system to provide compile-time safety for functional patterns, ensuring that your code is both robust and maintainable.
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
// Type inference works seamlessly
|
|
245
|
+
const option = Option(42)
|
|
246
|
+
// Inferred as number
|
|
247
|
+
const mappedValue = option.map((x) => x.toString())
|
|
248
|
+
// Inferred as string
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
MIT License
|
|
258
|
+
|
|
259
|
+
Copyright (c) 2025 Jordan Burke
|
|
260
|
+
|
|
261
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
262
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
263
|
+
in the Software without restriction, including without limitation the rights
|
|
264
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
265
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
266
|
+
furnished to do so, subject to the following conditions:
|
|
267
|
+
|
|
268
|
+
The above copyright notice and this permission notice shall be included in all
|
|
269
|
+
copies or substantial portions of the Software.
|
|
270
|
+
|
|
271
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
272
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
273
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
274
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
275
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
276
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
277
|
+
SOFTWARE.
|
package/dist/branded/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as Brand,g as BrandedBoolean,f as BrandedNumber,e as BrandedString,d as createBrander,c as hasBrand,b as unbrand}from'../chunk-
|
|
1
|
+
export{a as Brand,g as BrandedBoolean,f as BrandedNumber,e as BrandedString,d as createBrander,c as hasBrand,b as unbrand}from'../chunk-42EDYQ3O.mjs';//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(n,r){return r}function t(n){return n}function d(n,r){return n!=null}function a(n){return r=>e(n,r)}var o=n=>r=>e(n,r),s=n=>r=>e(n,r),K=n=>r=>e(n,r);export{e as a,t as b,d as c,a as d,o as e,s as f,K as g};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
function e(n,r){return r}function t(n){return n}function d(n,r){return n!=null}function a(n){return r=>e(n,r)}var o=n=>r=>e(n,r),s=n=>r=>e(n,r),K=n=>r=>e(n,r);export{e as a,t as b,d as c,a as d,o as e,s as f,K as g};//# sourceMappingURL=chunk-42EDYQ3O.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-42EDYQ3O.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/branded/Brand.ts"],"names":["Brand","brand","value","unbrand","branded","hasBrand","createBrander","BrandedString","BrandedNumber","BrandedBoolean"],"mappings":"AAoBO,SAASA,CAAAA,CAA2BC,CAAUC,CAAAA,CAAAA,CAAuB,CAC1E,OAAOA,CACT,CAOO,SAASC,CAAWC,CAAAA,CAAAA,CAA8B,CACvD,OAAOA,CACT,CAaO,SAASC,CAA8BH,CAAAA,CAAAA,CAAgBD,CAAgC,CAAA,CAG5F,OAAOC,CAAAA,EAAU,IACnB,CAOO,SAASI,CAAAA,CAAmCL,CAAU,CAAA,CAC3D,OAAQC,CAA0BF,EAAAA,CAAAA,CAAMC,CAAOC,CAAAA,CAAK,CACtD,KAQaK,CACQN,CAAAA,CAAAA,EAClBC,CACCF,EAAAA,CAAAA,CAAMC,CAAOC,CAAAA,CAAK,EAETM,CACQP,CAAAA,CAAAA,EAClBC,CACCF,EAAAA,CAAAA,CAAMC,CAAOC,CAAAA,CAAK,CAETO,CAAAA,CAAAA,CACQR,CAClBC,EAAAA,CAAAA,EACCF,CAAMC,CAAAA,CAAAA,CAAOC,CAAK","file":"chunk-42EDYQ3O.mjs","sourcesContent":["/**\r\n * Brand is a utility for creating nominal typing in TypeScript\r\n * It allows for creating distinct types that are structurally identical\r\n * but considered different by TypeScript's type system\r\n */\r\n\r\n// The brand symbol type\r\nexport type Brand<K extends string, T> = T & { readonly __brand: K }\r\n\r\n// Utility type to extract the underlying type from a branded type\r\nexport type Unbrand<T> = T extends Brand<string, infer U> ? U : never\r\n\r\n// Utility type to extract the brand from a branded type\r\nexport type ExtractBrand<T> = T extends Brand<infer K, unknown> ? K : never\r\n\r\n/**\r\n * Helper to create a branded type\r\n * @param value - The value to brand\r\n * @returns The branded value\r\n */\r\nexport function Brand<K extends string, T>(brand: K, value: T): Brand<K, T> {\r\n return value as Brand<K, T>\r\n}\r\n\r\n/**\r\n * Helper to remove a brand from a value\r\n * @param branded - The branded value\r\n * @returns The original value without the brand\r\n */\r\nexport function unbrand<T>(branded: Brand<string, T>): T {\r\n return branded as T\r\n}\r\n\r\n/**\r\n * Type guard for checking if a value has a specific brand\r\n * @param value - The value to check\r\n * @param brand - The brand to check for\r\n * @returns True if the value has the specified brand\r\n *\r\n * Note: Since brands are phantom types that exist only at compile time,\r\n * this function can only provide a runtime approximation. It always returns true\r\n * for non-null values, as we have no way to actually check the brand at runtime.\r\n * This function is primarily for API consistency and documentation purposes.\r\n */\r\nexport function hasBrand<K extends string, T>(value: unknown, brand: K): value is Brand<K, T> {\r\n // In a phantom type system, we can't actually check the brand at runtime\r\n // We can only verify the value exists\r\n return value !== null && value !== undefined\r\n}\r\n\r\n/**\r\n * Create a branded type constructor for a specific brand\r\n * @param brand - The brand name\r\n * @returns A function that brands values with the specified brand\r\n */\r\nexport function createBrander<K extends string, T>(brand: K) {\r\n return (value: T): Brand<K, T> => Brand(brand, value)\r\n}\r\n\r\n// Common branded primitive types\r\nexport type BrandedString<K extends string> = Brand<K, string>\r\nexport type BrandedNumber<K extends string> = Brand<K, number>\r\nexport type BrandedBoolean<K extends string> = Brand<K, boolean>\r\n\r\n// Factory for common primitive branded types\r\nexport const BrandedString =\r\n <K extends string>(brand: K) =>\r\n (value: string): BrandedString<K> =>\r\n Brand(brand, value)\r\n\r\nexport const BrandedNumber =\r\n <K extends string>(brand: K) =>\r\n (value: number): BrandedNumber<K> =>\r\n Brand(brand, value)\r\n\r\nexport const BrandedBoolean =\r\n <K extends string>(brand: K) =>\r\n (value: boolean): BrandedBoolean<K> =>\r\n Brand(brand, value)\r\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function n({_tag:e,impl:t}){return {...t,_tag:e}}function a(e,t){return !e||typeof e!="object"||!("_tag"in e)?false:t?e._tag===t:true}var T=e=>({_tag:"Tuple",map:t=>{let r=t(e);return T(r)},flatMap:t=>t(e),get:t=>e[t],toArray:()=>e,[Symbol.iterator](){let t=0;return {next:()=>t<e.length?{value:e[t++],done:false}:{value:void 0,done:true}}},toValue:()=>({_tag:"Tuple",value:e})});export{n as a,a as b,T as c};//# sourceMappingURL=chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
function n({_tag:e,impl:t}){return {...t,_tag:e}}function a(e,t){return !e||typeof e!="object"||!("_tag"in e)?false:t?e._tag===t:true}var T=e=>({_tag:"Tuple",map:t=>{let r=t(e);return T(r)},flatMap:t=>t(e),get:t=>e[t],toArray:()=>e,[Symbol.iterator](){let t=0;return {next:()=>t<e.length?{value:e[t++],done:false}:{value:void 0,done:true}}},toValue:()=>({_tag:"Tuple",value:e})});export{n as a,a as b,T as c};//# sourceMappingURL=chunk-DWRQQO3M.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-DWRQQO3M.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/typeable/Typeable.ts","../src/tuple/Tuple.ts"],"names":["Typeable","_tag","impl","isTypeable","value","tag","Tuple","values","f","mapValue","index"],"mappings":"AAWO,SAASA,CAAAA,CAAgC,CAAE,IAAAC,CAAAA,CAAAA,CAAM,KAAAC,CAAK,CAAA,CAA6C,CACxG,OAAO,CACL,GAAGA,EACH,IAAMD,CAAAA,CACR,CACF,CAGO,SAASE,CAAAA,CAAcC,EAAgBC,CAAyB,CAAA,CACrE,OAAI,CAACD,CAAS,EAAA,OAAOA,GAAU,QAAY,EAAA,EAAE,MAAUA,GAAAA,CAAAA,CAAAA,CAC9C,KAGFC,CAAAA,CAAAA,CAAMD,EAAM,IAASC,GAAAA,CAAAA,CAAM,IACpC,CCPaC,IAAAA,CAAAA,CAA2BC,IAC/B,CACL,IAAA,CAAM,OACN,CAAA,GAAA,CAAwBC,CAAiC,EAAA,CACvD,IAAMC,CAAWD,CAAAA,CAAAA,CAAED,CAAM,CAAA,CACzB,OAAOD,CAAAA,CAAMG,CAAQ,CACvB,CAAA,CAEA,OAA4BD,CAAAA,CAAAA,EACnBA,CAAED,CAAAA,CAAM,EAGjB,GAAwBG,CAAAA,CAAAA,EACfH,CAAOG,CAAAA,CAAK,CAGrB,CAAA,OAAA,CAAS,IACAH,CAET,CAAA,CAAC,MAAO,CAAA,QAAQ,CAAyB,EAAA,CACvC,IAAIG,CAAQ,CAAA,CAAA,CACZ,OAAO,CACL,IAAM,CAAA,IACAA,EAAQH,CAAO,CAAA,MAAA,CACV,CACL,KAAA,CAAOA,CAAOG,CAAAA,CAAAA,EAAO,EACrB,IAAM,CAAA,KACR,CAEO,CAAA,CACL,KAAO,CAAA,MAAA,CACP,KAAM,IACR,CAGN,CACF,CAAA,CACA,OAAS,CAAA,KAAO,CAAE,IAAM,CAAA,OAAA,CAAS,KAAOH,CAAAA,CAAO,CACjD,CAAA,CAAA","file":"chunk-DWRQQO3M.mjs","sourcesContent":["// Core type for Typeable objects\r\nexport type Typeable<Tag extends string, T = object> = T & {\r\n readonly _tag: Tag\r\n}\r\n\r\nexport type TypeableParams<Tag extends string, T> = { _tag: Tag; impl: T }\r\n\r\n// Utility type to extract the Tag from a Typeable type\r\nexport type ExtractTag<T> = T extends Typeable<infer Tag, unknown> ? Tag : never\r\n\r\n// Create a tagged object with type inference\r\nexport function Typeable<Tag extends string, T>({ _tag, impl }: TypeableParams<Tag, T>): Typeable<Tag, T> {\r\n return {\r\n ...impl,\r\n _tag: _tag,\r\n }\r\n}\r\n\r\n// Type guard with automatic type inference using the full type\r\nexport function isTypeable<T>(value: unknown, tag: string): value is T {\r\n if (!value || typeof value !== \"object\" || !(\"_tag\" in value)) {\r\n return false\r\n }\r\n\r\n return tag ? value._tag === tag : true\r\n}\r\n\r\n// // Usage\r\n// type User = Typeable<\r\n// \"User\",\r\n// {\r\n// id: string\r\n// name: string\r\n// email: string\r\n// }\r\n// >\r\n//\r\n// const user = Typeable(\"User\", {\r\n// id: \"123\",\r\n// name: \"John\",\r\n// email: \"john@example.com\",\r\n// })\r\n//\r\n// const maybeUser: unknown = user\r\n//\r\n// // Now we only need to specify User type\r\n// if (isTypeable<User>(maybeUser, \"User\")) {\r\n// console.log(maybeUser.name) // typed\r\n// console.log(maybeUser.email) // typed\r\n// console.log(maybeUser._tag) // typed as \"User\"\r\n// }\r\n//\r\n// // Can still check just for Typeable without specific tag\r\n// if (isTypeable<User>(maybeUser)) {\r\n// console.log(maybeUser.name) // typed\r\n// console.log(maybeUser.email) // typed\r\n// console.log(maybeUser._tag) // typed as \"User\"\r\n// }\r\n","import type { ArrayFunctor, Type } from \"@/functor\"\r\nimport { Typeable } from \"@/typeable/Typeable\"\r\nimport { Valuable } from \"@/valuable/Valuable\"\r\n\r\nexport type Tuple<T extends Type[]> = {\r\n get<K extends number>(index: K): T[K]\r\n\r\n map<U extends Type[]>(f: (value: T) => U): Tuple<U>\r\n\r\n flatMap<U extends Type[]>(f: (value: T) => Tuple<U>): Tuple<U>\r\n\r\n toArray(): T\r\n\r\n [Symbol.iterator](): Iterator<T[number]>\r\n} & ArrayFunctor<T> &\r\n Typeable<\"Tuple\"> &\r\n Valuable<\"Tuple\", T>\r\n\r\nexport const Tuple = <T extends Type[]>(values: T): Tuple<T> => {\r\n return {\r\n _tag: \"Tuple\",\r\n map: <U extends Type[]>(f: (value: T) => U): Tuple<U> => {\r\n const mapValue = f(values)\r\n return Tuple(mapValue)\r\n },\r\n\r\n flatMap: <U extends Type[]>(f: (value: T) => Tuple<U>): Tuple<U> => {\r\n return f(values)\r\n },\r\n\r\n get: <K extends number>(index: K): T[K] => {\r\n return values[index]\r\n },\r\n\r\n toArray: (): T => {\r\n return values\r\n },\r\n [Symbol.iterator](): Iterator<T[number]> {\r\n let index = 0\r\n return {\r\n next: (): IteratorResult<T[number]> => {\r\n if (index < values.length) {\r\n return {\r\n value: values[index++],\r\n done: false,\r\n }\r\n } else {\r\n return {\r\n value: undefined,\r\n done: true,\r\n }\r\n }\r\n },\r\n }\r\n },\r\n toValue: () => ({ _tag: \"Tuple\", value: values }),\r\n }\r\n}\r\n"]}
|