Skip to content

Instantly share code, notes, and snippets.

View petrosalema's full-sized avatar

Petro Salema petrosalema

View GitHub Profile
@petrosalema
petrosalema / max_challenge.js
Created July 14, 2011 23:58
JavaScript Max Challenge
/**
* JavaScript Max Challenge:
* A function that returns the greater of 2 numbers
* without using math.min, math.max, >, <, ==, !=
*
* ie:
* given a > b
* assert max(a, b) == a
*
* Solution:
@petrosalema
petrosalema / subtle_error.js
Created July 13, 2011 21:12
What is the problem with this valid JavaScript?
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var order = "desc";
alphabet.sort(function (a, b) {
return
a == b
? 0
: (order == "desc" ? -1 : 1)
* (a < b ? -1 : 1);
});
@petrosalema
petrosalema / name_your_anonymous_functions.js
Created June 22, 2011 10:32
I think it should be best practice to name immediately invoked functions (often anonymous), here's why...
// Execute this and look at your console errors.
// this ...
(function __I_HAVE_A_NAME_NOW__ () {
// deliberate error
catchMeIfYouCan();
})();
// ... debugs far better this anonymous function
@petrosalema
petrosalema / typecheck.js
Created June 21, 2011 21:59
typecheck: Better alternative to JavaScript's typeof operator
// Uber typeof:
// Since null, in JavaScript, is an object with an unknown value,
// typeof null == 'object' is technically correct.
// Nevertheless, JavaScript's typeof operator could be much more helpful
// than it is.
function typecheck (obj) {
var type;
// faster than if/else
switch (obj) {