Skip to content

Instantly share code, notes, and snippets.

View joeljameswatson's full-sized avatar

Joel Watson joeljameswatson

View GitHub Profile
/*
"Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
Write a function that, given a sentence like the one above, along with the position of an opening parenthesis, finds the corresponding closing parenthesis.
Example: if the example string above is input with the number 10 (position of the first parenthesis), the output should be 79 (position of the last parenthesis).
*/
function findClosingParenthesis(openingParenthesis, string) {
// use stack to track matching parenthesis
@joeljameswatson
joeljameswatson / mergeSort.js
Last active October 16, 2019 23:41
Implementation of a merge sort. Time complexity = O(n log n)
function mergeSort(array) {
if (array.length < 2) return array;
// split the input array in half
const midPoint = Math.floor(array.length / 2);
const left = array.slice(0, midPoint);
const right = array.slice(midPoint);
// recursively call mergeSort on halved input
const sortedLeft = mergeSort(left);
const middlewareA = store => {
return next => {
console.log("middlewareA next: ", next);
return action => {
console.log("running middlewareA");
return next(action);
};
};
};
@joeljameswatson
joeljameswatson / redux-combineReducers-implementation.js
Created September 25, 2018 03:28
redux combineReducers function implementation
const combineReducers = reducers => {
return (state = {}, action) => {
// Reduce all the keys for reducers from `todos` and `visibilityFilter`
return Object.keys(reducers).reduce(
(nextState, key) => {
// Call the corresponding reducer function for a given key
nextState[key] = reducers[key] (
state[key],
action
@joeljameswatson
joeljameswatson / redux-store-implementation.js
Created September 24, 2018 23:40
basic implementation of redux store
const createStore = (reducer) => {
let state;
let listeners = [];
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action);
listeners.forEach(listener => listener());
};
@joeljameswatson
joeljameswatson / delayed-promise.js
Last active September 18, 2018 22:23
A delayed promise. Useful for testing things like display of spinners when making network requests.
const delayedPromise = (delay = 1000, value = "foo", shouldReject) => {
return new Promise((resolve, reject) => {
const action = shouldReject ? reject : resolve;
setTimeout(() => action(value), delay);
});
};
delayedPromise().then(value => console.log(value));
// expected output: "foo");