Skip to content

Instantly share code, notes, and snippets.

@harmenjanssen
harmenjanssen / findInDomAncestry.js
Last active September 22, 2018 18:53
Walk up a DOM tree and return the matching element.
const findInDomAncestry = predicate => node =>
typeof node.nodeType === 'undefined' || node.nodeType === Node.DOCUMENT_NODE
? undefined
: predicate(node)
? node
: findInDomAncestry(predicate)(node.parentNode);
/*
Example usage:
@harmenjanssen
harmenjanssen / reverse.js
Last active August 20, 2017 11:57
Recursive reverse function.
const reverse = ([head, ...rest]) =>
!head ? [] : reverse([...rest]).concat([head]);
@harmenjanssen
harmenjanssen / isEven.js
Created August 20, 2017 10:56
Recursive is-even function. A classic.
const isEven = n => n === 0 ?
true :
!isEven(n - 1);
@harmenjanssen
harmenjanssen / recursive-to-object.js
Last active August 12, 2017 20:16
Generate object from array of keys and array of values, recursively.
const toObj = (keys, values, index = keys.length - 1) =>
typeof keys[index] === "undefined"
? {}
: Object.assign(
toObj(keys, values, index - 1),
{
[keys[index]]: values[index]
}
);
const sum = (collection, runningTotal = 0) =>
!collection.length ?
runningTotal :
sum(collection.slice(1), collection[0] + runningTotal);
const range = (max, n = 0) =>
n >= max ?
[] :
[n].concat(range(max, n+1));
@harmenjanssen
harmenjanssen / divide_functional.js
Created April 6, 2017 22:16
Divide an array into segments.
/**
* Sexy functional bits
* ----------------------------------------------------
*/
const range = max => Array.apply(null, Array(max)).map((_, i) => i);
const slice = (xs, index, size) => xs.slice(index, index + size);
const segmentSize = (len, iteration, segments) =>
Math.ceil((len - iteration) / segments);
<?php
/**
* Extract a substring from $input centered around $search with a maximum of $maxLength chars.
*
*
* @param string $input
* @param string $search The substring to search for.
* @param int $maxLength Maxlength of the excerpt, including delimiters.
* @param string $delimiter Character used to denote a break at the front or end of the excerpt.
* @return string
@harmenjanssen
harmenjanssen / parameterizeJqCallback.js
Created November 15, 2016 12:33
Small utility if you like to use jQuery but not so much its this-scoped callbacks.
/**
* Usage:
* $('.my-nodes').each(parameterizeJqCallback(myFunction));
*
*/
const parameterizeJqCallback = (fn) => function(...args) {
return fn($(this), ...args);
};
@harmenjanssen
harmenjanssen / home.ejs
Last active June 30, 2016 10:12
Reduced test-case showing the problem with sharing routes between Router instances
<p>This is the homepage.</p>
<a href="<% url('home') %>">A link to myself</a>
<!--
This will throw an error: "No route found with the name:home"
-->