functype 0.40.0 → 0.41.2

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.
Files changed (46) hide show
  1. package/dist/Brand-BPeggBaO.d.ts +1 -2
  2. package/dist/Brand-Cfr5zy8F.js +1 -2
  3. package/dist/Tuple-C4maYbiO.d.ts +1 -2
  4. package/dist/Tuple-CgX4p79w.js +1 -2
  5. package/dist/cli/index.js +2 -3
  6. package/dist/do/index.d.ts +1 -3
  7. package/dist/do/index.js +1 -1
  8. package/dist/either/index.d.ts +1 -3
  9. package/dist/either/index.js +1 -1
  10. package/dist/fpromise/index.d.ts +1 -3
  11. package/dist/fpromise/index.js +1 -1
  12. package/dist/{index-Bn_yRBx8.d.ts → index-B6Civ4kr.d.ts} +19 -9
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/list/index.d.ts +1 -3
  16. package/dist/list/index.js +1 -1
  17. package/dist/map/index.d.ts +1 -3
  18. package/dist/map/index.js +1 -1
  19. package/dist/option/index.d.ts +1 -3
  20. package/dist/option/index.js +1 -1
  21. package/dist/set/index.d.ts +1 -3
  22. package/dist/set/index.js +1 -1
  23. package/dist/{src-JcsaR9MX.js → src-DpfaJv6K.js} +2 -3
  24. package/dist/try/index.d.ts +1 -3
  25. package/dist/try/index.js +1 -1
  26. package/package.json +97 -119
  27. package/README.processed.md +0 -862
  28. package/dist/Brand-Cfr5zy8F.js.map +0 -1
  29. package/dist/Tuple-CgX4p79w.js.map +0 -1
  30. package/dist/cli/index.js.map +0 -1
  31. package/dist/src-JcsaR9MX.js.map +0 -1
  32. package/readme/BRAND_MIGRATION_GUIDE.md +0 -230
  33. package/readme/BUNDLE_OPTIMIZATION.md +0 -74
  34. package/readme/FPromise-Assessment.md +0 -43
  35. package/readme/HKT.md +0 -110
  36. package/readme/ROADMAP.md +0 -113
  37. package/readme/TASK-TODO.md +0 -33
  38. package/readme/TUPLE-EXAMPLES.md +0 -76
  39. package/readme/TaskMigration.md +0 -129
  40. package/readme/ai-guide.md +0 -406
  41. package/readme/examples.md +0 -2093
  42. package/readme/functype-changes-required.md +0 -189
  43. package/readme/quick-reference.md +0 -514
  44. package/readme/task-error-handling.md +0 -283
  45. package/readme/tasks.md +0 -203
  46. package/readme/type-index.md +0 -238
