Kata Array Helpers
/* jshint node: true */
var assert = require("chai").assert;
var origNumbers = [1, 2, 3, 4, 5];
var numbers = [1, 2, 3, 4, 5];
/*
* square each item in array
*
* @return {Array}
*/
Array.prototype.square = function() {
return this.map(function(n, i) {
return n*n;
});
};
/*
* cube each item in array
*
* @return {Array}
*/
Array.prototype.cube = function() {
return this.map(function(n, i) {
return n*n*n;
});
};
/*
* add all items in array
*
* @return {Number}
*/
Array.prototype.sum = function() {
return this.reduce(function(p, c) {
return p + c;
}, 0);
};
/*
* averages all items in array
*
* @return {Number}
*/
Array.prototype.average = function() {
return this.sum() / this.length;
};
/*
* return only even numbers
*
* @return {Array}
*/
Array.prototype.even = function() {
return this.filter(function(n, i) {
return (n % 2) === 0;
});
};
/*
* return only odd numbers
*
* @return {Array}
*/
Array.prototype.odd = function() {
return this.filter(function(n, i) {
return (n % 2) !== 0;
});
};
describe("array", function() {
function assertDoesNotAffectOriginalArray() {
it("does not affect the original array", function() {
assert.deepEqual(numbers, origNumbers);
});
}
describe("#square", function() {
var squared;
beforeEach(function() {
squared = numbers.square();
});
it("squares each number in the array", function() {
assert.deepEqual(squared, [1, 4, 9, 16, 25]);
});
assertDoesNotAffectOriginalArray();
});
describe("#cube", function() {
var cubed;
beforeEach(function() {
cubed = numbers.cube();
});
it("cubes each number in the array", function() {
assert.deepEqual(cubed, [1, 8, 27, 64, 125]);
});
assertDoesNotAffectOriginalArray();
});
describe("#sum", function() {
it("adds all the items in the array", function() {
assert.equal(numbers.sum(), 15);
});
});
describe("#average", function() {
it("averages all the items in the array", function() {
assert.equal(numbers.average(), 3);
});
});
describe("#even", function() {
var evens;
beforeEach(function() {
evens = numbers.even();
});
it("returns only the even numbers", function() {
assert.deepEqual(evens, [2, 4]);
});
assertDoesNotAffectOriginalArray();
});
describe("#odd", function() {
var odds;
beforeEach(function() {
odds = numbers.odd();
});
it("returns only the odd numbers", function() {
assert.deepEqual(odds, [1, 3, 5]);
});
assertDoesNotAffectOriginalArray();
});
});