Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Created January 12, 2015 04:11
Show Gist options
  • Save YanivHaramati/8ea73333bbc3c2c554a5 to your computer and use it in GitHub Desktop.
Save YanivHaramati/8ea73333bbc3c2c554a5 to your computer and use it in GitHub Desktop.
Longest word in a sentence in terms of reduce
// longest word in sentence, and ignore punctuation.
function longestWord(sen) {
// would be easier if we had support for unicode character classes, at which point can use \p{P} for punctuation.
var punctPattern = /[\!\@\#\$\%\^\&\*\(\)\'\|\"/\\\-\+~`?\<\>\}\{]/g;
return sen.replace(punctPattern, '')
.split(' ')
.reduce(function(p, c, i, a) {
var maxLength = p.max;
var curLength = c.length;
if (curLength >= maxLength) {
p.max = curLength;
p.longestWord = c;
}
return p;
}, { max: 0, longestWord: ""}).longestWord;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment