You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Since a function only can return one value it is absolutely sufficient to only support functions that consume only one parameter. Build your pipe function in a way, that one can pipe an arbitrary number of functions.
** 解答 **
// just a small amount of possible functions to start testing with.varaddOne=function(e){returne+1;};varsquare=function(e){returne*e;};// Extend the Function prototype with a method pipeFunction.prototype.pipe=function(input){varfunc=this;returnfunction(num){returninput(func(num));};};
介绍
近期看见一些有意思的前端面试题,激起了我心中的火,故收录并尝试解答分析
面试题
即乘法。
** 解答 **
** 分析 **
初一看这道题,被三个()看的有的晕乎,心想两个的我见过,三个的还真是头一回。
仔细琢磨下,发现这其中需要实现的就是需要保留每次执行函数的结果,用于跟下一次的入参做乘法;同时函数需要自执行,因为最终需要输出结果而不是Function
得出这几点:
然后我们通过解答去分析,mul(2)的执行结果是
function(b){ return mul(2 * y)}
,但是,该函数进行了valueOf操作,所以第一次执行的结果是mul(2 * y)
,接下来,将3传入,所以此时的结果是mul(6 * y)
,注意这时候的6是刚才的结果,y是接下来传入的参数值,同理传入4的时候没有y值了,所以最终的返回值为 2 * 3 * 4=24。** 出处 **
https://www.zhihu.com/question/54822257
Functional programming thrives from the reuse of functions. One core feature to extend the reuse is the concatenation of functions.
You probably know this feature from your favorite shell:
ls -la | sort | head
lists the top lines of the sorted result of ls -laBuild a function pipe to achieve this with JS. An example use could be:
Since a function only can return one value it is absolutely sufficient to only support functions that consume only one parameter. Build your pipe function in a way, that one can pipe an arbitrary number of functions.
** 解答 **
** 分析 **
这道题在我看来是将函数作为入参,另外考察数组map的使用
我们从
addOne.pipe(square)
看,这里说明pipe接收一个Fn作为参数,同时很显示,输出是原数组的每项加一的平方。即可以得出:如果用ES6的写法就更简单了,直接
...args
** 出处 **
https://www.codewars.com/kata/concatenating-functions/javascript
长期收集补充,欢迎大家提供有趣的前端面试题
此收录长期有效。
如果您也遇见或者接触到有意思的前端题目,欢迎留言给我,我们一起做这个有意义有价值的事情。
(完)
The text was updated successfully, but these errors were encountered: