Skip to content

Instantly share code, notes, and snippets.

@gobwas
gobwas / regexp.escaper.js
Created February 5, 2014 10:24
RegExp escaper
var escaper = function(value) {
assert(_.isString(value), "Can escape only the strings");
return value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
@gobwas
gobwas / random.hex.js
Created February 5, 2014 10:26
Random hex number
function randomHex() {
return (((1<<24) * Math.random())|0).toString(16);
}
{
flatten: function(obj) {
function flatten(obj) {
return _.reduce(obj, function(memo, value, key) {
if (_.isObject(value)) {
_.forEach(flatten(value), function(v, k) {
memo[key + "." + k] = v;
});
} else {
memo[key] = value;
@gobwas
gobwas / server.js
Created September 2, 2015 17:02
File receiver
var http = require("http");
var fs = require("fs");
var stat = fs.statSync("./index.html");
var server = http.createServer(function(req, res) {
switch(req.url) {
case "/": {
res.writeHead(200, {
'content-type': 'text/html',
@gobwas
gobwas / alloc.js
Created September 3, 2015 20:47
Alloc error
var bigInt = 1000000000;
console.log(process.argv);
function asBuf() {
var buf = new Buffer("");
for (var i = 0; i < bigInt; i++) {
if (i % 10000 == 0) console.log(process.memoryUsage()['rss'] / 1024 / 1024 + 'mb');
buf = Buffer.concat([buf, new Buffer("a")]);
@gobwas
gobwas / actor.js
Created October 22, 2015 15:28
Callable object
function Actor(min, max) {
var self = this;
this.id = Math.floor(min + Math.random() * (max - min + 1));
var actor = function() { return self.action.apply(actor, arguments); }
Object.setPrototypeOf(actor, this);
return actor;
}
@gobwas
gobwas / race.go
Last active November 13, 2015 15:22
Go slice race condition example
package main
import (
"fmt"
"time"
)
type List struct {
Items []int
}
@gobwas
gobwas / gcd.go
Created November 20, 2015 14:09
GCD
package gcd
import "fmt"
import "math/big"
func Dedup(l []int64) []int64 {
list := make([]int64, len(l))
copy(list, l)
last := len(list) - 1
@gobwas
gobwas / generator.js
Last active December 1, 2015 18:30
Generator object
var inherits = require("inherits-js");
var Generator;
/**
* @abstract
* @class Generator
* @constructor
*/
Generator = function() {
var self = this;
@gobwas
gobwas / Combine.js
Last active December 22, 2015 00:19
Combine strings algorithm.
/**
* Combine algorithm.
*
* @author Sergey Kamardin <gobwas@gmail.com>
*
* Usage:
*
* combine(['a','b'])
*
* Will return ['ab', 'ba'];