Skip to content

Instantly share code, notes, and snippets.

View eliperelman's full-sized avatar

Eli Perelman eliperelman

View GitHub Profile
@eliperelman
eliperelman / example.js
Created July 6, 2011 03:33
Speedy Loops
var arr = ['apple', 'banana', 'cheese', 'donut', 'egg', 'fish'];
var send = function (item) {
$.ajax({
type: 'post',
dataType: 'json',
url: '/Foods/Consume',
data: { food: item }
});
};
@eliperelman
eliperelman / example.js
Created July 6, 2011 03:47
Unlimited arguments
// Antipattern:
var preload = function (path) {
var img = new Image();
img.src = path;
};
preload('apple.png');
preload('banana.png');
preload('cheese.png');
@eliperelman
eliperelman / example.js
Created July 6, 2011 04:11
Revealing Module pattern
var App = (function() {
var module1 = {
method1: function() {
// code here
}
};
var module2 = {
ajax: $.ajax
@eliperelman
eliperelman / example.js
Created July 6, 2011 02:50
Comparing against undefined
var value;
// Antipattern:
if (value === undefined) {
// code here
}
// Good pattern:
@eliperelman
eliperelman / example.js
Created July 6, 2011 03:02
Building strings
// String concatenation
var stringBuilder = '';
for (var i = 0, len = 30; i < len; i++) {
stringBuilder += 'word' + i;
}
console.log(stringBuilder);
@eliperelman
eliperelman / example.js
Last active September 26, 2015 08:08
Guaranteed Instances
var Car = function(make, model, color) {
this.make = make;
this.model = model;
this.color = color;
};
// This way works:
var pinto = new Car('ford', 'pinto', 'green');
// but this doesn't:
var pinto = Car('ford', 'pinto', 'green');
var factoryAdder = function(initialValue) {
// this function "closes over" initialValue,
// effectively sealing it into the context
return function(numberToAdd) {
return initialValue + numberToAdd;
};
};
var add5 = factoryAdder(5);
console.log(add5(7)); // logs 12
@eliperelman
eliperelman / example.js
Created July 6, 2011 04:08
Module/Namespacing/Singleton pattern
var Namespace = {};
Namespace.module1 = {
method1: function() {
// code here
}
};
Namespace.module2 = {
method2: function() {
@eliperelman
eliperelman / index.html
Created November 2, 2011 03:23
jQuery Deferreds and Promises Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Deferreds and Promises</title>
</head>
<body>
<div class="container">
<form method="get" action="http://search.twitter.com/search.json">
<input type="search" class="search">
<input type="submit" value="Search teh Tweets!" class="submit">
@eliperelman
eliperelman / HttpError.js
Created January 5, 2012 16:57 — forked from unscriptable/HttpError.js
Example "subclass" of Error object
define(function () {
var HttpError = function (msg, code) {
var ex = new Error(msg || 'Unknown HTTP error');
ex.code = code;
ex.toString = function() {
return 'Error: '
+ (this.code ? '' : '(' + this.code + ') ')
+ this.message;
};