Skip to content

Instantly share code, notes, and snippets.

View gartenfeld's full-sized avatar

David Rosson gartenfeld

View GitHub Profile
@gartenfeld
gartenfeld / stringy.js
Created June 30, 2015 01:27
Experiment with stringifyJSON.
// this is what you would do if you liked things to be easy:
// var stringifyJSON = JSON.stringify;
// but you don't so you're going to write it from scratch:
var stringifyJSON = function(obj) {
if (obj===null) {
return 'null';
} else if (typeof obj === 'number' || 'boolean') {
@gartenfeld
gartenfeld / prime_sieve.js
Last active August 29, 2015 14:23
The Sieve of Eratosthenes.
function Eratosthenes(max) {
var elim = {},
primes = [];
for (var i=2; i<=max; i++) {
if ( !elim[i] ) {
primes.push(i);
for (var j=i*2; j<=max; j+=i) {
elim[j] = true;
}
}
@gartenfeld
gartenfeld / fizzbuzz.js
Last active August 29, 2015 14:22
A less readable rendition of FizzBuzz.
var f = function (n) {
var s = "";
// 0 is falsy, the ternary then evaluates to the value right of the colon
s += n % 3 ? "" : "Fizz";
s += n % 5 ? "" : "Buzz";
// empty string is also falsy
return s ? s : n;
};
console.log(f(7));
@gartenfeld
gartenfeld / min_change.js
Last active August 29, 2015 14:15
Iterative solution for the minimal change problem.
var solutions = {},
coins = [1,5,7,9,11];
var process = function (t) {
if (t == 0) {
// solved
return 0;
} else if (t < 0) {
// wrong path; return really large number
return 2e10;
@gartenfeld
gartenfeld / mode.js
Created February 18, 2015 03:50
Finding a mode in an array of numbers.
var array = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17],
c = {}, // counters
s = []; // sortable array
for (var i=0; i<array.length; i++) {
c[array[i]] = c[array[i]] || 0; // initialize
c[array[i]]++;
} // count occurrences
for (var key in c) {
@gartenfeld
gartenfeld / output.txt
Last active August 29, 2015 14:15
Recursive combinatorics.
State of binary switches: 0,0,0,0,0,0
Corresponding combination:
State of binary switches: 0,0,0,0,0,1
Corresponding combination: 100
State of binary switches: 0,0,0,0,1,0
Corresponding combination: 5
State of binary switches: 0,0,0,0,1,1
Corresponding combination: 5,100
State of binary switches: 0,0,0,1,0,0
Corresponding combination: 4
@gartenfeld
gartenfeld / max_comb.js
Created February 16, 2015 01:34
Binary combination adding to max.
function ArrayAdditionI(arr) {
// code goes here
var max = Math.max.apply( Math, arr ),
idx = arr.indexOf(max);
if (idx>-1) { arr.splice(idx, 1) }
return arr
}
@gartenfeld
gartenfeld / restore.sh
Created January 30, 2015 05:48
mongorestore
mongorestore --host mongodb1.example.net --port 37017 --username user --password pass /opt/backup/mongodump-2011-10-24
function getQuery (searchString, callback) {
mongo.MongoClient.connect(
uri,
function(err, db) {
if(err) throw err;
query = { "$text": { "$search": searchString.toString() } };
var cursor = db.collection("quotes").find(