int_32.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import type { EJSONOptions } from './extended_json';
  2. /** @public */
  3. export interface Int32Extended {
  4. $numberInt: string;
  5. }
  6. /**
  7. * A class representation of a BSON Int32 type.
  8. * @public
  9. * @category BSONType
  10. */
  11. export class Int32 {
  12. _bsontype!: 'Int32';
  13. value!: number;
  14. /**
  15. * Create an Int32 type
  16. *
  17. * @param value - the number we want to represent as an int32.
  18. */
  19. constructor(value: number | string) {
  20. if (!(this instanceof Int32)) return new Int32(value);
  21. if ((value as unknown) instanceof Number) {
  22. value = value.valueOf();
  23. }
  24. this.value = +value | 0;
  25. }
  26. /**
  27. * Access the number value.
  28. *
  29. * @returns returns the wrapped int32 number.
  30. */
  31. valueOf(): number {
  32. return this.value;
  33. }
  34. toString(radix?: number): string {
  35. return this.value.toString(radix);
  36. }
  37. toJSON(): number {
  38. return this.value;
  39. }
  40. /** @internal */
  41. toExtendedJSON(options?: EJSONOptions): number | Int32Extended {
  42. if (options && (options.relaxed || options.legacy)) return this.value;
  43. return { $numberInt: this.value.toString() };
  44. }
  45. /** @internal */
  46. static fromExtendedJSON(doc: Int32Extended, options?: EJSONOptions): number | Int32 {
  47. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  48. }
  49. /** @internal */
  50. [Symbol.for('nodejs.util.inspect.custom')](): string {
  51. return this.inspect();
  52. }
  53. inspect(): string {
  54. return `new Int32(${this.valueOf()})`;
  55. }
  56. }
  57. Object.defineProperty(Int32.prototype, '_bsontype', { value: 'Int32' });