-
Notifications
You must be signed in to change notification settings - Fork 509
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Q747】如何实现一个 omit/omitBy 函数 #793
Comments
TypeScript一种简单思路,顺序遍历 source 的每一项 key,与参数做对比,通过即储存到目标对象中 function omit<T extends Record<string, unknown>>(source: T, keys: (keyof T)[]) {
return Object.keys(source).reduce(((target: T, nowKey: keyof T) => {
if(!keys.includes(nowKey)) target[nowKey] = source[nowKey]
return target
}), {} as T)
}
function omitBy<T extends Record<string, unknown>>(source: T, filterFn: (v: unknown) => boolean) {
return Object.keys(source).reduce(((target: T, nowKey: keyof T) => {
if(!filterFn(source[nowKey])) target[nowKey] = source[nowKey]
return target
}), {} as T)
} JavaScriptfunction omit(source, keys) {
return Object.keys(source).reduce(((target, nowKey) => {
if(!keys.includes(nowKey)) target[nowKey] = source[nowKey]
return target
}), {})
}
function omitBy(source, filiterFn) {
return Object.keys(source).reduce(((target, nowKey) => {
if(!filiterFn(source[nowKey])) target[nowKey] = source[nowKey]
return target
}), {})
} |
@alexzhang1030 omit 的复杂度过高,性能较差。应遍历 keys,逐一删除。另外,ts 直接用 Omit 这个内置 type。 |
有个问题,直接删除不就修改源数据了 |
首先 {...obj}
…---原始邮件---
发件人: ***@***.***>
发送时间: 2022年10月21日(周五) 中午12:11
收件人: ***@***.***>;
抄送: ***@***.******@***.***>;
主题: Re: [shfshanyue/Daily-Question] 【Q747】如何实现一个 omit/omitBy 函数 (Issue #793)
@alexzhang1030 omit 的复杂度过高,性能较差。应遍历 keys,逐一删除。另外,ts 直接用 Omit 这个内置 type。
有个问题,直接删除不就修改源数据了
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you authored the thread.Message ID: ***@***.***>
|
懂了,还的是月哥,待会我加上 |
function omit<T extends Record<string, any>, K extends string, K2 extends keyof T>(obj: T, keys: (K | K2)[]) {
const result = { ...obj }
keys.forEach((key) => {
delete result[key]
})
return result as Omit<T, K>
}
function omitBy<T extends Record<string, any>, K extends keyof T>(object: T, callback: (value: T[K], key: K) => boolean) {
const result = { ...object }
Object.entries(result).forEach(([key, value]) => {
const isDrop = callback(value, key as K)
if (isDrop)
delete result[key]
})
return result as Partial<T>
}
|
The text was updated successfully, but these errors were encountered: