Considering the discussion from the comment if nanoseconds matter default value can be passed with ||
if timestamp
don't have any of the property.
Can be demonstrated as
function shortMonthDay(timestamp) {
let date = new Date(timestamp?.seconds * 1000 || Date.now() + (timestamp?.nanoseconds || 0) / 1000000);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric'
})
}
const timestamp = {
"seconds": 1667420699,
"nanoseconds": 394000000
};
console.log(`with timestamp ${shortMonthDay(timestamp)}`);
console.log(`without timestamp ${shortMonthDay()}`);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Without the timestamp
parameter it compromises nanoseconds to 0 and seconds to the current timestamp.
Performance (this is from the observation)
with old snippet
function shortMonthDay(timestamp = undefined) {
let date
if (timestamp) {
date = new Date(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
} else {
date = new Date()
}
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric'
}) // Nov 2
}
const timestamp = {
"seconds": 1667420699,
"nanoseconds": 394000000
};
let res = [];
for(let i = 0; i< 10; i++){
let start = window.performance.now();
shortMonthDay(timestamp);
res.push(window.performance.now() - start);
}
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With the altered snippet which minimizes a few unnoticeable things that benefit performance gain
function shortMonthDay(timestamp) {
let date = new Date(timestamp?.seconds * 1000 || Date.now() + (timestamp?.nanoseconds || 0) / 1000000);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric'
})
}
const timestamp = {
"seconds": 1667420699,
"nanoseconds": 394000000
};
let res = [];
for(let i = 0; i< 10; i++){
let start = window.performance.now();
shortMonthDay(timestamp);
res.push(window.performance.now() - start);
}
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }