Last active
May 2, 2020 22:46
-
-
Save CrossEye/005bc0c848593bd37860978fe258dd27 to your computer and use it in GitHub Desktop.
This file contains 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
// Response to https://stackoverflow.com/a/59556845 | |
const shrink = (len) => (str) => { | |
const words = str .split (' ') | |
const idx = words .findIndex ( | |
(w, i) => words .slice(0, i) .join (' ') .length > len | |
) | |
return idx < 0 ? str : words .slice (0, idx - 1) .join ( ' ') + '...' | |
} | |
shrink (17) ("Hi you know anybody like pizza") //=> "Hi you know..." | |
shrink (20) ("Hi you know anybody like pizza") //=> "Hi you know anybody..." | |
shrink (50) ("Hi you know anybody like pizza") //=> "Hi you know anybody like pizza" | |
// Alternately, in a version that uses only expressions and not statement, | |
// but which is not suitable for being `mapped`, for instance: | |
/* | |
const shrink = (len) => ( | |
str, | |
words = str .split (' '), | |
idx = words .findIndex ( | |
(w, i) => words .slice(0, i) .join (' ') .length > len | |
) | |
) => idx < 0 ? str : words .slice (0, idx - 1) .join ( ' ') + '...' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment