Skip to content

Instantly share code, notes, and snippets.

@user24
user24 / gist:1188669
Created September 2, 2011 14:06
Revealing Module Pattern
// Define an object using the Revealing Module Pattern
var myCounter = function() {
// Both Private and Public methods and properties are defined here
var counter = 0;
function count() {
return 0+counter;
}
@user24
user24 / gist:1189300
Created September 2, 2011 17:55
Node memory leak?
var foo = [];
setInterval(function() {
foo.push(Math.random());
if(foo.length > 200) {
foo = foo.slice(-200);
}
console.log(foo.length);
}, 10);
@user24
user24 / gist:1201439
Created September 7, 2011 19:16
Async Loop Pitfall
// the following code outputs: 999999999
var someArray = [1,2,3,4,5,6,7,8,9];
for(var i=0 ; i<someArray.length ; i++) {
performSomeAsyncOperation("foo", function hereIsACallback() {
console.log(someArray[i]);
});
}
@user24
user24 / gist:1201490
Created September 7, 2011 19:33
Various For Loop Patterns
var i=0;
// 01234
for(i=0 ; i<5 ; i++) {
console.log('standard for loop', i);
}
// 55555
for(i=0 ; i<5 ; i++) {
setTimeout(function() {
@user24
user24 / option1.js
Created November 27, 2011 16:36
various code style options
var handling = false;
window.onSomeEvent = function handleEvent() {
if(handling) return;
handling = true;
/* some other handler code here which eventually switches handling off again */
};
var hasMultipleArgs = args.length > 1;
var argIsString = typeof arg == 'string';
var argIsSentence = ~arg.indexOf(' ');
var argIsFormattingOption = ~arg.indexOf('%');
if (hasMultipleArgs && argIsString && !argIsSentence && !argIsFormattingOption) { /*...*/ }
// see https://github.com/observing/devnull/blob/master/lib/logger.js#L364-367 for alternative style
<html>
<head>
<script>
function foo() {
alert('bar');
}
document.onclick = foo;
</script>
Object.prototype.foo = 4;
var bar = {};
bar.baz = 5;
for(var prop in bar) {
console.log(prop);
}
/*
logs:
function fitness(chromosome){
// higher fitness is better
var f = 0; // start at 0 - the best fitness
for(var i=0, c=target.length ; i<c ; i++) {
// subtract the ascii difference between the target char and the chromosome char
// Thus 'c' is fitter than 'd' when compared to 'a'.
f -= Math.abs(target.charCodeAt(i)-chromosome[i]);
}
return f;
}
<?php
class Foo {
public function __call($func, $args) {
if(method_exists($this,$func)) {
return call_user_func_array(array($this,$func),$args);
}
}
}