Created
May 2, 2022 14:47
-
-
Save mshick/6ccc07697cb3b8951eaca2bdebed5b2e to your computer and use it in GitHub Desktop.
nodash
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
import type { JsonObject, JsonValue } from 'type-fest'; | |
type PropertyName = string; | |
type List<T> = ArrayLike<T>; | |
type ListIterator<T, TResult> = (value: T, index: number, collection: List<T>) => TResult; | |
type Many<T> = Array<T>; | |
function baseGet(path: Many<PropertyName> | PropertyName) { | |
return (obj: JsonObject, defaultValue = undefined) => { | |
if (!path) { | |
return undefined; | |
} | |
const pathArray = Array.isArray(path) ? path : path.match(/([^[.\]])+/g); | |
const result = pathArray.reduce((prevObj, key) => prevObj && prevObj[key], obj); | |
return result === undefined ? defaultValue : result; | |
} | |
} | |
export function get(obj: JsonObject, path: Many<PropertyName> | PropertyName, defaultValue: JsonValue = undefined) { | |
return baseGet(path)(obj, defaultValue); | |
} | |
export function identity<T>(value: T): T { | |
return value; | |
} | |
export function iteratee<T>(value: Many<ListIterator<T, unknown>>) { | |
if (typeof value == 'function') { | |
return value; | |
} | |
if (value == null) { | |
return identity; | |
} | |
return baseGet(value); | |
} | |
export function sortBy<T>(key: string, cb: (a: T, b: T) => number) { | |
if (!cb) { | |
cb = () => 0; | |
} | |
return (a, b) => (get(a, key) > get(b, key) ? 1 : get(b, key) > get(a, key) ? -1 : cb(a, b)); | |
} | |
export function sortByDesc<T>(key: string | () => , cb: (a: T, b: T) => number) { | |
if (!cb) { | |
cb = () => 0; | |
} | |
return (b, a) => { | |
if (typeof key ) | |
return get(a, key) > get(b, key) ? 1 : get(b, key) > get(a, key) ? -1 : cb(b, a); | |
}; | |
} | |
export function orderBy<T>(keys: string[], orders: Array<'asc' | 'desc'>) { | |
let cb = (a: T, b: T) => 0; | |
keys.reverse(); | |
orders.reverse(); | |
for (const [i, key] of keys.entries()) { | |
const order = orders[i]; | |
if (order == 'asc') { | |
cb = sortBy(key, cb); | |
} else if (order == 'desc') { | |
cb = sortByDesc(key, cb); | |
} else { | |
throw new Error(`Unsupported order "${order}"`); | |
} | |
} | |
return cb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment