Skip to content

Instantly share code, notes, and snippets.

View dana-ross's full-sized avatar

Dana Ross dana-ross

View GitHub Profile
<?php
use DaveRoss\FunctionalProgrammingUtils\Just as Just;
$f = function( $value ) {
$retval = $value + 2;
$value = 5; // Who cares?
return $retval;
};
<?php
/**
* Return the object's value + 2
*/
function f( $obj ) {
$retval = $obj->value + 2;
$obj->value = 5; // EVIL!
return $retval;
}
@dana-ross
dana-ross / comment-hash.php
Last active January 6, 2016 17:18
Example of a WordPress plugin written in a point-free style using PHP Functional Programming Utils
<?php
/*
Plugin Name: Comment Hash
Description: Sign comments with a sha256 hash to prevent tampering
Author: Dave Ross
Version: 1.0
Author URI: http://davidmichaelross.com/
*/
function busy_work( $value ) {
$sha256 = partially_apply( 'hash', 'sha256' );
$retval = $value;
for( $i = 0; $i < 1000; $i++ ) {
$retval = $sha256( $retval );
}
return $retval;
}
function render_subhead_meta_box() {
echo 'This is my meta box';
}
// This is equivalent to:
// add_meta_box( 'subhead', 'Article Subhead', 'render_subhead_meta_box' )
$add_meta_box_subhead = curry( 'add_meta_box', 'subhead' );
$add_meta_box_subhead_with_title = $add_meta_box_subhead( 'Article Subhead' );
$add_meta_box_subhead_with_title( 'render_subhead_meta_box' );
$add_the_content_filter = partially_apply( 'add_filter', 'the_content' );
function reverse_the_content( $content ) {
return strrev( $content );
}
$add_the_content_filter( 'reverse_the_content' );
/**
* Convert a value to non-negative integer.
*
* @since 2.5.0
*
* @param mixed $maybeint Data you wish to have converted to a non-negative integer.
* @return int A non-negative integer.
*/
$absint = compose( 'abs', 'intval' );
@dana-ross
dana-ross / capitalize_the_post_title.php
Created January 3, 2016 15:00
Demonstrates a pure function and a wrapper to deal with impurities
/**
* Wrapper to deal with global state and pass it to a pure function
* IMPURE - references global $post
* @return string
*/
function capitalize_the_post_title() {
global $post;
return _capitalize_the_post_title( $post );
// Or return _capitalize_the_post_title( $GLOBALS['post'] );
}
@dana-ross
dana-ross / just_monad.php
Created October 25, 2015 18:00
Just monad
<?php
class Just {
protected $value;
function __construct( $value ) {
$this->value = $value;
}
@dana-ross
dana-ross / template.js
Created October 19, 2015 21:06
Use underscore.js template engine with Mustache-style template tags (including escaping) instead of concatenation
_.template(
'[{{{ shortcodeString }}} url="{{{ url }}}" width="{{{ width }}}" height="{{{ height }}}"]',
{'shortcodeString': 'test',
'url': 'http://example.com',
'width': '100',
'height': '200'
}, {
interpolate: /\{\{([\s\S]+?)\}\}/g,
escape: /\{\{\{([\s\S]+?)\}\}\}/g}
);