|
|
import { BSONValue } from './bson_value'; |
|
|
import type { EJSONOptions } from './extended_json'; |
|
|
|
|
|
|
|
|
export interface DoubleExtended { |
|
|
$numberDouble: string; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export class Double extends BSONValue { |
|
|
get _bsontype(): 'Double' { |
|
|
return 'Double'; |
|
|
} |
|
|
|
|
|
value!: number; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
constructor(value: number) { |
|
|
super(); |
|
|
if ((value as unknown) instanceof Number) { |
|
|
value = value.valueOf(); |
|
|
} |
|
|
|
|
|
this.value = +value; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
valueOf(): number { |
|
|
return this.value; |
|
|
} |
|
|
|
|
|
toJSON(): number { |
|
|
return this.value; |
|
|
} |
|
|
|
|
|
toString(radix?: number): string { |
|
|
return this.value.toString(radix); |
|
|
} |
|
|
|
|
|
|
|
|
toExtendedJSON(options?: EJSONOptions): number | DoubleExtended { |
|
|
if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { |
|
|
return this.value; |
|
|
} |
|
|
|
|
|
if (Object.is(Math.sign(this.value), -0)) { |
|
|
|
|
|
|
|
|
return { $numberDouble: '-0.0' }; |
|
|
} |
|
|
|
|
|
return { |
|
|
$numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() |
|
|
}; |
|
|
} |
|
|
|
|
|
|
|
|
static fromExtendedJSON(doc: DoubleExtended, options?: EJSONOptions): number | Double { |
|
|
const doubleValue = parseFloat(doc.$numberDouble); |
|
|
return options && options.relaxed ? doubleValue : new Double(doubleValue); |
|
|
} |
|
|
|
|
|
|
|
|
[Symbol.for('nodejs.util.inspect.custom')](): string { |
|
|
return this.inspect(); |
|
|
} |
|
|
|
|
|
inspect(): string { |
|
|
const eJSON = this.toExtendedJSON() as DoubleExtended; |
|
|
return `new Double(${eJSON.$numberDouble})`; |
|
|
} |
|
|
} |
|
|
|