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 #2218

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
33 changes: 32 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,38 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const dateParts = {};
const separator = fromFormat.find(
(part) =>
part !== 'DD' && part !== 'MM' && part !== 'YYYY' && part !== 'YY',
);
Comment on lines +12 to +15

Choose a reason for hiding this comment

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

The logic for determining the separator is incorrect. It assumes that the first non-date part is the separator, but this might not be the case if multiple separators exist. Consider using a regular expression to extract the separator from the date string.

const splitDate = date.split(separator);

for (let i = 0; i < fromFormat.length; i++) {
if (fromFormat[i] === 'YY') {
const year = splitDate[i];

dateParts['YYYY'] =
year.length === 2 ? (+year < 30 ? `20${year}` : `19${year}`) : year;
dateParts['YY'] = year.length === 2 ? year : year.slice(-2);
} else {
dateParts[fromFormat[i]] = splitDate[i];
}
}

if (toFormat.includes('YY') && !dateParts['YY']) {
dateParts['YY'] = dateParts['YYYY'].slice(-2);
}

const newSeparator = toFormat.find(
(part) =>
part !== 'DD' && part !== 'MM' && part !== 'YYYY' && part !== 'YY',
);
Comment on lines +34 to +37

Choose a reason for hiding this comment

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

The logic for determining the new separator is incorrect for the same reason as the fromFormat separator. Ensure that you correctly identify the separator used in the toFormat.


return toFormat
.slice(0, -1)
.map((part) => dateParts[part])
.join(newSeparator);
Comment on lines +40 to +42

Choose a reason for hiding this comment

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

The slice(0, -1) call on toFormat is incorrect as it removes the last element of the array, which might be a necessary part of the format. Ensure that all parts of toFormat are included in the final result.

}

module.exports = formatDate;
Loading