Skip to content

Instantly share code, notes, and snippets.

@mcrumley
mcrumley / array_partition.php
Created April 10, 2014 15:56
Partition an array into approximately equal-sized chunks
<?php
/**
* Partition an array into N chunks
*
* @param array $a array to split
* @param int $np number of partitions
* @param bool $pad pad the result with empty arrays if necessary (default = true)
*
* @return array the original array split into $np chunks
@mcrumley
mcrumley / Map.php
Created November 6, 2013 19:51
PHP Map object
<?php
/*
EXAMPLES:
$map = new Map(array('foo' => 'bar', 'baz' => 'quux'));
$map = $map->withDefaultValue('default value');
$map = $map->withDefault('strtoupper');
var_dump($map->apply(array('foo', 'baz', 'quux'))); // bar, quux, QUUX
var_dump(array_map($map, array('foo', 'baz', 'quux'))); // bar, quux, QUUX
@mcrumley
mcrumley / cache_buster.js
Created June 3, 2013 18:21
Gets a unique URL to avoid browser cache
function cache_buster(url) {
cache_buster.nonce = cache_buster.nonce || 1;
var sep = "?";
var qpos = url.indexOf("?");
if (url.length === 0 || qpos === url.length-1) {
sep = "";
} else if (qpos >= 0) {
sep = "&";
}
return url + sep + "nocache=" + (new Date()).getTime() + "-" + cache_buster.nonce++;
@mcrumley
mcrumley / hex2bin.php
Created May 29, 2013 18:34
hex2bin replacement for PHP < 5.4
<?php
if (!function_exists('hex2bin')) {
function hex2bin($str) {
$map = array(
'00'=>"\x00", '10'=>"\x10", '20'=>"\x20", '30'=>"\x30", '40'=>"\x40", '50'=>"\x50", '60'=>"\x60", '70'=>"\x70",
'01'=>"\x01", '11'=>"\x11", '21'=>"\x21", '31'=>"\x31", '41'=>"\x41", '51'=>"\x51", '61'=>"\x61", '71'=>"\x71",
'02'=>"\x02", '12'=>"\x12", '22'=>"\x22", '32'=>"\x32", '42'=>"\x42", '52'=>"\x52", '62'=>"\x62", '72'=>"\x72",
'03'=>"\x03", '13'=>"\x13", '23'=>"\x23", '33'=>"\x33", '43'=>"\x43", '53'=>"\x53", '63'=>"\x63", '73'=>"\x73",
'04'=>"\x04", '14'=>"\x14", '24'=>"\x24", '34'=>"\x34", '44'=>"\x44", '54'=>"\x54", '64'=>"\x64", '74'=>"\x74",
@mcrumley
mcrumley / jquery.placeholder.js
Created May 20, 2013 21:11
HTML 5 placeholder support for older browsers.
(function($) {
var defaults = {
className: "placeholder"
};
if ("placeholder" in document.createElement("input")) {
$.fn.placeholder = function(){ return this; };
} else {
$.fn.placeholder = function(options){
options = $.extend({}, defaults, options);