gpt4 book ai didi

javascript - 如何使用 van Laarhoven Lens 删除对象的聚焦属性?

转载 作者:行者123 更新时间:2023-11-29 10:56:14 25 4
gpt4 key购买 nike

通过我简单的镜头实现,我可以执行通常的修改、设置、获取和删除操作:

// Lens type

const Lens = f => ({runLens: f, [Symbol.toStringTag]: "Lens"});

const objLens = map => k =>
Lens(f => o =>
map(x => Object.assign({}, o, {[k]: x})) (f(o[k]))); // object lens

// Id type

const Id = x => ({runId: x, [Symbol.toStringTag]: "Id"});
const idMap = f => tx => Id(f(tx.runId)); // functor

// Const type

const Const = x => ({runConst: x, [Symbol.toStringTag]: "Const"});
const constMap = f => tx => Const(tx.runConst); // functor

// auxiliary function

const _const = x => y => x;

// MAIN

const o = {foo: "abc", bar: 123};

const get = objLens(constMap) ("foo").runLens(x => Const(x)) (o),
set = objLens(idMap) ("bat").runLens(_const(Id(true))) (o),
mod = objLens(idMap) ("foo").runLens(s => Id(s.toUpperCase())) (o),
del = objLens(idMap) ("foo").runLens(_const(Id(null))) (o); //*

console.log("get", get.runConst);
console.log("set", set.runId);
console.log("mod", mod.runId);
console.log("del", del.runId);

但是,delete 并不令人满意,因为我想删除整个属性,而不是仅仅用空值替换值。

我怎样才能做到这一点?

*请注意,我通常会使用适当的 Option 类型来表示没有值。

最佳答案

这是我会做的:

// type Lens a b = forall f. Functor f => (b -> f b) -> a -> f a

// newtype Const b a = Const { getConst :: b } deriving Functor
const Const = getConst => ({ getConst, map: _ => Const(getConst) });

// newtype Identity a = Identity { runIdentity :: a } deriving Functor
const Identity = runIdentity => ({ runIdentity, map: f => Identity(f(runIdentity)) });

// remove :: String -> Object -> Object
const remove = key => ({ [key]: _, ...rest }) => rest;

// prop :: String -> Lens Object (Maybe Value)
const prop = key => fun => obj =>
fun(obj.hasOwnProperty(key) ? { fromJust: obj[key] } : null)
.map(data => Object.assign(remove(key)(obj), data && { [key]: data.fromJust }));

// get :: Lens a b -> a -> b
const get = lens => data => lens(Const)(data).getConst;

// modify :: Lens a b -> (b -> b) -> a -> a
const modify = lens => fun => data => lens(x => Identity(fun(x)))(data).runIdentity;

// set :: Lens a b -> b -> a -> a
const set = lens => value => modify(lens)(_ => value);

// del :: Lens a (Maybe b) -> a -> a
const del = lens => set(lens)(null);

// foo :: Lens Object (Maybe Value)
const foo = prop("foo");

console.log(get(foo)({ foo: 10, bar: 20 })); // { fromJust: 10 }
console.log(del(foo)({ foo: 10, bar: 20 })); // { bar: 20 }

如上所示,像 foo 这样的属性 lens 的类型签名是 Lens Object (Maybe Value)。这是有道理的,因为如果你尝试 get(foo)({ bar: 20 }) 你应该什么也得不到。 del 函数适用于任何关注可能值的镜头,并将其值设置为空(即 null)。

showing me 归功于 Bergi可以对计算属性进行模式匹配。

关于javascript - 如何使用 van Laarhoven Lens 删除对象的聚焦属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56616733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com