Skip to content

Commit

Permalink
solution
Browse files Browse the repository at this point in the history
  • Loading branch information
yuliiazubenko committed Nov 6, 2024
1 parent 5cdfa57 commit c31dd7a
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions src/convertToObject.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,29 @@
*
* @return {object}
*/
function convertToObject(sourceString) {
const stylesObject = {};

sourceString
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line.includes(':'))
.forEach((line) => {
const [key, value] = line.split(':').map((part) => part.trim());

if (key && value) {
if (value.endsWith(';')) {
// eslint-disable-next-line no-const-assign
value = value.slice(0, -1);
}
stylesObject[key] = value;
}
});

return stylesObject;
function convertToObject(stylesString) {
return stylesString.split(';').reduce((accumulator, declaration) => {
const trimmedDecl = declaration.trim();

if (!trimmedDecl) {
return accumulator;
}

const colonIndex = trimmedDecl.indexOf(':');

if (colonIndex === -1) {
return accumulator;
}

const property = trimmedDecl.slice(0, colonIndex).trim();
const value = trimmedDecl.slice(colonIndex + 1).trim();

if (property && value) {
accumulator[property] = value;
}

return accumulator;
}, {});
}

module.exports = convertToObject;

0 comments on commit c31dd7a

Please sign in to comment.