Skip to content

Instantly share code, notes, and snippets.

View joshwashywash's full-sized avatar
🤡

Josh Oertel joshwashywash

🤡
View GitHub Profile
@joshwashywash
joshwashywash / zip.md
Last active February 27, 2022 00:30
zips two arrays together

Zip function for TypeScript

all elements of as must be of type A. all elements of bs must be of type B. you can do this using recursion and you wouldn't have to know about the lengths of the arrays but that's for another gist.

const zip = <A, B>(as: A[], bs: B[]) => {
  const length = Math.min(as.length, bs.length);
  return Array.from({ length }, (_, i) => [as[i], bs[i]]);
};
@joshwashywash
joshwashywash / sample.md
Last active March 4, 2023 00:29
takes a random sample from an array

Sample an element from an array in TypeScript

const sample = <T>(items: T[]) => items[Math.floor(Math.random() * items.length)];
@joshwashywash
joshwashywash / List.md
Last active February 27, 2022 00:15
generic list component for svelte

Here's how you can know what type item has in the parent component so you get nice autocompletion :)

<script lang="ts">
  type Item = $$Generic;
  export let items: Item[] = [];
</script>

<ul>
 {#each items as item, index}
@joshwashywash
joshwashywash / createFetch.md
Last active February 27, 2022 00:02
create typesafe fetch in TypeScript

Just a higher-order function around fetch.

const createFetch = <T>(fn: (response: Response) => Promise<T>) => {
  return (...params: Parameters<typeof fetch>) => fetch(...params).then(fn);
};

You can use it like this:

@joshwashywash
joshwashywash / aperture.md
Last active April 7, 2023 19:53
aperture implementation in TypeScript

This is named after Ramda's aperture function https://ramdajs.com/docs/#aperture.

const aperture = (n: number) =>
	<T>(xs: T[]): T[][] =>
		n < 1 || n > xs.length
			? []
			: Array.from({ length: xs.length - n + 1 }, (_, i) => xs.slice(i, i + n));