Wednesday, October 26, 2011

This weekend I got round to writing a Google Chrome extension that aids you in plotting graphs from Wolfram|Alpha. The extension simply takes the parameters you input, constructs a url to Wolfram|alpha and then opens a new tab with that url.

Sunday, October 2, 2011

The following is an implementation for a state manager written in JavaScript. More than one state can be "on" at one moment but mutual exclusivity rules can be set up to allow certain states to not be "on" at the same time i.e. if one of the states is switched on while the other is already on, the latter will be switched off since they can't be both on at the same time.

It also supports two hooks which can be used if you want to be notified when states are changed.

Mutual Exclusivity

var state = stateManager();
state.mutex("state 1", "state 3"); // "state 1" and "state 2" now cannot be both on at the same time
state.mutex("state 2", "state 3"); // "state 2" and "state 3" now cannot be both on at the same time
state.turnOn("state 1");
state.turnOn("state 3"); // "state 1" will now be turned off since 1 and 3 are mutually exclusive
state.turnOn("state 1"); // turning "state 1" on, but switching "state 3" off for the same reason
state.turnOn("state 2"); // if "state 3" was on at this point, it would have been switched off

state 1 is now 1
[Custom hook] state 1 has been changed. New value: 1
state 3 is now 1
state 2 is now 1
state 1 is now 0
[Custom hook] state 1 has been changed. New value: 0

Note that the onStateChanged event fires only when a state changes. For example, if you turnOn("state 2") while "state 2" is already on, the event will not fire. The same goes for when a state is off and you try to turnOff.

Saturday, October 1, 2011

Function composition is the application of a result of a function as input to another function. Say we have the following three functions:

Composing functions f, g and h respectively means that we pass the output from function h as the input to function g and then passing the output from g as the input to function f. Mathematically, it would be represented as follows:

That's essentially the same as:

Functions in JavaScript are first class citizens. This means that they can be stored in variables and data structures, passed as an argument to functions and also returned from functions. This means that we can easily implement function composition in JavaScript with a very trivial function: