Created
January 12, 2015 04:11
-
-
Save YanivHaramati/8ea73333bbc3c2c554a5 to your computer and use it in GitHub Desktop.
Longest word in a sentence in terms of reduce
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
// 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