JSFiddle - React, Tailwind, and code Playground
JavaScript
var log = function (result) {
document.querySelector('pre').innerText += result + '\r';
};
var logJson = function (result) {
document.querySelector('pre').innerText += JSON.stringify(result, null, 2) + '\r\r';
};
var memoize = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
var hash = '';
var i = args.length;
var currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ? JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize = {});
}
return (hash in fn.memoize) ? fn.memoize[hash] : fn.memoize[hash] = fn.apply(this, args);
};
};
// Implementation
var list = [
{ id: 'foo' },
{ id: 'bar' },
];
// Bug is in this function.
var setActive = function (id, list) {
return list.map(function (item) {
item.active = item.id === id;
return item;
});
};
var memSetActive = memoize(setActive);
// Output
log('Set foo as active');
logJson(memSetActive('foo', list));
log('Set bar as active');
logJson(memSetActive('bar', list));
log('Set foo as active');
logJson(memSetActive('foo', list));
log('Set bar as active');
logJson(memSetActive('bar', list));
log('Woah, that didnt work did it?');