Skip to content

Instantly share code, notes, and snippets.

@jnsprnw
Created December 5, 2016 09:27
Show Gist options
  • Select an option

  • Save jnsprnw/c60940a7dacceb5f9671bbc8e07d3089 to your computer and use it in GitHub Desktop.

Select an option

Save jnsprnw/c60940a7dacceb5f9671bbc8e07d3089 to your computer and use it in GitHub Desktop.
function getSpacePositions(str, origin) {
const positions = [];
const pre = str.lastIndexOf(' ', origin);
const post = str.indexOf(' ', origin);
if (pre > 0) { positions.push(pre); }
if (post > 0) { positions.push(post); }
return positions;
}
function getClosestValue(positions, value) {
return value - positions[0] < positions[1] - value ? positions[0] : positions[1];
}
function insertLineBreak(str, positions) {
if (!positions.length) { return str; }
let broken = str;
positions.sort().forEach(function (position, index) {
const positiom = position + index;
broken = broken.substr(0, positiom).trim() + '\n' + broken.substr(positiom).trim();
});
return broken;
}
function getBreakForPosition(str, position) {
const possibleBreaks = getSpacePositions(str, position);
let bestPosition = 0;
if (possibleBreaks.length == 1) {
bestPosition = possibleBreaks[0];
} else if (possibleBreaks.length > 1) {
bestPosition = getClosestValue(possibleBreaks, position);
}
return bestPosition;
}
function getPositions(str, n) {
const distance = str.length / n;
const positions = [];
const length = n - 1;
for(let i = 1; i <= length; i++) {
positions.push(distance * i);
}
return positions;
}
function insertLineBreaks(str) {
const positions = getPositions(str, 3);
const bestPositions = positions.map(function(position) {
return getBreakForPosition(str, position);
})
return insertLineBreak(str, bestPositions);
}
console.log(insertLineBreaks('Mario Vargass Lsssssosa Vargass'));
console.log(insertLineBreaks('M a r i o V a r g a s s Lsssssosa Vargass'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment