Skip to content

Instantly share code, notes, and snippets.

@adriancooney
Created June 21, 2014 00:10
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 adriancooney/938823b96ece6fbbe29a to your computer and use it in GitHub Desktop.
Save adriancooney/938823b96ece6fbbe29a to your computer and use it in GitHub Desktop.
Javascript Proxy Madness
loop[0][2][20] = function(i) {
console.log(i);
};
// Output:
// 0
// 2
// 4
// 6
// 8
// 10
// 12
// 14
// 16
// 18
loop[5][10] = function(i) {
console.log(i);
};
// Output:
// 5
// 6
// 7
// 8
// 9
loop[10] = function(i) {
console.log(i);
};
// Output:
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
var loop = new Proxy({
u: null, // Initial condition
v: null, // Length of loop
step: null // Step
}, {
get: function(target, property) {
if(target.v === null) { // Set the length of the loop initially
target.v = parseFloat(property);
return loop;
} else if(target.u === null) { // Add a start condition
target.u = target.v;
target.v = parseFloat(property);
return loop;
} else throw new Error("Too many arguments for loop."); // The lat condition is on the set
},
set: function(target, property, callback) {
// Parse the arguments
if(target.v === null) target.v = parseFloat(property);
else if(target.u === null) target.u = target.v, target.v = parseFloat(property);
else if(target.step === null) target.step = target.v, target.v = parseFloat(property);
// Make sure the loop conditions are set
if(target.v !== null) {
// Make sure the iterator is a callback
if(typeof callback !== "function") throw new Error("Loop iterator is not a function.");
// Create the loop conditions
var u = target.u !== null ? target.u : 0,
v = target.v,
step = target.step !== null ? target.step : 1;
// Run the loop
for(var i = u; i < v; i += step) callback(i, v - u, u, v);
// Reset the options
target.u = target.v = target.step = null;
} else throw new Error("Loop conditions not set.");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment