Your code is good, but it could be improved:
findLongestWord
: You actually just find the length, I would title it findLongestWordLength
instead, or make it return the word.
- As SirPython points out, you should add the ability to use a custom delimiter.
- If you attached this function to the
String
prototype, you'd find that this function would look a lot simpler:
String.prototype.findLongestWordLength = function(){
//...
}
"Lorem Ipsum...".findLongestWordLength();
Inside prototype
chains attached to primitive types, you can access the parent object, which in this case would be "Lorem Ipsum..."
with this
, however, this
only has a getter property, you cannot reassign this
, however, you can assign properties to this
.
You don't need to use for ... in
, I would avoid using it. Personally, I usually use forEach
and normal for
loops only.
However, like Charlie says, you can simply sort the array.
String.prototype.findLongestWord = function(delimiter){
delimiter = delimiter || " ";
return this.split(delimiter).sort(function(a, b){
return b.length - a.length;
})[0];
}
This example would return the word, whereas if you added .length
after [0]
, it would return the length.
Adding to String.prototype
is one method, however as @SirPython, @JosephTheDreamer and @DanPantry point out in the comments, you shouldn't add to prototype
s of vendor types unless you really know what you're doing, as it makes your code really hard to maintain in terms of backwards and forward compatibility.
It's probably better to add the string
as a parameter. (Make sure it's passed in first, JavaScript has optional parameters)
Additionally, in this case, you should throw an error if it's not passed in the function.
function findLongestWord(string, delimiter){
if (!string){ throw new Error("String needed"); }
delimiter = delimiter || " ";
return this.split(delimiter).sort(function(a, b){
return b.length - a.length;
})[0];
}
for(let i=0; i<arr.length(); ++i) { let s = arr[i]; if(s.length>size) ... }
? \$\endgroup\$arr.sort(s=>s.length)[0].length;
(sort by length of string, get shortest string, get length) orarr.map(s=>s.length).sort()[0];
(make new array with lengths of strings in arr, sort that array, get shortest size) \$\endgroup\$