Skip to content

Instantly share code, notes, and snippets.

View dana-ross's full-sized avatar

Dana Ross dana-ross

View GitHub Profile
@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 / 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'] );
}
/**
* 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' );
$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' );
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' );
function busy_work( $value ) {
$sha256 = partially_apply( 'hash', 'sha256' );
$retval = $value;
for( $i = 0; $i < 1000; $i++ ) {
$retval = $sha256( $retval );
}
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/
*/
<?php
/**
* Return the object's value + 2
*/
function f( $obj ) {
$retval = $obj->value + 2;
$obj->value = 5; // EVIL!
return $retval;
}
<?php
use DaveRoss\FunctionalProgrammingUtils\Just as Just;
$f = function( $value ) {
$retval = $value + 2;
$value = 5; // Who cares?
return $retval;
};
<?php
$good = json_decode('{ "label": "This is valid JSON", "value": 5 }' );
$bad = json_decode('{ "label": This is invalid JSON, "value": 5 }' );
if( is_null( $good ) ) {
echo "Couldn't parse good JSON\n";
}
else {
echo $good->value . "\n";