Skip to content

Instantly share code, notes, and snippets.

@slikts
slikts / clone.js
Last active August 29, 2015 13:57
Object cloning using property descriptors
function clone(obj, deep) {
if (!(obj instanceof Object)) {
return obj;
}
var descriptors = {};
Object.getOwnPropertyNames(obj).forEach(function(name) {
var prop = Object.getOwnPropertyDescriptor(obj, name);
@slikts
slikts / get.js
Last active August 29, 2015 13:57
// array-like only
function get(arr, i) {
var len = arr.length;
i = i % len;
if (i < 0) {
i += len;
}
return arr[i];
}
@slikts
slikts / assign.js
Created March 20, 2014 19:56
My least favorite thing about ES5
// I want to add multiple properties to a target object in one statement without adding extra variables to the current scope
// This can be done in ES6 with Object.assign:
var targetObj = {};
Object.assign({
a: 1,
b: 2
}, targetObj);
@slikts
slikts / ansi_console.js
Created April 5, 2014 13:58
nodejs console with ANSI syntax highlighting
(function() {
var highlight = require('cardinal').highlight;
var beautify = require('js-beautify').js_beautify;
var log = console.log;
console.log = function() {
log.apply(console, Array.prototype.map.call(arguments, function(x) {
return highlight('(' + beautify(JSON.stringify(x)) + ')');
}));
};
REPORTER ?= nyan
TESTS = test/*.js
test: ; @NODE_ENV=test ./node_modules/.bin/mocha \
--timeout 1000 --reporter $(REPORTER) $(TESTS)
.PHONY: test
var pattern = /^(\d+?)(0+)$/;
function ne(n) {
'use strict';
var str = String(n);
var match = str.match(pattern);
var len;
if (!match) {
@slikts
slikts / r2v.js
Created April 13, 2014 13:14
radians to heading vector
'use strict';
function d2r(d) {
return d * Math.PI / 180;
}
function r2d(r) {
return r * 180 / Math.PI;
}
@slikts
slikts / reload.js
Last active August 29, 2015 14:00
Ping a server with HEAD requests until it's up and then reload
function reload(url, delay) {
url = url || '/';
delay = delay || 10;
var req = new XMLHttpRequest();
req.onload = window.location.reload.bind(window.location);
req.onerror = setTimeout.bind(null, reload.bind(null, url, delay), delay);
req.open('head', url, true);
@slikts
slikts / naive_extend.js
Last active August 29, 2015 14:00
Naive extend objects & primitives only
function extend(target, source) {
Object.keys(source).forEach(function(key) {
var sourceItem = source[key];
var targetItem = target[key];
if (sourceItem instanceof Object && targetItem !== undefined) {
extend(targetItem, sourceItem);
} else {
target[key] = sourceItem;
}
var listeners = {
a: function(done) {
// do something
done();
},
b: function(done) {
// do something
done();
}
};