From bc146aaefbdab07b7775a280b01c49a21f5c56e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AD=99=E9=A2=A2?= Date: Thu, 27 Dec 2018 17:30:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20get=20utils?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- @types/index.d.ts | 7 ++++++ src/utils/get.ts | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/utils/get.ts diff --git a/@types/index.d.ts b/@types/index.d.ts index 279c787..4c79723 100644 --- a/@types/index.d.ts +++ b/@types/index.d.ts @@ -411,5 +411,12 @@ declare namespace build { */ unpdate: (middlewares: any[]) => void } + + namespace Get { + interface BaseGetOptions { + strict?: boolean + defaultValue?: any + } + } } } diff --git a/src/utils/get.ts b/src/utils/get.ts new file mode 100644 index 0000000..3f9f304 --- /dev/null +++ b/src/utils/get.ts @@ -0,0 +1,55 @@ + +import { utils } from "@types"; +type BaseGetOptions = utils.Get.BaseGetOptions + +/** + * 安全获取对象的值 - 不报错 + * * 可能为 undefined + * @param obj 读取对象 + * @param args 读取路径 + */ +export function getValue (obj: T): T +export function getValue (obj: T, k1: K1): T[K1] +export function getValue (obj: T, k1: K1, k2: K2): T[K1][K2] +export function getValue (obj: T, k1: K1, k2: K2, k3: K3): T[K1][K2][K3] +export function getValue(obj: any, ...args: string[]) { + return obj == null ? undefined : baseGet(obj, args) +} + +/** + * 安全获取对象的值 - 会报错 + * * 必须使用 try - catch + * @param obj 读取对象 + * @param options 配置参数 + * @param args 读取路径 + */ +export function getInsureValue(obj: T, options: BaseGetOptions): T +export function getInsureValue(obj: T, options: BaseGetOptions, k1: K1): T[K1] +export function getInsureValue(obj: T, options: BaseGetOptions, k1: K1, k2: K2): T[K1][K2] +export function getInsureValue(obj: T, options: BaseGetOptions, k1: K1, k2: K2, k3: K3): T[K1][K2][K3] +export function getInsureValue(obj: any, options: BaseGetOptions = {}, ...args: string[]) { + Object.assign(options, { strict: true }) + return obj == null ? undefined : baseGet(obj, args, options) +} + + +function baseGet(object: any, path: string[], { strict, defaultValue }: BaseGetOptions = {}) { + let index = 0 + const length = path.length + while (object != null && index < length) { + object = object[path[index++]] + } + if (index === length) { + return object + } else { + if (strict) { + if (!defaultValue) { + throw new Error( + `[getValue] Uncaught TypeError: Object.${path.join('.')} Cannot read property '${path[index]}' of undefined.`, + ) + } return defaultValue + } else { + return undefined + } + } +} \ No newline at end of file