Skip to content

Instantly share code, notes, and snippets.

@CrossEye
Last active May 2, 2020 22:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrossEye/005bc0c848593bd37860978fe258dd27 to your computer and use it in GitHub Desktop.
Save CrossEye/005bc0c848593bd37860978fe258dd27 to your computer and use it in GitHub Desktop.
// 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