Skip to content

Instantly share code, notes, and snippets.

View akmjenkins's full-sized avatar

Adam akmjenkins

  • Halifax, NS
View GitHub Profile
@akmjenkins
akmjenkins / conway.ts
Last active October 14, 2024 23:59
conway-game-of-life
// 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
// 2. Any live cell with more than three live neighbours dies, as if by overcrowding.
// 3. Any live cell with two or three live neighbours lives on to the next generation.
// 4. Any dead cell with exactly three live neighbours becomes a live cell.
type Grid = boolean[][];
const getNextStateOfCell = (grid: Grid, [y, x]: [number, number]): boolean => {
const liveNeighbours = [
grid[y - 1]?.[x - 1],
@akmjenkins
akmjenkins / observableStorage.js
Created March 4, 2023 19:55
Observable Storage because storageEvent doesn't fire in the same tab
const memo = (fn) => {
let lastArg;
return (arg) => {
if (typeof lastArg === 'undefined' || arg !== lastArg) fn((lastArg = arg));
};
};
const decorateStorage = () => {
if (typeof Storage === 'undefined') {
throw new Error('No Storage found in environment');
@akmjenkins
akmjenkins / partitioner.ts
Created November 17, 2022 13:13
Typescript Array Partitioner
const partitioner =
<T extends any[]>(fn: (arg: T) => string) =>
(arr: T) =>
Object.values(
arr.reduce((acc, item) => {
const id = fn(item);
acc[id] = acc[id] || [];
acc[id].push(item);
return acc;
}, {}),
import React, { useState } from 'react';
const setupActions = (setState,actions) => () => Object.entries(actions).reduce((acc,[name,fn]) => ({...acc,[name]:(...args) => setState(fn(...args))}),{});
export const statefulComponent = (initial,actions,stateProp='state') => Cmp => props => {
const [state,setState] = useState(initial);
return <Cmp
{...props}
{...{[stateProp]:state}}
{...useState(setupActions(setState,actions))[0]}
@akmjenkins
akmjenkins / gist:84b4fe3bb3fc9571f6dfa025f7eb3a94
Last active October 24, 2017 18:49
Flatten unlimited depth arrays
var a = [
1,
[1,2],
[1,[1,2,3]],
[1,[[1,2,3]]],
[[[[[[1,2,]],1,2]]],1,[1,2]]
];
function flatten(arr) {
return arr.reduce(function(c, item) {
@akmjenkins
akmjenkins / gulpfile.js
Last active August 29, 2015 14:24
Load gulp modules conditionally, depending on task.
var gulp = require('gulp');
/*
Dependencies used to be loaded like this: (too slow)
var sass = require('gulp-sass');
var cssShrink = require('gulp-cssshrink');
var bower = require('gulp-bower');
var uglify = require('gulp-uglify');