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

Open
wants to merge 1 commit 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
32 changes: 31 additions & 1 deletion src/formatDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,37 @@
* @returns {string}
*/
function formatDate(date, fromFormat, toFormat) {
// write code here
const result = [];
const separator = fromFormat[fromFormat.length - 1];
const parts = date.split(separator);
const mapping = {};

for (let i = 0; i < fromFormat.length - 1; i++) {
mapping[fromFormat[i]] = parts[i];
}

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

if (year < 30) {
mapping['YYYY'] = 20 + mapping['YY'];

Choose a reason for hiding this comment

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

The concatenation of 20 with mapping['YY'] should be a string operation. Use mapping['YYYY'] = '20' + mapping['YY']; to ensure the result is a string.

} else {
mapping['YYYY'] = 19 + mapping['YY'];

Choose a reason for hiding this comment

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

The concatenation of 19 with mapping['YY'] should be a string operation. Use mapping['YYYY'] = '19' + mapping['YY']; to ensure the result is a string.

}
}

const newSeparator = toFormat[toFormat.length - 1];

Choose a reason for hiding this comment

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

Ensure that toFormat always has a separator as its last element. If this is not guaranteed, you might encounter issues with the newSeparator variable.


const newDate = toFormat
.slice(0, -1)
.map((format) => mapping[format])
.join(newSeparator);

result.push(newDate);

return result.join('');
}

module.exports = formatDate;
Loading