前端大佬能当场写出这道题吗?

2022-06-20 18:02:49 +08:00
 zhaomeicheng

当场没写出来,面试官劝我别紧张,说这道题很基础,可是面试后自己在这也没写出来...

4266 次点击
所在节点    前端开发
41 条回复
enchilada2020
2022-06-20 21:32:14 +08:00
@sweetcola 很极致 我喜欢
skies457
2022-06-20 21:52:37 +08:00
const compose = ((self, [fn, ...fns]) => () => fn?.(self(self, fns)))((self, [fn, ...fns]) => () => fn?.(self(self, fns)), arr)

还可以升级一下难度,只使用匿名函数(逃
skies457
2022-06-20 21:53:33 +08:00
const compose = arr => ((self, [fn, ...fns]) => () => fn?.(self(self, fns)))((self, [fn, ...fns]) => () => fn?.(self(self, fns)), arr)

少了 arr => (
dasbn
2022-06-20 22:46:07 +08:00
@skies457 Y= f => (x => v => f(x(x))(v)) (x => v => f(x(x))(v))

提取出你的 Y (
molvqingtai
2022-06-20 23:09:44 +08:00
洋葱圈模型还挺实用的,koa 就不用说了,比如前端使用的 redux 、vue-router 内部实现都是使用洋葱模型

我也这种模式封装了一个 http 客户端:
https://github.com/molvqingtai/resreq
chezs66
2022-06-20 23:13:47 +08:00
这就是栈呀。。。无非是自己写一个栈,或用 js 自带的栈
zyxyz123
2022-06-20 23:17:32 +08:00
const compose = (arr) => {
if (arr.length === 0) {
return () => {}
}
return () => {
arr[0](compose(arr.slice(1)))
}
}
otakustay
2022-06-20 23:29:13 +08:00
const compose = handlers => handlers.reduceRight((out, v) => () => v(out), () => {});

手写倒有点难,电脑敲再简单调试一下下可以
Agassiz
2022-06-21 00:54:36 +08:00
洋葱模型
walpurgis
2022-06-21 01:40:31 +08:00
middlewares = [fn1,fn2,fn3]
compose 展开后是这样
fn = () => fn1(() => fn2(() => fn3(() => {})));

暴力拼接法

function compose(arr) {
const fn = arr.pop();
let composed = () => fn(() => {});
while (arr.length > 0) {
const fn = arr.pop();
composed = ((next) => () => fn(next))(composed)
};
return composed;
}
wanacry
2022-06-21 03:19:59 +08:00
这是啥玩意 我也会 js 但是为啥我都看不懂
MonkeyD1
2022-06-21 09:04:55 +08:00
@wanacry 哈哈 ➕1 我也是
banmuyutian
2022-06-21 09:47:03 +08:00
才疏学浅,请教下这个洋葱模型是不是类似于 Spring Boot 的堆栈?
danhua
2022-06-21 10:14:32 +08:00
为啥我第一眼感觉可以用异步来解决,不过异步比上面大佬们给出的方法要麻烦多了。
dtdths1
2022-06-21 10:56:54 +08:00
洋葱圈模型
ryougifujino
2022-06-21 12:43:51 +08:00
function compose(arr) {
let next = function () {
}
arr.reverse().forEach(fn => {
const nextFn = next
next = function () {
fn(nextFn)
}
})
return next
}
ryougifujino
2022-06-21 12:48:27 +08:00
@ryougifujino #36 个人感觉我这个思路很简单,确实就是洋葱圈模型。next 顾名思义,就是下一次要执行的函数,所以核心思路就是把下一次的函数放到 next 中去就行了。
zhaomeicheng
2022-06-21 13:50:48 +08:00
@ryougifujino 说真的,我看不懂😂
Lenic
2022-06-25 12:33:39 +08:00
建议看下 Array.prototype.reduce 方法
channg
2022-08-03 17:56:54 +08:00
我感觉这道题是需要多次运行 fn() 可以再出输入 1 2 3 3.1 2.1 1.1 吧 难道是我想多了?
@zhaomeicheng
@ryougifujino
@Cbdy
@cyrbuzz

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/860936

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX