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
30 changes: 29 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,35 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const splitedDate = date.split(fromFormat[3]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This split logic assumes the separator is always at fromFormat[3]. The description defines fromFormat as a format descriptor array but doesn’t guarantee that the separator is always at index 3; if that changes, this will fail. Consider finding the non-token element dynamically instead of hardcoding the index.


const objDate = {};

for (let i = 0; i < 3; i++) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The loop is hardcoded to exactly three components, which works for the provided examples, but it assumes the format will always have three date tokens. If fromFormat length or composition changes, this will not adapt; iterating based on the actual date-part entries in fromFormat would be more aligned with the description.

objDate[fromFormat[i]] = splitedDate[i];
}

const result = [];

for (let item = 0; item < 3; item++) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Similarly, this loop assumes exactly three date-part positions in toFormat. While OK for the examples, it couples the logic to a specific array shape; using the actual date-part entries from toFormat instead of a magic number would make the function match the general “format descriptor” idea more closely.

if (objDate[toFormat[item]]) {
result.push(objDate[toFormat[item]]);
} else if (toFormat[item] === 'YY') {
const fullYear = objDate['YYYY'];

result.push(fullYear.slice(-2));
} else if (toFormat[item] === 'YYYY') {
const shortYear = objDate['YY'];

if (shortYear >= 30) {
result.push('19' + shortYear);
} else {
result.push('20' + shortYear);
}
}
}

return result.join(toFormat[3]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Joining with toFormat[3] implicitly assumes the separator is always at index 3 in toFormat. If the format arrays ever place the separator elsewhere, the output separator will be wrong. Deriving the separator by finding the non-YYYY/YY/MM/DD entry would avoid this assumption.

}

module.exports = formatDate;
Loading