问题
I am currently on a task in python and i need help with this and i am to
Write a function called longest which will take a string of space separated words and will return the longest one.
For example:
longest("This is Andela") => "Andela"
longest("A") => "A"
This is the sample test
const assert = require("chai").assert;
describe("Module 10 - Algorithyms", () => {
describe("longest('This Is Andela')", () => {
let result = longest("This Is Andela");
it("Should return 'Andela'", () => {
assert.equal(result, 'Andela');
});
});
describe("longest('This')", () => {
let result = longest("This");
it("Should return 'This'", () => {
assert.equal(result, 'This');
});
});
describe("longest(23)", () => {
let result = longest(23);
it("Should return ''", () => {
assert.equal(result, '');
});
});
});
This is what i have tried
function longest(str) {
str = "This is Andela";
var words = str.split(' ');
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
return longest;
}
But my code seem to only pass the first test case.Please what do i need to change to pass the other two first case considering i am new to javascript
回答1:
You need to remove this line in your function:
str = "This is Andela";
You function should be (added check if str is string):
function longest(str) {
if(typeof str !== 'string') return '';
var words = str.split(' ');
var longest = '';
for (var i = 0; i < words.length; i++) {
if (words[i].length > longest.length) {
longest = words[i];
}
}
return longest;
}
回答2:
Simplified code with no arrays and no each statements.
function longer(champ, contender) {
return (contender.length > champ.length) ? contender: champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord('This is longest'));
console.log(longestWord('This is longest or may this is more longestest'));
回答3:
Check this one:
function longest(s){
return typeof s != 'string' ? '' : s.split(' ').sort( (a,b) => b.length - a.length)[0]
}
The input is converted into string through concatenation with an empty string so that it works when a number is passed as well.
来源:https://stackoverflow.com/questions/44111701/find-longest-word-in-string-javascript