debounce by requestAnimationFrame

events$.withHandler((() => {
let last, emitter, loop;
return (_emitter, { value, type }) => {
emitter = _emitter;
switch (type) {
case 'value':
last = value;
if (!loop) {
loop = requestAnimationFrame(() => {
emitter.value(last);
last = undefined;
loop = undefined;
});
}
break;
case 'error':
emitter.error(value);
break;
case 'end':
if (loop) {
cancelAnimationFrame(loop);
}
loop = requestAnimationFrame(() => {
if (last) {
emitter.value(last);
}
emitter.end();
last = undefined;
loop = undefined;
});
break;
}
};
})())
debounce-raf.js

Server-Side Rendering with React

import React from 'react';
const App = React.createClass({
displayName: 'App',
propTypes: {
headline: React.PropTypes.string.isRequired
},
render: function render() {
return (
<h1 className="headline">
{this.props.headline}
</h1>
);
}
});
export default App;
app.js
<h1 class="headline">
Hello World!
</h1>
rendered.html
import express from 'express';
import exphbs from 'express-handlebars';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
const app = express();
app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', 'hbs');
app.use(express.static('public'));
app.get('/', (req, res) => {
const state = { headline: 'Hello World!' };
res.render('index', {
app: ReactDOMServer.renderToString(<App {...state} />),
state: JSON.stringify(state)
});
});
server.js
import ReactDOM from 'react-dom';
const state = window.__INITIAL_STATE__ || {};
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<App {...state} />,
document.getElementById('app')
);
});
client.js

Expanding a div to take up the space in a row

<div class="row">
<div class="contained">
<span>Some Text</span>
</div>
<div class="expanded">
<span>Some more text that should take up all the remaining space.</span>
</div>
</div>
original.html
<div class="table">
<div class="row">
<div class="contained">
<span>Some Text</span>
</div>
<div class="expanded">
<span>Some more text that should take up all the remaining space.</span>
</div>
</div>
</div>
updated.html
.table {
display: table;
width: 100%;
}
.row {
display: table-row;
}
.contained {
display: table-cell;
width: 1px;
white-space: nowrap;
}
.expanded {
display: table-cell;
}
styles.css

Chatr Boilerplate

{"presets":["es2015","react"]}
.babelrc
import express from 'express';
const app = express();
app.use(express.static('public'));
app.get('/', (req, res) => {
res.set('Content-Type', 'text/html');
res.send('<h1>Hello World!</h1>');
});
app.listen(3000);
server.js
const webpack = require('webpack');
module.exports = {
entry: ['./client.js'],
devtool: 'sourcemap',
debug: true,
output: {
path: 'public/',
filename: '[name].min.js',
sourceMapFilename: '[name].js.map'
},
module: {
loaders: [
{
test: /.js$/,
loader: 'babel',
exclude: /(node_modules)/,
}
]
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({minimize: true})
]
};
webpack.config.js
const add = (a, b) => a + b;
console.log(add(1,2));
client.js
@import "node_modules/bourbon/core/bourbon";
@import "node_modules/bourbon-neat/app/assets/stylesheets/neat";
@import "base/base";
styles.scss
app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index', {
app: '<h1>Hello World!</h1>',
state: '{}'
})
});
handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web Chat</title>
<link href="/styles.css" rel="stylesheet" title="Default Styles">
</head>
<body>
<div id="app">{{{app}}}</div>
<script type="text/javascript">
window.__INITIAL_STATE__ = {{{state}}}
</script>
<script src="/client.js" charset="utf-8"></script>
</body>
</html>
main.hbs

Does this get garbage collected?

var el = (function() {
var templateString = template.render();
var wrapper = document.createElement('div');
wrapper.innerHTML = templateString;
var result = wrapper.firstChild;
// Zero out the innerHTML to ensure
// no reference to the resulting node.
wrapper.innerHTML = '';
return result;
})();
gc.js

