Last active
December 23, 2018 02:25
-
-
Save wafs/8a6382d91a994530b8a1ba22cac6839f to your computer and use it in GitHub Desktop.
Type safe FindOrfail implementation in typescript
This file contains 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
// Takes an array of data, then a comparator, then returns a function that will search for the item given some key | |
const finder = <T>(arr: T[]) => | |
<K>(comparator: (key: K, item: T) => boolean) => | |
(key: K) => arr.find(v => comparator(key, v)); | |
// Wraps the input function to throw on undefined while keeping it type safe | |
const throwOnUndefined = <F extends Function>(f: F): F => { | |
return <any>function (...args: any[]): F { | |
const res = f(...args); | |
if (res === undefined) { | |
throw new Error("Could not find element") | |
} | |
return res; | |
} | |
}; | |
//// Usage //// | |
interface EnumTableEntry { | |
id: number; | |
name: string; | |
} | |
// Some imaginary data from an imaginary database | |
const listOfStuff: EnumTableEntry[] = [ | |
{id: 0, name: 'Zero'}, | |
{id: 2, name: 'Two'}, | |
{id: 441, name: 'Four hundred and forty one'}, | |
]; | |
/// Example of Setting it up before exporting | |
const idComparator = (id: number, item: any) => id === item.id; | |
const nameComparator = (name: string, item: any) => name === item.name; | |
const boundData = finder(listOfStuff); | |
const getById = boundData(idComparator) | |
const getByName = boundData(nameComparator) | |
/// Example of a something returned by module.exports | |
const hasElementById = throwOnUndefined(getById); | |
const hasElementByName = throwOnUndefined(getByName); | |
console.log('By id = 0 :', hasElementById(0)); | |
// console.log(hasElementById('0')); // type fail, param is a string | |
console.log('By name = Two : ', hasElementByName('Two')); | |
// console.log(hasElementByName(2)); // type fail, param is a number | |
try { | |
hasElementByName('FAIL FAIL') | |
} catch (e) { | |
console.log('Failed to collect element by name') | |
} | |
try { | |
hasElementById(12481094289) | |
} catch (e) { | |
console.log('Failed to collect element by number') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment