Skip to content

Instantly share code, notes, and snippets.

@skiano
Last active March 8, 2018 15:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skiano/464782d5723787099419244443a7b5bb to your computer and use it in GitHub Desktop.
Save skiano/464782d5723787099419244443a7b5bb to your computer and use it in GitHub Desktop.
Interesting code snippets to talk about
// -------------------------------------------------------------------------------------------------------
// Once (from source of async)
// @see https://github.com/caolan/async/blob/f5d86b80b986c8cad88a224a6f8b3ec154839490/lib/internal/once.js
// -------------------------------------------------------------------------------------------------------
function once(fn) {
return function () {
if (fn === null) return;
var callFn = fn;
fn = null;
callFn.apply(this, arguments);
};
}
// -----------------------------------------------------
// dlv() source
// https://github.com/developit/dlv/blob/master/index.js
// -----------------------------------------------------
export default function dlv(obj, key, def, p) {
p = 0;
key = key.split ? key.split('.') : key;
while (obj && p<key.length) obj = obj[key[p++]];
return obj===undefined ? def : obj;
}
// ------------------------------
// UMD (simplified rollup output)
// ------------------------------
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('myLibrary')) :
typeof define === 'function' && define.amd ? define(['myLibrary'], factory) : (global.MyMod = factory(global.MyLibrary));
}(this, (function (myLibrary) {
const myMod = { doSomething: function() { myLibrary.coolHelper(); } }
return myMod;
})));
// -------------------------------
// Google Tag Manager (beautified)
// -------------------------------
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-XXXX');
// ---------------------------
// request logger (simplified)
// ---------------------------
logger.requestLogger = (req, res, next) => {
req._startTime = Date.now()
const end = res.end
res.end = (chunk, encoding) => {
const responseTime = Date.now() - req._startTime
res.end = end
res.end(chunk, encoding)
logger.labeledInfo(req.method, `${req.originalUrl || req.url} ${responseTime}ms`)
}
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment