无法通过递归函数的断言测试

问题描述 投票:1回答:1
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);
  });

现在我想发生的是,如果从第一个元素开始,str1str2不相等,那么我的函数将返回false。我认为这是一个很好的例子,因为在那之后再执行该函数就没有意义了。此断言测试至少通过一次递归本身后是否在寻找false的结果?这意味着递归至少要发生一次才能通过。

javascript recursion mocha
1个回答
1
投票

我认为测试期望您编写一个函数来比较每个字符的字符串,在这种情况下,您需要到达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'));
© www.soinside.com 2019 - 2024. All rights reserved.