[go: nahoru, domu]

Skip to content

Commit

Permalink
Implement Timestamp.valueOf().
Browse files Browse the repository at this point in the history
This enables comparison of Timestamp objects using the arithmetic comparison operators, such as < and >.

#2632
  • Loading branch information
dconeybe committed Feb 21, 2020
1 parent fbe0543 commit 53894ae
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/firestore/src/api/timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,31 @@ export class Timestamp {
')'
);
}

// Overriding valueOf() allows Timestamp objects to be compared in JavaScript using the
// arithmetic comparison operators, such as < and >.
// https://github.com/firebase/firebase-js-sdk/issues/2632
valueOf(): string {
const formattedSeconds = Timestamp.normalizeAndPad(
this.seconds,
Timestamp.MIN_SECONDS,
Timestamp.MAX_SECONDS
);
const formattedNanoseconds = Timestamp.normalizeAndPad(
this.nanoseconds,
Timestamp.MIN_NANOSECONDS,
Timestamp.MAX_NANOSECONDS
);
return formattedSeconds + '.' + formattedNanoseconds;
}

private static normalizeAndPad(
value: number,
minValue: number,
maxValue: number
): string {
const padLength = Math.ceil(Math.log10(maxValue - minValue));
const normalizedValue = value - minValue;
return normalizedValue.toString().padStart(padLength, '0');
}
}
12 changes: 12 additions & 0 deletions packages/firestore/test/unit/api/timestamp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,16 @@ describe('Timestamp', () => {
nanoseconds: 750000000
});
});

it('valueOf', () => {
expect(new Timestamp(-62135596677, 456).valueOf()).to.equal(
'000000000123.000000456'
);
expect(new Timestamp(-62135596800, 0).valueOf()).to.equal(
'000000000000.000000000'
);
expect(new Timestamp(253402300799, 1e9 - 1).valueOf()).to.equal(
'315537897599.999999999'
);
});
});

0 comments on commit 53894ae

Please sign in to comment.