Module References in CommonJS

var mod1 = require('./mod1');
var mod2 = require('./mod2');
mod1.impactMod2();
console.log(mod2.prop);
index.js
var mod2 = require('./mod2');
exports.impactMod2 = function() {
mod2.prop = 'Changed from mod1';
};
mod1.js
exports.prop = 'Defaulted in mod2';
mod2.js

Fat Arrow Functions, One-Line Callbacks, and Composing Promises

doSomething().then(function(value) {
return value.prop
});
old-style.js
doSomething().then(value => value.prop);
new-style.js
doSomething().then(value => value.asyncMethod())
.then(asyncMethodValue => asyncMethodValue.prop);
composing-promises.js

Convert Markdown Files into Quiver Notes

'use strict';
const fs = require('fs');
const Bluebird = require('bluebird');
const path = require('path');
const readDir = Bluebird.promisify(fs.readdir);
const readFile = Bluebird.promisify(fs.readFile);
const mkdir = Bluebird.promisify(fs.mkdir);
const stat = Bluebird.promisify(fs.stat);
const moment = require('moment');
const writeFile = Bluebird.promisify(fs.writeFile);
const rimraf = Bluebird.promisify(require('rimraf'));
const uuid = require('node-uuid')
readDir(process.cwd())
.filter(filename => filename.indexOf('.md') !== -1)
.map(generateQuiverNote);
function generateQuiverNote(filename) {
const filepath = path.join(process.cwd(), filename);
const fileuuid = uuid.v4().toUpperCase();
const dirpath = path.join(process.cwd(), fileuuid + '.qvnote');
return createNoteDir()
.then(() => Bluebird.join(createNoteMeta(), createNoteContent()));
function createNoteDir() {
return rimraf(dirpath).then(() => mkdir(dirpath));
}
function createNoteMeta() {
return stat(filepath).then(function(stats, data) {
let meta = {};
meta.created_at = moment(stats.birthtime).unix();
meta.tags = [];
meta.title = filename.slice(0, -3);
meta.updated_at = moment(stats.mtime).unix();
meta.uuid = fileuuid;
return writeFile(path.join(dirpath, 'meta.json'), JSON.stringify(meta, null, 2));
});
}
function createNoteContent() {
return readFile(filepath).then(function(data) {
let content = {};
content.title = filename;
content.cells = [{
type: 'markdown',
data: data.toString()
}];
return writeFile(path.join(dirpath, 'content.json'), JSON.stringify(content, null, 2));
});
}
}
sort.js
{
"name": "markdown-to-quiver",
"version": "1.0.0",
"description": "Convert your markdown files into Quiver notes.",
"main": "sort.js",
"scripts": { "test": "echo \"Error: no test specified\" && exit 1" },
"author": "James DiGioia <jamesorodig@gmail.com> (jamesdigioia.com)",
"license": "ISC",
"dependencies": {
"bluebird": "^3.1.1",
"moment": "^2.10.6",
"node-uuid": "^1.4.7",
"rimraf": "^2.4.4"
}
}
package.json

OS X Provisioning Script

cd /tmp
git clone https://github.com/mAAdhaTTah/tea-party.git
cd tea-party
./invite
sudo gem install homesick
homesick clone https://github.com/mAAdhaTTah/dotfiles
homesick link dotfiles
mackup restore
python -c "$(curl -fsSL https://raw.githubusercontent.com/fix-macosx/fix-macosx/master/fix-macosx.py)"
provision-osx.sh

save_post Error Reporting Boilerplate

add_action( 'admin_notices', 'my_error_message' );
admin-notice-hook.php
add_action( 'save_post', 'my_save_post_function' );
function my_save_function( $post_id ) {
    $error = false;
    // Do stuff.
    if ($something_went_wrong) {
        $error = new WP_Error($code, $msg);
    }
    if ($error) {
        // Handle error.
    }
    return true;
}
save-post-hook.php