Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,42 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const sep = fromFormat[fromFormat.length - 1];
const obj = {};
const a = [];

function convertDigits() {
if ('YYYY' in obj) {
obj['YY'] = obj['YYYY'].slice(2);
delete obj['YYYY'];

return;
}

if ('YY' in obj) {
obj['YYYY'] = obj['YY'] < 30 ? '20' + obj['YY'] : '19' + obj['YY'];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

obj['YYYY'] = obj['YY'] < 30 ? '20' + obj['YY'] : '19' + obj['YY']; relies on implicit numeric coercion of the string obj['YY']. Given assumptions about valid input this likely works, but making the comparison numeric explicitly would better reflect the requirement YY < 30 and avoid subtle type issues.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When converting YY to YYYY, this comparison relies on implicit string-to-number coercion; consider using Number(obj['YY']) < 30 to make the numeric intent explicit and avoid subtle type issues.

delete obj['YY'];
}
}

const splitArray = date.split(sep);

for (let i = 0; i < splitArray.length; i++) {
obj[fromFormat[i]] = splitArray[i];
}

if (
(fromFormat.includes('YYYY') && toFormat.includes('YY')) ||
(fromFormat.includes('YY') && toFormat.includes('YYYY'))
) {
convertDigits();
}

for (let i = 0; i < toFormat.length - 1; i++) {
a.push(obj[toFormat[i]]);
}

return a.join(toFormat[toFormat.length - 1]);
}

module.exports = formatDate;
Loading