Limit Title/string Length #Javascript #limit
/*
// STRING Title = Pasta with Tomato and spinach
acc : 0 / acc + cur.length = 5 / newTitle = ['Pasta']
acc : 5 / acc + cur.length = 9 / newTitle = ['Pasta','with']
acc : 9 / acc + cur.length = 15 / newTitle = ['Pasta','with','Tomato']
acc : 15 / acc + cur.length = 18 / newTitle = ['Pasta','with','Tomato']
acc : 18 / acc + cur.length = 18 / newTitle = ['Pasta','with','Tomato'] -> The word 'and' not passed on array newTitle
acc : 18 / acc + cur.length = 18 / newTitle = ['Pasta','with','Tomato'] -> The word 'spinach' not passed on array newTitle
*/
const stringLengthLimit = (title, limit = 17) => {
const newTitle = [];
if (title.length > limit) {
title.split(' ').reduce((acc, cur) => {
if (acc + cur.length <= limit) {
newTitle.push(cur);
}
return acc + cur.length;
}, 0);
return `${newTitle.join(' ')}...`;
}
return title;
};