feat: Add native Date object support to fast-json-patch#330
Open
nyamathshaik wants to merge 1 commit intoStarcounter-Jack:masterfrom
Open
feat: Add native Date object support to fast-json-patch#330nyamathshaik wants to merge 1 commit intoStarcounter-Jack:masterfrom
nyamathshaik wants to merge 1 commit intoStarcounter-Jack:masterfrom
Conversation
This commit adds proper handling for JavaScript Date objects in JSON Patch operations.
## Changes
### 1. Enhanced `_deepClone` function (src/helpers.ts)
- Added special handling for Date objects to preserve them as Date instances
- Changed from JSON.stringify/parse approach to recursive cloning
- Date objects are now cloned using `new Date(obj.getTime())` to maintain type and value
- Arrays and objects are recursively cloned to handle nested Date objects
### 2. Enhanced `_generate` function (src/duplex.ts)
- Added Date-specific comparison logic
- Date objects are now compared by value (using `getTime()`) instead of by reference
- When two Date objects have different timestamps, a replace patch is generated
- Preserves Date objects in the generated patches (not converted to ISO strings)
### 3. Added comprehensive test suite (test/spec/dateSpec.mjs)
- Tests for cloning Date objects
- Tests for comparing objects with Date properties
- Tests for nested Date objects in arrays and objects
- Real-world scenario test simulating calendar event workflows
## Benefits
- **Type Preservation**: Date objects remain as Date instances throughout patch operations
- **Correct Comparisons**: Dates are compared by value, not reference
- **Backward Compatible**: All existing tests pass (215 specs, 0 failures)
- **Real-world Use Case**: Solves issues when working with API responses containing dates
## Use Case
This fix addresses the common scenario where workflow contexts contain Date objects
(e.g., calendar events, timestamps, scheduled tasks) and need to generate accurate
diffs without converting dates to strings.
Example:
```javascript
const oldContext = { events: [] };
const newContext = {
events: [{
startTime: new Date('2025-11-15T10:00:00Z'),
endTime: new Date('2025-11-15T11:00:00Z')
}]
};
const patches = compare(oldContext, newContext);
// Patches now contain actual Date objects, not ISO strings
```
## Testing
All tests pass:
- New Date-specific tests: 11 specs, 0 failures
- Existing core tests: 215 specs, 0 failures
Co-authored-by: Claude <noreply@anthropic.com>
nyamathshaik
added a commit
to nyamathshaik/JSON-Patch
that referenced
this pull request
Nov 11, 2025
- Changed package name to @nyamathshaik/fast-json-patch - Updated version to 3.1.2-date-support.0 - Added FORK_README.md with migration instructions - This is a temporary fork until PR Starcounter-Jack#330 is merged
86cdb1b to
c4a1886
Compare
chakrabar
reviewed
Nov 11, 2025
| var newVal = obj[key]; | ||
| if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) { | ||
| _generate(oldVal, newVal, patches, path + "/" + helpers_js_1.escapePathComponent(key), invertible); | ||
| // Special handling for Date objects: compare by value, not reference |
There was a problem hiding this comment.
if structuredClone is available, maybe we can use that, otherwise fallback to this?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Add Native Date Object Support
Summary
This PR adds proper handling for JavaScript Date objects in JSON Patch operations. Currently,
fast-json-patchconverts Date objects to ISO strings during cloning, which causes type loss and incorrect comparisons. This PR fixes that by preserving Date objects throughout the patching process.Problem
When using
compare()on objects containing Date objects:Root Causes:
_deepCloneusesJSON.stringify/parse- This converts Date objects to ISO strings===), not by valueSolution
1. Enhanced
_deepCloneFunctionnew Date(obj.getTime())Before:
After:
2. Enhanced
_generateFunctiongetTime()replacepatchesBefore:
After:
Changes
src/helpers.ts_deepClonewith Date supportsrc/duplex.ts_generatetest/spec/dateSpec.mjsTesting
New Tests (11 specs)
✅ Clone Date objects correctly
✅ Clone objects containing Date objects
✅ Clone arrays with Date objects
✅ Detect Date changes in
compare()✅ No patches for identical Dates
✅ Handle Date objects in nested structures
✅ Detect Date additions
✅ Detect Date removals
✅ Apply Date patches with
applyPatch()✅ Real-world calendar events scenario
Existing Tests
✅ All 215 existing tests pass (core, duplex, validate)
Real-World Use Case
This fix is crucial for workflows that handle:
Example: Workflow Context Diffing
Performance
Backward Compatibility
✅ Fully backward compatible
Related Issues
This fixes issues where:
Checklist
Would love feedback on: