Nifty JavaScript Experiments
I don't know about you, but I'm a fan of messing about with a language to see what I can do with it! Here I list a set of my personal JavaScript experiments. Each one has a specific goal it wishes to accomplish and an example of how I want to use the result.
Descriptions of implementations are coming soon!
“Allow multiple implementations of a function for different input”
Aim:
“Allow multiple implementations of a function based on different arguments. e.g. if you want different code to run if a function is called with an Array as opposed to an Object.”
Expected Usage:
var myFn = new MultiFn({
".* .*": function (_n1, _n2) { return myFn(_n1) + myFn(_n2); },
"Number": function (_num) { return _num; },
"String": function (_str) { return parseInt(_str, 10); },
"default": function () { return 0; }
});
myFn(); // -> 0 (default)
myFn([]); // -> 0 (default: no array implementation)
myFn(3); // -> 3 (Number)
myFn("9"); // -> 9 (String)
myFn(8, 2); // -> 10 (.* .*: Any Any)
myFn("6", 2); // -> 8 (.* .*: Any Any)
MultiFn implementation on GitHub/LiamGoodacre/MultiFn.js
“Listen for changes in an object’s properties.”
Aim:
“Allow callbacks for property change events on an object.”
Expected Usage:
var obj = { a: 2 };
PEL.makeListenable(obj, 'a');
PEL.listen(obj, 'a', function (_data) {
console.log('Heard obj.a change! old: %d, new: %d', _data.old, _data.new);
});
obj.a = 3; // -> Heard obj.a change! old: 2, new: 3
PEL implementation on GitHub/LiamGoodacre/PEL.js
“The idea for this came from aiding a friend who wished to do something similar (although he never used it…).”
Aim:
“Provide a mechanism for appending functions to others, retaining access to all chained functions. Evaluating a Function Chain variable, should invoke each appended function in order. Extra functionality could include the removal of functions and the ability to clone and extend exiting chains.”
Expected Usage:
var myFunc = new FnChain(function () {
console.log('Original Function.');
});
myFunc(); // -> Original Function
myFunc.append(function () {
console.log('Appended Function.')
});
myFunc(); // -> Original Function
// Appended Function
myFunc[0](); // -> Original Function
myFunc[1](); // -> Appended Function
var myFunc2 = myFunc.extend(function () {
console.log('myFunc2');
});
myFunc2(); // -> Original Function
// Appended Function
// myFunc2
myFunc(); // -> Original Function
// Appended Function
myFunc.size(); // -> 2
FnChain implementation on GitHub/LiamGoodacre/FnChain.js