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));
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));
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:
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}
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]]);
};
[ | |
{ | |
"name": "bug", | |
"color": "#A8B820", | |
"halfEffectiveAgainst": [ | |
"fairy", | |
"fighting", | |
"fire", | |
"flying", | |
"ghost", |
const swap = <T>(t: T[], i: number, j: number) => { | |
[t[i], t[j]] = [t[j], t[i]]; | |
}; | |
export const shuffle = <T>(t: T[]) => { | |
for (let i = t.length - 1; i > 0; i -= 1) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
swap(t, i, j); | |
} | |
}; |
const typedKeys = <O extends {}>(o: O) =>
Object.keys(o) as Array<keyof O>;
const o = {
first: 'josh',
last: 'o'
};
const keys = Object.keys(o);
const normalize = (min: number) => (max: number) => (x: number) => (x - min) / (max - min);
// usage
const min = 25;
const max = 100;
const n = normalize(min)(max);
const ns = [32, 62.5, 90].map(n);