Last active
February 19, 2024 01:31
-
-
Save tdubs42/01ca2f9a92c37156bdd17211082246a3 to your computer and use it in GitHub Desktop.
Array methods for Dicts (Objects) - TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From Frontend Masters Typescript Fundamentals v3 course | |
// Array.prototype.map, but for Dict | |
function mapDict<T, U>( | |
input: Dict<T>, | |
mappingCb: (arg: T, key: string) => U | |
): Dict<U> { | |
const output: Dict<U> = {} | |
// for-of loop is for an iterable | |
// for-in loop iterates over the properties of an Object | |
for (let key in input) { | |
const thisVal = input[key] | |
output[key] = mappingCb(thisVal, key) | |
} | |
return output | |
} | |
// Array.prototype.filter, but for Dict | |
function filterDict<T>( | |
input: Dict<T>, | |
filterCb: (arg: T) => boolean): Dict<T> { | |
const output: Dict<T> = {} | |
for (let key in input) { | |
const thisVal = input[key] | |
if (filterCb(thisVal)) output[key] = thisVal | |
} | |
return output | |
} | |
// Array.prototype.reduce, but for Dict | |
function reduceDict<T, V>( | |
input: Dict<T>, | |
reducer: (currentValue: V, item: T) => V, | |
initialVal: V | |
): V { | |
let output = initialVal | |
for (let key in input) { | |
const thisVal = input[key] | |
output = reducer(output, thisVal) | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment