[英]TDD and re-creating underscore functions
So I'm getting an error on the last test: "Assertion failed:", should produce a brand new array instead of modifying the input array. 因此,我在上一个测试中遇到了一个错误:“断言失败:”,应该产生一个全新的数组,而不是修改输入数组。
I thought I was creating a new array but I'm unsure of what the test is wanting. 我以为我要创建一个新的数组,但不确定测试需要什么。 Is it saying I need to create a new empty array and then push the correct values into the new array? 是说我需要创建一个新的空数组,然后将正确的值推入新数组吗? I don't see whats wrong with the way I'm doing it now, but it seems to want me to do something else. 我看不到我现在的操作方式有什么问题,但是似乎要我做其他事情。
_.uniq = function(array) {
var newArray = array;
_.each(newArray, function(val,i){
for(var j = 0; j < newArray.length; j++)
if(val === newArray[j] && i !== j){
array.splice(j,1);
}
})
return newArray;
}
Test: 测试:
describe('uniq', function() {
it('should return all unique values contained in an unsorted array', function() {
var numbers = [1, 2, 1, 3, 1, 4]
expect_equal(_.uniq(numbers), [1, 2, 3, 4])
})
it('should handle iterators that work with a sorted array', function() {
var iterator = function(value) { return value + 1 }
var numbers = [1, 2, 2, 3, 4, 4]
expect_equal(_.uniq(numbers, true, iterator), [1, 2, 3, 4])
})
it('should produce a brand new array instead of modifying the input array', function() {
var numbers = [1, 2, 1, 3, 1, 4]
var uniqueNumbers = _.uniq(numbers)
console.assert(uniqueNumbers !== numbers)
})
})
ended up solving it with this: 最终解决了这个问题:
_.uniq = function(array) {
var newArray = [];
_.each(array, function(val){
newArray.push(val);
})
_.each(newArray, function(val,i){
for(var j = 0; j < newArray.length; j++)
if(val === newArray[j] && i !== j){
newArray.splice(j,1);
}
})
return newArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.