@@ -1,230 +0,0 @@
1
- # Brand Type Migration Guide
2
-
3
- This guide helps you migrate from the old object-based Brand implementation to the new phantom type implementation.
4
-
5
- ## What Changed?
6
-
7
- ### Old Implementation (Object Wrappers)
8
-
9
- - Branded values were **objects** with methods
10
- - Required `.unbrand()` or `.unwrap()` to access the primitive value
11
- - `typeof brandedString === "object"`
12
- - Object overhead and indexed properties
13
-
14
- ### New Implementation (Phantom Types)
15
-
16
- - Branded values **ARE** the primitive values
17
- - No unwrapping needed - use directly
18
- - `typeof brandedString === "string"`
19
- - Zero runtime overhead
20
-
21
- ## Migration Steps
22
-
23
- ### 1. Remove `.unbrand()` and `.unwrap()` calls
24
-
25
- **Before:**
26
-
27
- ```typescript
28
- const userId = Brand("UserId", "user-123")
29
- const id = userId.unbrand() // Had to unwrap
30
- console.log(`User: ${userId.unbrand()}`)
31
- ```
32
-
33
- **After:**
34
-
35
- ```typescript
36
- const userId = Brand("UserId", "user-123")
37
- const id = userId // It IS the string!
38
- console.log(`User: ${userId}`)
39
- ```
40
-
41
- ### 2. Remove `.toString()` for custom formatting
42
-
43
- **Before:**
44
-
45
- ```typescript
46
- const userId = Brand("UserId", "user-123")
47
- console.log(userId.toString()) // "UserId(user-123)"
48
- ```
49
-
50
- **After:**
51
-
52
- ```typescript
53
- const userId = Brand("UserId", "user-123")
54
- console.log(userId.toString()) // "user-123" - standard string method
55
- console.log(userId) // "user-123"
56
- ```
57
-
58
- ### 3. Update ValidatedBrand usage
59
-
60
- **Before:**
61
-
62
- ```typescript
63
- const email = EmailAddress.of("user@example.com")
64
- if (!email.isEmpty) {
65
- const branded = email.get()
66
- sendEmail(branded.unbrand()) // Had to unwrap
67
- }
68
- ```
69
-
70
- **After:**
71
-
72
- ```typescript
73
- const email = EmailAddress.of("user@example.com")
74
- if (!email.isEmpty) {
75
- const branded = email.get()
76
- sendEmail(branded) // It IS a string!
77
- }
78
- ```
79
-
80
- ### 4. Update refine validators
81
-
82
- **Before:**
83
-
84
- ```typescript
85
- const SmallPositive = PositiveNumber.refine("SmallPositive", (n) => {
86
- return n.unbrand() < 100 // Had to unwrap
87
- })
88
- ```
89
-
90
- **After:**
91
-
92
- ```typescript
93
- const SmallPositive = PositiveNumber.refine("SmallPositive", (n) => {
94
- return n < 100 // n IS a number!
95
- })
96
- ```
97
-
98
- ### 5. Remove type assertions for external APIs
99
-
100
- **Before:**
101
-
102
- ```typescript
103
- const config = {
104
- userId: userId.unbrand(),
105
- port: port.unbrand(),
106
- }
107
- await api.request(config)
108
- ```
109
-
110
- **After:**
111
-
112
- ```typescript
113
- const config = {
114
- userId, // Already a string!
115
- port, // Already a number!
116
- }
117
- await api.request(config)
118
- ```
119
-
120
- ## Common Patterns
121
-
122
- ### Working with Option/Either
123
-
124
- When extracting branded values from Option or Either, you may need to adjust default values:
125
-
126
- **Before:**
127
-
128
- ```typescript
129
- const email = EmailAddress.of(input)
130
- const value = email.map((e) => e.unbrand()).orElse("")
131
- ```
132
-
133
- **After (Option 1 - Keep branded type):**
134
-
135
- ```typescript
136
- const email = EmailAddress.of(input)
137
- const value = email.orElse("" as Brand<"EmailAddress", string>)
138
- ```
139
-
140
- **After (Option 2 - Use fold for clean extraction):**
141
-
142
- ```typescript
143
- const email = EmailAddress.of(input)
144
- const value = email.fold(
145
- () => "", // Default value
146
- (e) => e, // e IS already a string!
147
- )
148
- ```
149
-
150
- ### Type-safe functions
151
-
152
- Function signatures don't change, but implementation is cleaner:
153
-
154
- **Before:**
155
-
156
- ```typescript
157
- function processUser(userId: Brand<"UserId", string>) {
158
- const id = userId.unbrand()
159
- return db.query(`SELECT * FROM users WHERE id = '${id}'`)
160
- }
161
- ```
162
-
163
- **After:**
164
-
165
- ```typescript
166
- function processUser(userId: Brand<"UserId", string>) {
167
- return db.query(`SELECT * FROM users WHERE id = '${userId}'`)
168
- }
169
- ```
170
-
171
- ## Benefits After Migration
172
-
173
- 1. **Better Performance**: No object allocation overhead
174
- 2. **Cleaner Code**: No more `.unbrand()` calls everywhere
175
- 3. **Natural JavaScript**: String interpolation, JSON serialization work directly
176
- 4. **Smaller Bundles**: Less code to ship
177
- 5. **Better Debugging**: Values show as primitives in debugger
178
-
179
- ## Compatibility
180
-
181
- ### If you need the old behavior
182
-
183
- The `unbrand` utility function still exists for compatibility:
184
-
185
- ```typescript
186
- import { unbrand } from "@/branded"
187
-
188
- const userId = Brand("UserId", "user-123")
189
- const plain = unbrand(userId) // Works but unnecessary
190
- ```
191
-
192
- ValidatedBrand also provides an `unwrap` method:
193
-
194
- ```typescript
195
- const email = EmailAddress.unsafeOf("user@example.com")
196
- const plain = EmailAddress.unwrap(email) // Works but unnecessary
197
- ```
198
-
199
- ## Quick Reference
200
-
201
- | Old Code | New Code |
202
- | ------------------------------------ | --------------------------- |
203
- | `value.unbrand()` | `value` |
204
- | `value.unwrap()` | `value` |
205
- | `value.toString()` | `value` or `String(value)` |
206
- | `typeof value === "object"` | `typeof value === "string"` |
207
- | `${value.unbrand()}` | `${value}` |
208
- | `JSON.stringify({id: id.unbrand()})` | `JSON.stringify({id})` |
209
-
210
- ## Testing
211
-
212
- Update your tests to expect primitives:
213
-
214
- **Before:**
215
-
216
- ```typescript
217
- expect(typeof userId).toBe("object")
218
- expect(userId.unbrand()).toBe("user-123")
219
- ```
220
-
221
- **After:**
222
-
223
- ```typescript
224
- expect(typeof userId).toBe("string")
225
- expect(userId).toBe("user-123")
226
- ```
227
-
228
- ## Summary
229
-
230
- The migration is mostly about **removing code**. Branded values now work exactly like their underlying primitive types, making the code cleaner and more performant. The type safety remains unchanged - you still get full compile-time protection against mixing different branded types.
@@ -1,74 +0,0 @@
1
- # Bundle Size Optimization Guide
2
-
3
- ## Overview
4
-
5
- Functype is designed with tree-shaking in mind, allowing you to optimize your application's bundle size by only including the specific modules you need.
6
-
7
- ## Import Strategies
8
-
9
- ### Strategy 1: Selective Module Imports (Recommended)
10
-
11
- Import only the specific modules you need to reduce bundle size significantly.
12
-
13
- ```typescript
14
- import { Option } from "functype/option"
15
- import { Either } from "functype/either"
16
-
17
- // Usage
18
- const option = Option.some(42)
19
- const either = Either.right("value")
20
- ```
21
-
22
- ### Strategy 2: Direct Constructor Imports (Smallest Bundle)
23
-
24
- For the most aggressive tree-shaking, import only the specific constructors and functions you need.
25
-
26
- ```typescript
27
- import { some, none } from "functype/option"
28
- import { right } from "functype/either"
29
-
30
- // Usage
31
- const option = some(42)
32
- const none_value = none()
33
- const either = right("value")
34
- ```
35
-
36
- ## Bundle Size Comparison
37
-
38
- | Import Strategy | Approximate Bundle Size | Best For |
39
- | --------------- | ------------------------ | -------------------------- |
40
- | Selective | 200-500 bytes per module | Most applications |
41
- | Direct | <200 bytes per feature | Size-critical applications |
42
-
43
- ## Common Module Sizes
44
-
45
- | Module | Approximate Size (minified) | Gzipped Size |
46
- | -------- | --------------------------- | ------------ |
47
- | Option | ~200 bytes | ~140 bytes |
48
- | Either | ~290 bytes | ~190 bytes |
49
- | List | ~170 bytes | ~125 bytes |
50
- | Try | ~170 bytes | ~125 bytes |
51
- | Tuple | ~120 bytes | ~100 bytes |
52
- | FPromise | ~200 bytes | ~140 bytes |
53
-
54
- ## Additional Tips
55
-
56
- 1. **Import Analysis**: Use tools like [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer) or [rollup-plugin-visualizer](https://github.com/btd/rollup-plugin-visualizer) to analyze your bundle and identify opportunities for optimization.
57
-
58
- 2. **Dynamic Imports**: Consider using dynamic imports for rarely used functionality:
59
-
60
- ```typescript
61
- // Only load when needed
62
- const useRareFeature = async () => {
63
- const { someLargeUtility } = await import("functype/some-large-module")
64
- return someLargeUtility()
65
- }
66
- ```
67
-
68
- 3. **Development vs Production**: During development, you might prefer the convenience of importing everything. In production builds, switch to selective imports.
69
-
70
- 4. **Peer Dependencies**: Functype has minimal dependencies, and the only external dependency (`safe-stable-stringify`) is quite small.
71
-
72
- ## Need Help?
73
-
74
- If you need assistance with optimizing your bundle size further, please open an issue on our GitHub repository.
@@ -1,43 +0,0 @@
1
- # FPromise Implementation Assessment
2
-
3
- ## Overview
4
-
5
- This document provides an assessment of whether the FPromise implementation is ready to replace the old main branch version, with particular focus on potential impacts to implementing libraries outside this one.
6
-
7
- ## Strengths of the FPromise Implementation
8
-
9
- 1. **Comprehensive Error Handling**: FPromise provides rich error handling capabilities including `mapError`, `tapError`, `recover`, `recoverWith`, `recoverWithF`, `filterError`, and `logError`.
10
-
11
- 2. **Either Integration**: FPromise has built-in conversion to/from Either with `toEither()` and `fromEither()`, which aligns well with the functional programming approach used in the Task implementation.
12
-
13
- 3. **Promise Compatibility**: FPromise implements the PromiseLike interface, ensuring compatibility with async/await and standard Promise chains.
14
-
15
- 4. **Extensive Test Coverage**: The test suite is comprehensive, covering basic functionality, error handling, recovery mechanisms, and real-world scenarios.
16
-
17
- 5. **Retry Mechanisms**: The implementation includes multiple retry strategies (basic retry, retry with backoff, and retry with options).
18
-
19
- ## Potential Compatibility Issues
20
-
21
- 1. **Import Path Differences**: The Task.ts file imports from `"'core/throwable/Throwable"'` and `"'either/Either"'` with unusual quotes, while the actual imports should use `@/` prefix. This might cause issues if external libraries rely on these specific import paths.
22
-
23
- 2. **Type Compatibility**: The Task implementation uses `Either<Throwable, T>` for error handling, while FPromise uses a more generic approach. Libraries expecting specific Either structures might need adjustments.
24
-
25
- 3. **API Surface Changes**: External libraries that directly interact with the Promise implementation might need to adapt to the new methods and patterns provided by FPromise.
26
-
27
- ## Recommendation
28
-
29
- The FPromise implementation is technically sound and provides significant improvements, but to avoid breaking implementing libraries outside this one:
30
-
31
- 1. **Gradual Migration**: Consider a phased approach where both implementations coexist temporarily.
32
-
33
- 2. **Version Bumping**: This change warrants a major version bump to signal potential breaking changes.
34
-
35
- 3. **Documentation**: Provide clear migration guides for dependent libraries.
36
-
37
- 4. **Import Path Fixes**: Ensure import paths are consistent and follow the project's conventions.
38
-
39
- 5. **Compatibility Layer**: Consider providing a thin compatibility layer for libraries that can't immediately migrate to the new API.
40
-
41
- ## Conclusion
42
-
43
- The FPromise implementation appears ready to replace the old main branch version from a technical perspective, but careful migration planning is necessary to minimize disruption to implementing libraries.
package/readme/HKT.md DELETED
@@ -1,110 +0,0 @@
1
- # Higher-Kinded Types (HKT)
2
-
3
- Higher-kinded types allow for writing generic code that works across different container types like `Option`, `List`, `Either`, and `Try`. This is a powerful abstraction that lets you create algorithms that work with any type that supports certain operations, without having to rewrite them for each specific type.
4
-
5
- ## Introduction
6
-
7
- In functional programming, many operations like `map`, `flatMap`, or `sequence` follow similar patterns across different data structures. The HKT module provides a unified way to work with these operations for any supporting container type.
8
-
9
- ## Key Concepts
10
-
11
- 1. **Kind**: A type-level function representing a higher-kinded type relationship
12
- 2. **Container Types**: Data structures that contain values (Option, List, Either, etc.)
13
- 3. **Type Constructor**: A function that takes a type and returns a new type
14
-
15
- ## Basic Operations
16
-
17
- ### Map
18
-
19
- Apply a function to a value inside a container:
20
-
21
- ```typescript
22
- import { Option, HKT } from "functype"
23
-
24
- const option = Option(42)
25
- const doubled = HKT.map(option, (x) => x * 2) // Option(84)
26
- ```
27
-
28
- ### FlatMap
29
-
30
- Apply a function that returns a container to a value inside a container, then flatten the result:
31
-
32
- ```typescript
33
- const option = Option(42)
34
- const result = HKT.flatMap(option, (x) => Option(x * 2)) // Option(84)
35
- ```
36
-
37
- ### Flatten
38
-
39
- Flatten a nested container:
40
-
41
- ```typescript
42
- const nestedOption = Option(Option(42))
43
- const flattened = HKT.flatten(nestedOption) // Option(42)
44
- ```
45
-
46
- ## Advanced Operations
47
-
48
- ### Sequence
49
-
50
- Transform a container of containers into a container of container (e.g., `Option<List<A>>` to `List<Option<A>>`):
51
-
52
- ```typescript
53
- const optionOfList = Option(List([1, 2, 3]))
54
- const listOfOptions = HKT.sequence(optionOfList)
55
- // List([Option(1), Option(2), Option(3)])
56
- ```
57
-
58
- ### Traverse
59
-
60
- Transform each element in a container using a function that returns another container type, then sequence the results:
61
-
62
- ```typescript
63
- const list = List([1, 2, 3])
64
- const result = HKT.traverse(list, (x) => Option(x * 2))
65
- // Option(List([2, 4, 6]))
66
- ```
67
-
68
- ### Applicative (ap)
69
-
70
- Apply a function inside a container to a value inside another container:
71
-
72
- ```typescript
73
- const optionFn = Option((x: number) => x * 2)
74
- const optionValue = Option(21)
75
- const result = HKT.ap(optionFn, optionValue) // Option(42)
76
- ```
77
-
78
- ## Supported Container Types
79
-
80
- The HKT module currently supports the following container types:
81
-
82
- - `Option<A>`
83
- - `List<A>`
84
- - `Either<E, A>`
85
- - `Try<A>`
86
-
87
- ## Creating Generic Algorithms
88
-
89
- The power of HKT is in creating algorithms that work with any container type:
90
-
91
- ```typescript
92
- // A function that works with any container implementing map
93
- function increment<F extends (a: number) => any>(container: Kind<F, number>): Kind<F, number> {
94
- return HKT.map(container, (x) => x + 1)
95
- }
96
-
97
- // Works with any container
98
- increment(Option(41)) // Option(42)
99
- increment(List([1, 2, 3])) // List([2, 3, 4])
100
- increment(Right<string, number>(41)) // Right(42)
101
- ```
102
-
103
- ## Implementing Your Own Container Types
104
-
105
- To make your custom container types work with HKT, you need to:
106
-
107
- 1. Implement the appropriate methods (`map`, `flatMap`, etc.)
108
- 2. Add type checking in the HKT functions
109
-
110
- This allows seamless integration with the rest of the functional programming ecosystem.
package/readme/ROADMAP.md DELETED
@@ -1,113 +0,0 @@
1
- # Functype Roadmap (2025-2026)
2
-
3
- This roadmap outlines the planned development path for the Functype library, focusing on expanding functionality, improving performance, ensuring API consistency, and enhancing TypeScript integration.
4
-
5
- ## Q2 2025: Core Functional Data Types
6
-
7
- ### Lazy Evaluation
8
-
9
- - [ ] Implement `LazyList` / `Stream` for efficient processing of potentially infinite sequences
10
- - [ ] Add common operations: `map`, `filter`, `take`, `drop`, etc.
11
- - [ ] Implement memoization for evaluated values
12
-
13
- ### Validation Type
14
-
15
- - [ ] Create `Validation` data type for applicative validation
16
- - [ ] Support collecting multiple errors (unlike Either which short-circuits)
17
- - [ ] Add utilities for combining validation results
18
-
19
- ### Performance Foundation
20
-
21
- - [ ] Add memoization utilities for expensive function calls
22
- - [ ] Implement a basic benchmarking suite for measuring performance
23
- - [ ] Standardize performance metrics across data structures
24
-
25
- ## Q3 2025: Advanced Functional Patterns & Optimizations
26
-
27
- ### Type Classes
28
-
29
- - [x] Implement `Foldable` typeclass with fold, foldLeft, and foldRight methods
30
- - [x] Implement `Matchable` typeclass for pattern matching
31
- - [ ] Implement proper `Functor` and `Monad` typeclasses
32
- - [ ] Add `Applicative` typeclass
33
- - [ ] Support `Traversable` with comprehensive HKT
34
-
35
- ### Monad Implementations
36
-
37
- - [ ] Implement `Reader` monad for dependency injection
38
- - [ ] Add `State` monad for managing state transformations
39
- - [ ] Create `IO` monad for pure handling of side effects
40
- - [ ] Add comprehensive documentation and examples
41
-
42
- ### Performance Improvements
43
-
44
- - [ ] Implement structural sharing for immutable collections
45
- - [ ] Optimize recursive operations for large data structures
46
- - [ ] Add performance comparison against other FP libraries
47
-
48
- ### Lenses & Optics
49
-
50
- - [ ] Implement lens abstraction for immutable updates
51
- - [ ] Add prism implementation for optional data
52
- - [ ] Create utilities for composing lenses and prisms
53
-
54
- ## Q4 2025: TypeScript Enhancements & API Consistency
55
-
56
- ### TypeScript Integration
57
-
58
- - [x] Add support for higher-kinded types
59
- - [ ] Remove `any` from HKT
60
- - [x] Implement branded/nominal types for stronger type safety
61
- - [ ] Add type-level utilities using newer TypeScript features
62
- - [ ] Leverage const type parameters and tuple manipulation
63
-
64
- ### API Normalization
65
-
66
- - [ ] Review and standardize API across all modules
67
- - [ ] Ensure consistent implementation of the Scala-inspired pattern
68
- - [ ] Standardize import patterns (@imports throughout)
69
- - [ ] Create migration guides for API changes
70
-
71
- ## Q1 2026: Testing, Documentation & Community Support
72
-
73
- ### Testing Expansion
74
-
75
- - [ ] Add test coverage metrics and set coverage goals
76
- - [ ] Expand property-based testing across all modules
77
- - [ ] Create interoperability tests with popular libraries
78
- - [ ] Add more specialized test cases for error handling
79
-
80
- ### Documentation & Examples
81
-
82
- - [ ] Add comprehensive documentation for all modules
83
- - [ ] Create step-by-step migration guides from imperative to functional
84
- - [ ] Add real-world examples showcasing practical applications
85
- - [ ] Create tutorial sections for beginners
86
-
87
- ### Community Engagement
88
-
89
- - [ ] Create contribution guidelines and templates
90
- - [ ] Set up automated issue/PR handling
91
- - [ ] Establish regular release schedule
92
- - [ ] Add community forum/discussion platform
93
-
94
- ## Ongoing Priorities
95
-
96
- ### Compatibility
97
-
98
- - [ ] Ensure compatibility with Node.js LTS versions
99
- - [ ] Maintain browser compatibility
100
- - [ ] Support for Deno and other runtimes
101
- - [ ] Test with various bundlers (webpack, esbuild, etc.)
102
-
103
- ### Bundle Size
104
-
105
- - [x] Optimize tree-shaking
106
- - [x] Provide guidance on importing only needed modules
107
- - [x] Add bundle size monitoring to CI/CD
108
-
109
- ### Community Feedback
110
-
111
- - [ ] Regular review of GitHub issues and feature requests
112
- - [ ] Prioritization based on community needs
113
- - [ ] Transparent development process
@@ -1,33 +0,0 @@
1
- # Task TODO
2
-
3
- ## Goals
4
-
5
- - Enhance the Task module as an adapter between promise-based code and functional patterns
6
- - Improve interoperability with existing JavaScript/TypeScript codebases
7
- - Allow gradual migration to functional patterns without complete rewrites
8
-
9
- ## Implementation Tasks
10
-
11
- - [x] Review current Task implementation for completeness of promise integration
12
- - [x] Ensure robust error handling in sync/async conversions
13
- - [x] Document explicit try/catch/finally semantics
14
- - [x] Add examples showing migration from promise-based to functional patterns
15
- - [x] Add utilities to simplify Task composition with promise-returning functions
16
- - [x] Create migration guide for converting promise chains to Task operations
17
-
18
- ## Design Considerations
19
-
20
- - Maintain clear separation between synchronous and promise-based operations
21
- - Preserve functional error handling patterns while supporting promise interop
22
- - Keep API consistent with the rest of the library's functional approach
23
-
24
- ## Completed Enhancements
25
-
26
- - Added `fromPromise` adapter to convert promise-returning functions to Task-compatible functions
27
- - Added `toPromise` converter to transform Task results back to promises
28
- - Enhanced documentation with clearer descriptions of functionality
29
- - Created TaskMigration.md guide showing how to migrate from promises to functional Task patterns
30
- - Added comprehensive tests for the new adapter methods
31
- - Improved error handler behavior to ensure handlers are always called, even for TaggedThrowable errors
32
- - Enhanced error chaining to preserve context while supporting logging in error handlers
33
- - Added test coverage to verify error handlers are always called for all error types
@@ -1,76 +0,0 @@
1
- # Tuple Enhanced with Modern TypeScript Features
2
-
3
- ## What's Improved
4
-
5
- Our enhanced `Tuple` implementation leverages modern TypeScript features:
6
-
7
- 1. **Const type parameters** (TypeScript 5.0+)
8
- 2. **Variadic tuple types** (TypeScript 4.0+)
9
- 3. **Stronger type inference** for tuple elements
10
-
11
- ## Examples
12
-
13
- ### Basic Usage
14
-
15
- ```typescript
16
- import { Tuple } from "@/tuple"
17
-
18
- // Create a tuple with mixed types
19
- const personTuple = Tuple(["John Doe", 42, true])
20
-
21
- // Access values with type safety
22
- const name = personTuple.get(0) // Type is string
23
- const age = personTuple.get(1) // Type is number
24
- const active = personTuple.get(2) // Type is boolean
25
-
26
- // Transform the tuple
27
- const mapped = personTuple.map((values) => values.map((x) => (typeof x === "number" ? x * 2 : x)))
28
- ```
29
-
30
- ### Preserving Literal Types
31
-
32
- ```typescript
33
- // Using 'as const' with the enhanced implementation
34
- const literalTuple = Tuple([1, "hello", true] as const)
35
-
36
- // TypeScript now knows the exact types:
37
- const first = literalTuple.get(0) // Type is exactly 1 (not just number)
38
- const second = literalTuple.get(1) // Type is exactly 'hello' (not just string)
39
- const third = literalTuple.get(2) // Type is exactly true (not just boolean)
40
-
41
- // Benefits:
42
- // - Better type checking
43
- // - Autocomplete shows exact values
44
- // - Prevents invalid index access
45
- ```
46
-
47
- ### Type-Level Utilities (for future improvements)
48
-
49
- ```typescript
50
- // Example of potential future type utilities
51
- type FirstElement<T extends Tuple<unknown[]>> = T extends Tuple<[infer F, ...unknown[]]> ? F : never
52
-
53
- // Extract first element's type
54
- type First = FirstElement<typeof literalTuple> // Would be 1
55
-
56
- // Could expand to other utilities like:
57
- // - LastElement
58
- // - RemoveFirst
59
- // - Prepend<T, Item>
60
- // - etc.
61
- ```
62
-
63
- ## When Is This Useful?
64
-
65
- 1. **Strong typing for heterogeneous collections**:
66
- - When you need to store different types in a fixed structure
67
- - When you want type safety beyond what arrays provide
68
-
69
- 2. **APIs returning fixed-length, mixed-type results**:
70
- - When a function returns multiple values of different types
71
-
72
- 3. **Data transformation pipelines**:
73
- - When you need to transform data while preserving type information
74
-
75
- 4. **Configuration objects with fixed format**:
76
- - When config must follow a specific format with specific types at each position