Skip to content

Instantly share code, notes, and snippets.

@richardharrington
Created July 15, 2014 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardharrington/545f816b447755bf236e to your computer and use it in GitHub Desktop.
Save richardharrington/545f816b447755bf236e to your computer and use it in GitHub Desktop.
var assert = require('assert')
// Underscore and/or lo-dash are great
// utility libraries that abstract lots of cruft
// from javascript code. That said,
// there may be times when including a library
// isn't feasible in a project. Let's dig into
// some of the most valuable methods in the project
// and put together our own version.
var _ = {
// go over each item is list, running iterator
each: function(list, iterator, context) {
},
// produce new array from list run through iterator
map: function(list, iterator, context) {
},
// return a list sorted by iterator
sortBy: function(list, iterator, context) {
},
// creates function only callable once
once: function(fn) {
},
// produce a fn only callable once during wait interval (ms)
throttle: function(fn, wait) {
}
};
// tests
var array, fn, createCountFn;
console.log('_.each performs iterator on all input');
array = [];
_.each([1, 2, 3], function(n) {
array.push(n);
});
assert.deepEqual(array, [1, 2, 3]);
console.log('_.map returns an array of mapped input');
array = _.map([1, 2, 3], function(n) {
return n + 1;
});
assert.deepEqual(array, [2, 3, 4]);
console.log('_.sortBy sorts by criteria');
array = _.sortBy([{name: 'sally'}, {name : 'bob'}], function(obj) {
return obj.name;
});
assert.deepEqual(array, [{name : 'bob'}, {name : 'sally'}]);
console.log('_.sortBy does not mutate input');
array = ['b', 'a'];
_.sortBy(array, function(character) {
return character;
});
assert.deepEqual(array, ['b', 'a']);
// Next three tests use createCountFn
createCountFn = function(count) {
return function() {
count++;
return count;
}
};
console.log('_.once produces a function only callable once');
fn = _.once(createCountFn(0));
fn();
assert.equal(fn(), 1);
console.log('_.throttle calls only once per given amount of milliseconds')
fn = _.throttle(createCountFn(0), 50);
fn();
assert.equal(fn(), 1);
console.log('_.throttle calls again if you wait until its throttling limit is up');
fn = _.throttle(createCountFn(0), 50);
fn();
setTimeout(function() {
assert.equal(fn(), 2)
}, 100)
console.log('ALL TESTS PASS');
// Improvements: test context; _.each for objects{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment