Skip to content

Instantly share code, notes, and snippets.

@bjdixon
bjdixon / isType.js
Last active September 10, 2015 20:57
type checking for bool, string and number
var isBoolean = is('Boolean'),
isNumber = is('Number'),
isString = is('String'),
isObject = is('Object'),
isArray = is('Array');
function is(type) {
var fastTypes = ['undefined', 'boolean', 'string', 'number', 'function', 'symbol'];
if (fastTypes.indexOf(type.toLowerCase()) >= 0) {
type = type.toLowerCase();
@bjdixon
bjdixon / partial.js
Last active September 14, 2015 20:00
partial and findIndex
function partial (fn) {
var initialArgs = Array.prototype.slice.call(arguments, 1);
return function () {
var remainingArgs = Array.prototype.slice.call(arguments);
return fn.apply({}, initialArgs.concat(remainingArgs));
}
}
function findIndex(arr, predicate) {
var i;
@bjdixon
bjdixon / compact.js
Created September 8, 2015 20:47
take an array and return an array with falsy values removed
function compact(a) {
return a.reduce(function(memo, x) {
return x ? memo.concat(x) : memo;
}, []);
}
@bjdixon
bjdixon / flatten.js
Created August 21, 2015 15:26
flatten an array es5
function flatten(a) {
return a.map(function(val) {
return (Array.isArray(val)) ? flatten(val) : val;
});
}
//example usage
var arr = [1, 2, [3, 4], 5, [6, [7, [8]], 9], 10];
var flat = flatten(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
@bjdixon
bjdixon / queue.js
Created July 30, 2015 17:39
Queue in javascript
const Queue = () => {
let array = [];
return {
push: (value) => array.push(value),
pull: () => array.shift(),
isEmpty: () => !array.length
};
};
@bjdixon
bjdixon / model.js
Created July 30, 2015 16:34
A Model with undo and redo stacks
const copyObject = (source) => Object.assign({}, source);
const Stack = () => {
const array = [];
return {
push (value) {
array.push(value);
},
pop () {
@bjdixon
bjdixon / memo.js
Last active August 29, 2015 14:26
Memoize a function
memo = function (fn) {
var cache = {};
return function () {
var key = JSON.stringify(this, arguments);
return cache[key] || (cache[key] = fn.apply(this, arguments));
}
}
@bjdixon
bjdixon / combinators.js
Last active August 29, 2015 14:25
Combinators in JavaScript (ES6)
// Kestrel
const K = ( x ) => ( y ) => x;
// Identity
const I = ( x ) => x;
// Vireo
const V = ( x ) => ( y ) => ( z ) => z( x )( z );
// Thrush
const T = ( x ) => ( y ) => y( x ), x;
// Why
const Y = ( x ) => ( ( y ) => y( y ) )( ( y ) => ( x( ( z ) => y( y )( z ) ) ) );
@bjdixon
bjdixon / list_events.js
Created June 3, 2015 00:38
List all events registered to a particular element
$._data( $(selector)[0], "events" );
@bjdixon
bjdixon / jquery.exists
Created April 27, 2015 13:17
Extend jquery with function to check if an element exists
//extend jquery with function to check if element exists
$.fn.exists = function(){
return this.length > 0 ? this : false;
}
//usage
$('.matchme').exists(); //returns reference to element if exists otherwise false