Instantly share code, notes, and snippets.

Bran van der Meer branneman

View GitHub Profile
View primitive-reference-types-javascript.md

Primitive Types & Reference Types in JavaScript

An explanation of JavaScript's pass-by-value, which is unlike pass-by-reference from other languages.

Facts

  • JavaScript has 2 kinds of variable types: primitive and reference.
  • A fixed amount of memory is reserved after creation of every variable.
  • When a variable is copied, it's in-memory value is copied.
  • Passing a variable to a function via a call also creates a copy of that variable.

Primitive Types

View fp.js
const { curryN, curry } = require('./curry') // https://gist.github.com/branneman/4ffb7ec3fc4a2091849ba5d56742960c
// Array
const nth = curry((key, list) => list[key])
const slice = curry((from, to, list) => list.slice(from, to))
const head = nth(0)
const init = slice(0, -1)
const tail = slice(1, Infinity)
const last = slice(-1, Infinity)
const reverse = list => list.slice().reverse()
View create-zip.js
const stat = require('fs').statSync;
const AdmZip = require('adm-zip');
/**
* Example usage
*/
newArchive(`test-${+new Date}.zip`, [
'index.js',
'package.json',
'node_modules'
View curry.js
const curryN = (fn, arity, accIn = []) => (...args) => {
const len = args.length
const accOut = accIn.concat(args)
if (len + accIn.length >= arity) {
return fn.apply(this, accOut)
}
return curryN(fn, arity, accOut)
}
const curry = fn => curryN(fn, fn.length)
View better-nodejs-require-paths.md

Better local require() paths for Node.js

Problem

When the directory structure of your Node.js application (not library!) has some depth, you end up with a lot of annoying relative paths in your require calls like:

const Article = require('../../../../app/models/article');

Those suck for maintenance and they're ugly.

Possible solutions

View turing-machine-interpreter.js
/**
* Turing Machine Interpreter
*
* Features:
* - Infinite tape, both ways
* - Uses JS values, anything that matches ==, is a valid symbol
*
* Definition:
* - States (Q): { integer, halt }
* - Input symbols read/write (Σ): any integer or string
View validations.js
export {
isNull,
isUndef,
isBool,
isNum,
isInt,
isStr,
isArr,
isObj,
isFunc,
View client.js
var net = require('net');
//
// Client
//
function openSocket() {
var socket = net.connect(3e3);
socket.setKeepAlive(true);
socket.on('connect', onConnect.bind({}, socket));
View count-lint-errors.js
// :: (String, String) => String
const spawn = require('child_process').spawnSync;
// :: String => [String]
const getRules = raw => raw
.split('\n')
.map(line => line.trim())
.filter(line => !!line)
.filter(line => line[0] !== '/' && line[0] !== '')
.map(line => line.match(/[a-z-]+$/)[0]);
View app.js
#!/usr/bin/env node
'use strict';
var spawn = require('child_process').spawn;
var args = [
'--harmony',
'app/bootstrap.js'
];