@string001

Задачка по javaScript?

В JS новичок строго не судите!)
Есть задачка, написать функцию которая принимает слова или предложения в аргументе, и возвращает длину этого аргумента.

count("No results for search term `s`"); // 6 - длина предложения

function count(str) {
  var arr = str.split(' ');
  var someArr = arr.filter(function(e){
          return e;
    });

  return someArr.length ;
}

count("No results for search term `s`");


Сама задача!

Can you realize a function that returns word count from a given string?

You have to ensure that spaces in string is a whitespace for real.

What we want and finish of work:

countWords("Hello"); // returns 1 as int
countWords("Hello, World!") // returns 2
countWords("No results for search term `s`") // returns 6
countWords(" Hello") // returns 1


describe("countWords", function() {
  it("should work in basic form of problem", function() {
    Test.assertEquals(countWords("Hello"), 1);
    Test.assertEquals(countWords("Hello, World!"), 2);
    Test.assertEquals(countWords("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."), 19);
    Test.assertEquals(countWords(""), 0);
    Test.assertEquals(countWords("With! Symbol@ #Around! (Every) %Word$"), 5);
    Test.assertEquals(countWords("Dear   Victoria, I love  to press   space button."), 8);
  });
  
  it("should work with spaces around string", function() {
    Test.assertEquals(countWords(" Arthur "), 1);
    Test.assertEquals(countWords(" David"), 1);
    Test.assertEquals(countWords("Nelson "), 1);
    Test.assertEquals(countWords("  Hello Gomer  "), 2);
    Test.assertEquals(countWords("  Hello     Bart  "), 2);
  });
  
  it("should work with non-whitespace (ex. breakspace) chars", function() {
    Test.assertEquals(countWords("HelloWorld "), 2);
    Test.assertEquals(countWords("HelloWorld"), 2);
  });
});
// ... and so on


What kind of tests we got for your code:

Function have to count words, but not spaces, so be sure that it does right.
Empty string has no words.
String with spaces around should be trimmed.
Non-whitespace (ex. breakspace, unicode chars) should be assumed as delimiter
Be sure that words with chars like -, ', ` are counted right.
  • Вопрос задан
  • 1438 просмотров
Пригласить эксперта
Ответы на вопрос 2
khipster
@khipster
Ничего не понял. Вот тебе длина аргумента:
function count(str) {
    return str.length;
}
Ответ написан
Комментировать
@string001 Автор вопроса
Все правильно, но почему на последнее условие не работает? Вот тесты:
it("should work with non-whitespace (ex. breakspace) chars", function() {
    Test.assertEquals(countWords("HelloWorld "), 2);
    Test.assertEquals(countWords("HelloWorld"), 2);
  });
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы