Skip to content

Instantly share code, notes, and snippets.

// How many steps a Knight takes on an infinite chessboard from O(0,0) to P (x,y)
// With O(1) time complexity
const knightsMetric = (x, y) => {
let normalizedX = Math.abs(x);
let normalizedY = Math.abs(y);
// Normailze coordinates, so that 0 <= y <= x
if(normalizedX < normalizedY) {
[normalizedY, normalizedX] = [normalizedX, normalizedY]
@tokdaniel
tokdaniel / fizzbuzz.purs
Last active July 3, 2020 15:16
FizzBuzz in Purescript
module Main where
import Prelude (bind, mod, pure, (<$>), (<<<), (==))
import Data.List (List, (..))
import Data.Either (Either(..))
isDivisibleBy :: Int -> String -> Either String Int -> Either String Int
isDivisibleBy divider replacer value = do
v <- value
if mod v divider == 0
// These are some nice-to-have utilies which js doesn't provide by default
// creates an array of numbers as [m..n]
const range = (m: number, n: number): number[] => Array.from(Array(n - m + 1).keys()).map(n => n + m)
// combines functions from right to left (opposite of pipe)
const compose = <R>(fn1: (a: R) => R, ...fns: Array<(a: R) => R>) =>
fns.reduce((prevFn, nextFn) => value => prevFn(nextFn(value)), fn1);
// if `value` is anything other than a number this is an identity, and modulus otherwise
@tokdaniel
tokdaniel / hooks.ts
Last active November 19, 2019 00:02
import { useState, useEffect, useRef, EffectCallback } from 'react';
import throttle from 'lodash/throttle';
import debounce from 'lodash/debounce';
// Ties two states together, and tracks only if a specific case occur.
export const transitionTracker = <A, B>(from: A, to: B) => {
let marker = 0;
return (state1: A, state2: B) => {
if (from === state1 && to === state2) {
@tokdaniel
tokdaniel / id.js
Created September 5, 2019 13:46
Relatively safe ID generator, fixed length option
const ID = () => (Date.now() + Math.random().toString(36)
.substr(2, 9))
.split('')
.sort(() => (0.5 > Math.random() ? -1 : 1))
.join('');
const createFixedLengthID = (length) => ID().padStart(length, ID())