Test-driven development exercise
Recreating array methods and testing them
by ShaCP
HTML
<script id="tinyTest">
var TinyTest = {
run: function(tests) {
var failures = 0;
for (var testName in tests) {
var testAction = tests[testName];
try {
testAction.apply(this);
console.log('Test:', testName, 'OK');
} catch (e) {
failures++;
console.error('Test:', testName, 'FAILED', e);
console.error(e.stack);
}
}
setTimeout(function() { // Give document a chance to complete
if (window.document && document.body) {
document.body.style.backgroundColor = (failures == 0 ? '#99ff99' : '#ff9999');
}
}, 0);
},
fail: function(msg) {
throw new Error('fail(): ' + msg);
},
assert: function(value, msg) {
if (!value) {
throw new Error('assert(): ' + msg);
}
},
assertEquals: function(expected, actual) {
if (expected != actual) {
throw new Error('assertEquals() "' + expected + '" != "' + actual + '"');
}
},
assertStrictEquals: function(expected, actual) {
if (expected !== actual) {
throw new Error('assertStrictEquals() "' + expected + '" !== "' + actual + '"');
}
},
};
var fail = TinyTest.fail.bind(TinyTest),
assert = TinyTest.assert.bind(TinyTest),
assertEquals = TinyTest.assertEquals.bind(TinyTest),
eq = TinyTest.assertEquals.bind(TinyTest), // alias for assertEquals
assertStrictEquals = TinyTest.assertStrictEquals.bind(TinyTest),
tests = TinyTest.run.bind(TinyTest);
</script>
<script id="adder">
function add(a, b) {
return a + b;
}
</script>
<script id="custom-filter-function">
function filter(array, callback, optionalThisObject) {
var filterCallback = callback;
if (optionalThisObject) filterCallback = callback.bind(optionalThisObject);
var filteredArray = [];
for (var index = 0; index < array.length; index++) {
var filterResult = filterCallback(array[index], index,...
JavaScript
/*When the code is run, a green background means all tests passed. To see the custom tests I created, refer to the HTML script element with id "custom-tests-(name of function)", e.g., "custom-tests-filter". To see the custom function code I created, refer to the HTML script element with id "custom-(name of function)-function", e.g., "custom-filter-function". The functions I included here are forEach, filter, map and reduce.
I also added below some simple cases of my custom functions in action.
*/
var filteredArray = filter([1, 2, 3, 4, 5], function(e) {
return this + e < 5
}, 1)
document.body.innerHTML = "filteredArray = " + filteredArray + "<br>"
var forEachResultsArray = []
forEach([1, 2, 3, 4, 5], function(e, i) {
forEachResultsArray[i] = this + e
}, 1);
document.body.innerHTML += "forEachResult = " + forEachResultsArray + "<br>"
var mappedArray = map([1, 2, 3, 4, 5], function(e) {
return this + e
}, 10)
document.body.innerHTML += "mappedArray = " + mappedArray + "<br>"
var reducedArray = reduce([1, 2, 3, 4, 5], function(total, e) {
return total + e
}, 100)
document.body.innerHTML += "reducedArray = " + reducedArray