Skip to content

Instantly share code, notes, and snippets.

View jtrein's full-sized avatar

Jeremiah Naylor-Trein jtrein

View GitHub Profile
@jtrein
jtrein / mergeSortAlgorithm.js
Last active December 28, 2016 22:15
Merge Sort Algorithm in JavaScript (with Comments)
/**
* Merge Sort Algorithm: "divide and conquer", "break you down in order to build you back up"
* Overview:
* ---------
* A recursive sorting algorithm where we 1) divide an unsorted array in half (dismantle big array into tiny sub-arrays)
* until we reach atomic values (< 2 - it's never 0), then we 2) sort the adjacent sub-arrays (left, right) and
* 3) merge the sorted sub-array values (put things back together) after each iteration
*
* Time Complexity (worst case):
* -----
@jtrein
jtrein / greedyAlgorithm.js
Last active February 1, 2020 17:33
Greedy Algorithm in JavaScript - Max Profit on Stock Prices (with comments)
/**
* Greedy Algorithm (maximum daily profit from stock sale) - "let me see what my options are, first..."
*
* Overview:
* ---------
* By using Greedy Algorithms we can pass over the data once (O(n) time), storing values we find to be optimal, per our criteria, by
* comparing them to current values. We have to go over the entire set to do this, but we only have to do it once - yay!
*
* From Wikipedia: "A greedy algorithm is an algorithm that follows the problem solving heuristic of making the locally optimal
* choice at each stage with the hope of finding a global optimum."
@jtrein
jtrein / git-open-url.sh
Last active March 16, 2017 04:48
Open Git URL from Command Line
#!/bin/bash
##
# Git Open Remote Repo URL
# - by default opens at current tracked branch
# - opens with default web browser
# - supports HTTPS, ssh protocols using default "origin"
# Options:
# -b opens base repo URL
# -r change remote
@jtrein
jtrein / load-scripts-from-other-html.js
Last active March 21, 2017 10:09
Load Scripts and HTML from a Fetched Web Page (load scripts from another webpage)
/**
* Load HTML + scripts from a fetched HTML page (e.g. fetch a GitHub project page)
*
* PS - not really thatttttt useful. If you're using this, it's probably because
* of a bad design choice, initially. I just wanted a mini-challenge.
*/
fetch('[URL_OF_WEBPAGE]')
.then((res) => res.text())
.then((text) => {
this.apiRoot.innerHTML += text;
@jtrein
jtrein / cachedFetchGet.js
Last active May 24, 2017 00:44
Cached Fetch GET Request
/**
* CachedCall
*
* Caches a network GET request. When called more than once, the closure returns the cached value.
*
* @param {func} asyncFunc - i.e. `async (arg) => {}`
* @param ...args - spreads arguments into an array
* @return {Promise} cachedResponse | unresolvedCall - thenable with a resolved value
*/
export const CachedCall = (asyncFunc, ...args) => {
@jtrein
jtrein / mockFetch.js
Last active May 24, 2017 05:52
Mock Fetch with Jest
// __mocks__/mockFetch.js
const MockFetch = responseJson => (
() => (
new Promise(resolve => resolve({
json: () => JSON.parse(JSON.stringify(responseJson)),
}))
)
);
@jtrein
jtrein / sumAllRange.js
Last active September 21, 2017 07:12
Sum of all numbers in range in JavaScript
const sumAll = (arr) => {
// get our largest and smallest int's
const max = Math.max.apply(null, arr);
const min = Math.min.apply(null, arr);
// how many slots are there to add?
const slots = (max - min) + 1;
// create sparse array with number of slots found
const sumArr = Array(slots);
@jtrein
jtrein / ErrorBoundary.js
Created October 27, 2017 10:21
React Error Boundary Component and HOC
import React, { Component } from 'react';
export default class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch = (error, errorInfo) => catchFunc(error, errorInfo, this)
@jtrein
jtrein / corsHeaders.go
Last active October 31, 2017 03:24
CORS Header Golang (Gorilla)
// https://stackoverflow.com/questions/40985920/making-golang-gorilla-cors-handler-work/40987389#40987389
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With"})
originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
// start server listen
// with error handling
log.Fatal(http.ListenAndServe(":" + os.Getenv("PORT"), handlers.CORS(originsOk, headersOk, methodsOk)(router)))
@jtrein
jtrein / AWS_Single_LetsEncrypt.yaml
Created December 2, 2017 11:00 — forked from tony-gutierrez/AWS_Single_LetsEncrypt.yaml
AWS Elastic Beanstalk .ebextensions config for single instance free SSL using letsencrypt certbot and nginx. http://bluefletch.com/blog/domain-agnostic-letsencrypt-ssl-config-for-elastic-beanstalk-single-instances/
# Dont forget to set the env variable "certdomain", and either fill in your email below or use an env variable for that too.
# Also note that this config is using the LetsEncrypt staging server, remove the flag when ready!
Resources:
sslSecurityGroupIngress:
Type: AWS::EC2::SecurityGroupIngress
Properties:
GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
IpProtocol: tcp
ToPort: 443