Created
November 11, 2016 07:19
-
-
Save LilyMGoh/e4ef587770c67bcfe8e0a36e0c76d53f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getIndicesOf(str, delimiter, options) { | |
let indices = new Set(); | |
let fromIdx = 0; | |
let idx = null; | |
while (idx !== -1 && idx <= options.max) { | |
if (idx) { | |
indices.add(idx); | |
} | |
idx = str.indexOf(delimiter, fromIdx); | |
fromIdx = idx + 1; | |
} | |
return indices; | |
} | |
function findIdealIdx(indices, options) { | |
let maxDiff = options.max - options.ideal; | |
let minDiff = options.ideal - options.min; | |
for(let i = 0; i <= maxDiff || i <= minDiff; i++) { | |
let minIndex = options.ideal - i; | |
let maxIndex = options.ideal + i; | |
if (i <= maxDiff && indices.has(maxIndex)) { | |
return maxIndex; | |
} else if (i <= minDiff && indices.has(minIndex)) { | |
return minIndex; | |
} | |
} | |
return null; | |
} | |
export function truncate (str, options) { | |
if (str.split('').length < options.min) { | |
return [str, '']; | |
} | |
let idx = | |
findIdealIdx(getIndicesOf(str, '. ', options), options) || | |
findIdealIdx(getIndicesOf(str, ', ', options), options) || | |
findIdealIdx(getIndicesOf(str, ' ', options), options) || | |
findIdealIdx(getIndicesOf(str, '', options), options); | |
return [str.substring(0, idx + 1), str.substring(idx + 1)]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment