feat: Add immutable toSorted function
#379
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #255
Summary
This PR adds a new
toSortedfunction that provides an immutable alternative to the existingsortfunction. Unlikesort, which mutates the original array,toSortedreturns a new sorted array without modifying the input.Changes
New Function:
toSortedsrc/toSorted.tssrc/index.tssortfunction (supports currying)Key Features
Array.prototype.toSortedwhen available (ES2023+)pipeand other FxTS functionsImplementation Details
Array.prototype.toSortedArray.from()+sort()when native method is unavailablesortfor consistency@ts-expect-errorcomments to handle TypeScript type limitations (see TypeScript Version Considerations below)Testing
Comprehensive test suite added in
test/toSorted.spec.ts:sortfunction (same results, no mutation)pipe,filter,mapcombinations)All tests pass:
npm test✅TypeScript Version Considerations
Current Implementation
The current implementation uses
@ts-expect-errorcomments to work around TypeScript type limitations:Array.prototype.toSortedis not in TypeScript lib types until TS 5.2+package.json)["es2020"](as specified intsconfig.json)Why
@ts-expect-errorInstead ofany?We chose
@ts-expect-erroroveranytype assertions because:Future Improvement Opportunity
When the project upgrades to TypeScript 5.2+ and updates
tsconfig.jsonto includeES2023in thelibarray, we can:@ts-expect-errorcomments - TypeScript will recognizeArray.prototype.toSortednativelyRecommended upgrade path:
After upgrading, the code can be simplified to:
This is a non-breaking change - the current implementation works correctly and will continue to work after the upgrade, but the upgrade will allow us to remove the workarounds.
Code Quality
npm run compile:check(TypeScript type checking)npm run lint(ESLint)npm run prettier(code formatting)sortfunction structure for consistencyExamples
Breaking Changes
None. This is a purely additive change.
Related
sort,shuffle(for immutable pattern reference)