Instantly share code, notes, and snippets.

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 modules.js
/**
* Globals
*/
var Carrousel = function(elem) { this.init() };
Carrousel.prototype = { init: function() {} };
new Carrousel();
/**
* Namespacing
* - No globals (only the namespace variable itself is global)
View fp-lenses.js
// FP Lenses
const lens = get => set => ({ get, set });
const view = lens => obj => lens.get(obj);
const set = lens => val => obj => lens.set(val)(obj);
const over = lens => fn => obj => set(lens)(fn(view(lens)(obj)))(obj);
const lensProp = key => lens(prop(key))(assoc(key));
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 lambda-img-to-webp.js
'use strict';
const whitelist = {
'/static/img/photo.jpg': '/static/img/photo.webp'
};
exports.handler = (event, context, callback) => {
// Grab HTTP request and it's headers
const request = event.Records[0].cf.request;
View asyncParallel.js
var asyncParallel = function(tasks, callback) {
var results = [];
var count = tasks.length;
tasks.forEach(function(task, index) {
task(function(err, data) {
results[index] = data;
if (err) {
callback && callback(err);
callback = null;
}
View server.js
var fs = require('fs'),
exec = require('child_process').exec,
express = require('express'),
app = express();
app.get('/static/img/*.svg.*.png', function(req, res) {
var pngFile = 'src' + req.url,
svgFile = pngFile.substring(0, pngFile.indexOf('.svg') + 4);
if (!fs.existsSync(svgFile)) {
return res.render('404', {
View event.js
$(function() {
var resizeEnd;
$(window).on('resize', function() {
clearTimeout(resizeEnd);
resizeEnd = setTimeout(function() {
$(window).trigger('resize-end');
}, 100);
});
});
View _util.js
/**
* This function polls the component's props for Apollo to set `props.data.loading` to `false`
* @example
* await waitDuringLoadingState(testRenderer, TodoContainer)
* @see {@link https://reactjs.org/docs/test-renderer.html}
* @param {TestRenderer} testRenderer
* @param {React.Component} testComponent
* @returns {Promise}
*/
export function waitDuringLoadingState(testRenderer, testComponent) {