From ba5f3940e12f59f7af80686c4debbe728a244655 Mon Sep 17 00:00:00 2001 From: Owk Date: Wed, 22 Jan 2025 15:47:32 +0200 Subject: [PATCH] Solution --- src/formatDate.js | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/formatDate.js b/src/formatDate.js index 769e2766..fa737b16 100644 --- a/src/formatDate.js +++ b/src/formatDate.js @@ -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']; + } else { + mapping['YYYY'] = 19 + mapping['YY']; + } + } + + const newSeparator = toFormat[toFormat.length - 1]; + + const newDate = toFormat + .slice(0, -1) + .map((format) => mapping[format]) + .join(newSeparator); + + result.push(newDate); + + return result.join(''); } module.exports = formatDate;