function solution(polynomial) {
let terms = polynomial.replace(/ /gi, '').split('+');
let sums = terms.reduce(([a,b], term) => {
if (term.includes('x')) {
if (term.length === 1) {
return [a + 1, b];
} else {
return [a + term.replace('x', '')*1, b];
}
} else {
return [a, b + term*1];
}
}, [0, 0]);
if (sums[0] === 0 && sums[1] === 0) {
return 0;
}
if (sums[0] > 0 && sums[1] === 0) {
return `${sums[0]}x`;
}
if (sums[0] === 0 && sums[1] > 0) {
return `${sums[1]}`;
}
if (sums[0] > 0 && sums[1] > 0) {
return `${sums[0]}x + ${sums[1]}`;
}
}
function solution(polynomial) {
let terms = polynomial.replace(/ /gi, '').split('+');
let sums = terms.reduce(([a,b], term) => {
console.log('a : ', a, ' b : ', b, ' term : ', term);
if (term.includes('x')) {
if (term.length === 1) {
return [a + 1, b];
} else {
return [a + term.replace('x', '')*1, b];
}
} else {
return [a, b + term*1];
}
}, [0, 0]);
console.log('***', sums[0], ' / ', sums[1]);
if (sums[0] === 0 && sums[1] === 0) {
return 0;
}
if (sums[0] > 0 && sums[1] === 0) {
return sums[0] === 1 ? 'x' : `${sums[0]}x`;
}
if (sums[0] === 0 && sums[1] > 0) {
return `${sums[1]}`;
}
if (sums[0] > 0 && sums[1] > 0) {
return `${sums[0] === 1 ? '' : sums[0]}x + ${sums[1]}`;
}
}