Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
:
or ;
-
or ~
)
or D
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.
library(tidyverse)
<- function(array) {
countSmileys # str_detect() 支持向量化操作
str_detect(array, "[:;][-~]?[)D]") %>%
sum()
}
library(testthat)
test_that("Sample Tests", {
expect_equal(countSmileys(c(":)", ";(", ";}", ":-D")), 2)
expect_equal(countSmileys(c(";D", ":-(", ":-)", ";~)")), 3)
expect_equal(countSmileys(c(";]", ":[", ";*", ":$", ";-D")), 1)
})
#> Test passed 🎊
/**
* smiley face checker
* @param {String} str
* @returns {Boolean} the parameter is a smiley face or not
*/
function isSmileyFace(str) {
return /^[:;][-~]?[)D]/.test(str);
}
/**
* smiley face counter
* @param {Arrary} arr string array
* @returns {integer} total number of smiling faces in the array
*/
function countSmileys(arr) {
return arr.filter(isSmileyFace).length;
}
.exports = countSmileys; module