var compareStr = function(str1, str2) {
if (str1.slice(1) !== str2.slice(1)) {
return false;
}
if (str1.slice(1) === '' && str2.slice(1) === '') {
return true;
}
return compareStr(str1.slice(1), str2.slice(1));
}
我正在使用递归在两个字符串参数之间创建一个比较字符串函数。我正在针对各种摩卡测试来测试我的功能。我不能特别通过这个。
AssertionError: expected 1 to be above 1
指向此代码:
it('should use recursion by calling self', function() {
compareStr('house', 'houses');
expect(compareStr.callCount).to.be.above(1);
});
现在我想发生的是,如果从第一个元素开始,str1
和str2
不相等,那么我的函数将返回false。我认为这是一个很好的例子,因为在那之后再执行该函数就没有意义了。此断言测试至少通过一次递归本身后是否在寻找false
的结果?这意味着递归至少要发生一次才能通过。
我认为测试期望您编写一个函数来比较每个字符的字符串,在这种情况下,您需要到达s
的最后houses
才能完成递归:
var compareStr = function(str1, str2) {
console.log('compareStr called');
return str1.length <= 1 || str2.length <= 1
? str1 === str2
: compareStr(str1.slice(1), str2.slice(1));
};
console.log(compareStr('house', 'houses'));