Skip to content

fix: use ObjectID timestamp for createdTime sorting#18

Open
Leoyishou wants to merge 1 commit intoevalor:masterfrom
Leoyishou:fix/createdTime-sorting
Open

fix: use ObjectID timestamp for createdTime sorting#18
Leoyishou wants to merge 1 commit intoevalor:masterfrom
Leoyishou:fix/createdTime-sorting

Conversation

@Leoyishou
Copy link

Problem

When using sortBy: "createdTime" with sortOrder: "desc", the tasks are not sorted correctly by creation time. The oldest tasks appear first instead of the newest.

Root Cause

The current implementation uses the sortOrder field as a proxy for creation time:

case "createdTime": {
    const orderA = a.sortOrder ?? 0;
    const orderB = b.sortOrder ?? 0;
    comparison = orderA - orderB;
    break;
}

However, sortOrder values are extremely large negative numbers (e.g., -8936026338357117000), which is approximately 8.9×10^18. This exceeds JavaScript's safe integer range (Number.MAX_SAFE_INTEGER = 2^53 - 19×10^15).

When arithmetic operations are performed on these values, precision is lost, resulting in incorrect comparison results.

Solution

Extract the actual Unix timestamp from MongoDB ObjectID. The first 8 hexadecimal characters of an ObjectID represent a Unix timestamp in seconds.

case "createdTime": {
    const getTimestampFromId = (id: string | undefined): number => {
        if (typeof id === 'string' && id.length >= 8) {
            return parseInt(id.substring(0, 8), 16);
        }
        return 0;
    };
    const timeA = getTimestampFromId(a.id);
    const timeB = getTimestampFromId(b.id);
    comparison = timeA - timeB;
    break;
}

Testing

Before fix:

Task 1 (2025-08-31) → Task 2 (2025-09-01) → ... → Task 50 (2025-12-17)

(Oldest first, regardless of sortOrder setting)

After fix:

Task 50 (2025-12-17) → ... → Task 2 (2025-09-01) → Task 1 (2025-08-31)

(Newest first when sortOrder: "desc")


🤖 Generated with Claude Code

The previous implementation used `sortOrder` field as a proxy for
creation time, but these values (~8.9×10^18) exceed JavaScript's
safe integer range (2^53 ≈ 9×10^15), causing precision loss during
arithmetic operations and incorrect sorting results.

This fix extracts the actual Unix timestamp from MongoDB ObjectID's
first 8 hex characters, which provides accurate creation time sorting.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant