58 lines
1.4 KiB
JavaScript
58 lines
1.4 KiB
JavaScript
const moment = require('moment');
|
|
|
|
class TransactionNumberGenerator {
|
|
constructor() {
|
|
this.timestampMap = new Map();
|
|
this.lock = { isLocked: false };
|
|
}
|
|
|
|
_acquireLock() {
|
|
while (this.lock.isLocked) {
|
|
/* Busy wait */
|
|
}
|
|
this.lock.isLocked = true;
|
|
}
|
|
|
|
_releaseLock() {
|
|
this.lock.isLocked = false;
|
|
}
|
|
|
|
// Convert date and time to Unix timestamp, handling 'YYYY-MM-DD' and 'YYYY-MM-DD HH:mm:ss'
|
|
_getUnixTimestamp(dateTime) {
|
|
if (dateTime instanceof Date) {
|
|
// Convert Date object to 'YYYY-MM-DD HH:mm:ss'
|
|
dateTime = moment(dateTime).format('YYYY-MM-DD HH:mm:ss');
|
|
}
|
|
|
|
// Determine whether the input includes time
|
|
const format = dateTime.includes(' ')
|
|
? 'YYYY-MM-DD HH:mm:ss'
|
|
: 'YYYY-MM-DD';
|
|
|
|
// Parse based on the format and return Unix timestamp
|
|
return moment(dateTime, format).unix();
|
|
}
|
|
|
|
generateUniqueTransactionNumber(dateTime = new Date()) {
|
|
this._acquireLock();
|
|
|
|
const timestamp = this._getUnixTimestamp(dateTime);
|
|
if (!this.timestampMap.has(timestamp)) {
|
|
this.timestampMap.set(timestamp, 0);
|
|
}
|
|
let counter = this.timestampMap.get(timestamp) + 1;
|
|
this.timestampMap.set(timestamp, counter);
|
|
|
|
this._releaseLock();
|
|
|
|
// Create unique number with timestamp and counter
|
|
const uniqueNumber = ((timestamp % 10000000000) * 1000 + counter)
|
|
.toString()
|
|
.padStart(11, '0');
|
|
|
|
return uniqueNumber;
|
|
}
|
|
}
|
|
|
|
module.exports = TransactionNumberGenerator;
|