Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution #2002

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 2 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
39 changes: 38 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,44 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const fromSeparator = fromFormat[3];
const toSeparator = toFormat[3];

const dateParts = date.split(fromSeparator);

const dateMap = {};

fromFormat.slice(0, 3).forEach((part, index) => {
dateMap[part] = dateParts[index];
Comment on lines +18 to +19

Choose a reason for hiding this comment

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

Ensure that the date parts are correctly mapped even if the fromFormat array is not in the order of 'YYYY', 'MM', 'DD'. The current implementation assumes a specific order, which may not always be the case.

Copy link
Author

Choose a reason for hiding this comment

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

done

});

if (fromFormat.includes('YYYY') && toFormat.includes('YY')) {
if (dateMap['YYYY'] && dateMap['YYYY'].length === 4) {
dateMap['YY'] = dateMap['YYYY'].slice(2);
}
} else if (fromFormat.includes('YY') && toFormat.includes('YYYY')) {
if (dateMap['YY'] && dateMap['YY'].length === 2) {
const year = parseInt(dateMap['YY'], 10);

if (!isNaN(year)) {
dateMap['YYYY'] =
year < 30 ? '20' + dateMap['YY'] : '19' + dateMap['YY'];
}
}
}

const newDate = toFormat

Choose a reason for hiding this comment

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

The mapping from dateMap to the new date format assumes that all required parts are present in dateMap. Consider adding a check to ensure that each required part of toFormat is available in dateMap before attempting to map it to avoid undefined values in the output.

.slice(0, 3)
.map((part) => {
if (dateMap[part] === undefined) {
throw new Error(`Missing required part '${part}' in the date.`);
}

return dateMap[part];
})
.join(toSeparator);

return newDate;
}

module.exports = formatDate;
Loading