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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With