René's URL Explorer Experiment


Title: 从一道面试题认识函数柯里化 · Issue #4 · webproblem/Blog · GitHub

Open Graph Title: 从一道面试题认识函数柯里化 · Issue #4 · webproblem/Blog

X Title: 从一道面试题认识函数柯里化 · Issue #4 · webproblem/Blog

Description: 最近在整理面试资源的时候,发现一道有意思的题目,所以就记录下来。 题目 如何实现 multi(2)(3)(4)=24? 首先来分析下这道题,实现一个 multi 函数并依次传入参数执行,得到最终的结果。通过题目很容易得到的结论是,把传入的参数相乘就能够得到需要的结果,也就是 2X3X4 = 24。 简单的实现 那么如何实现 multi 函数去计算出结果值呢?脑海中首先浮现的解决方案是,闭包。 function multi(a) { return function(b) ...

Open Graph Description: 最近在整理面试资源的时候,发现一道有意思的题目,所以就记录下来。 题目 如何实现 multi(2)(3)(4)=24? 首先来分析下这道题,实现一个 multi 函数并依次传入参数执行,得到最终的结果。通过题目很容易得到的结论是,把传入的参数相乘就能够得到需要的结果,也就是 2X3X4 = 24。 简单的实现 那么如何实现 multi 函数去计算出结果值呢?脑海中首先浮现的解决方案是,闭包。...

X Description: 最近在整理面试资源的时候,发现一道有意思的题目,所以就记录下来。 题目 如何实现 multi(2)(3)(4)=24? 首先来分析下这道题,实现一个 multi 函数并依次传入参数执行,得到最终的结果。通过题目很容易得到的结论是,把传入的参数相乘就能够得到需要的结果,也就是 2X3X4 = 24。 简单的实现 那么如何实现 multi 函数去计算出结果值呢?脑海中首先浮现的解决方案是,闭包。...

Opengraph URL: https://github.com/webproblem/Blog/issues/4

X: @github

direct link

Domain: patch-diff.githubusercontent.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"从一道面试题认识函数柯里化","articleBody":"最近在整理面试资源的时候,发现一道有意思的题目,所以就记录下来。 \r\n\r\n### 题目\r\n\r\n如何实现 multi(2)(3)(4)=24?\r\n\r\n首先来分析下这道题,实现一个 multi 函数并依次传入参数执行,得到最终的结果。通过题目很容易得到的结论是,把传入的参数相乘就能够得到需要的结果,也就是 2X3X4 = 24。\r\n\r\n### 简单的实现\r\n\r\n那么如何实现 multi 函数去计算出结果值呢?脑海中首先浮现的解决方案是,闭包。\r\n\r\n```javascript\r\nfunction multi(a) {\r\n    return function(b) {\r\n        return function(c) {\r\n            return a * b * c;\r\n        }\r\n    }\r\n}\r\n```\r\n\r\n利用闭包的原则,multi 函数执行的时候,返回 multi 函数中的内部函数,再次执行的时候其实执行的是这个内部函数,这个内部函数中接着又嵌套了一个内部函数,用于计算最终结果并返回。\r\n\r\n![闭包实现](https://user-images.githubusercontent.com/20440496/44616464-dce4d800-a882-11e8-94be-fb73f543fce4.png)\r\n\r\n单纯从题面来说,似乎是已经实现了想要的结果,但仔细一想就会发现存在问题。\r\n\r\n上面的实现方案存在的缺陷:\r\n\r\n* 代码不够优雅,实现步骤需要一层一层的嵌套函数。\r\n* 可扩展性差,假如是要实现 multi(2)(3)(4)...(n) 这样的功能,那就得嵌套 n 层函数。\r\n\r\n那么有没有更好的解决方案,答案是,使用函数式编程中的函数柯里化实现。\r\n\r\n### 函数柯里化\r\n\r\n在函数式编程中,函数是一等公民。那么函数柯里化是怎样的呢?\r\n\r\n函数柯里化指的是将能够接收多个参数的函数转化为接收单一参数的函数,并且返回接收余下参数且返回结果的新函数的技术。\r\n\r\n函数柯里化的主要作用和特点就是参数复用、提前返回和延迟执行。\r\n\r\n例如:封装兼容现代浏览器和 IE 浏览器的事件监听的方法,正常情况下封装是这样的。\r\n\r\n```javascript\r\nvar addEvent = function(el, type, fn, capture) {\r\n    if(window.addEventListener) {\r\n        el.addEventListener(type, function(e) {\r\n            fn.call(el, e);\r\n        }, capture);\r\n    }else {\r\n        el.attachEvent('on' + type, function(e) {\r\n            fn.call(el, e);\r\n        })\r\n    }\r\n}\r\n```\r\n\r\n该封装的方法存在的不足是,每次写监听事件的时候调用 addEvent 函数,都会进行 if else 的兼容性判断。事实上在代码中只需要执行一次兼容性判断就可以了,后续的事件监听就不需要再去判断兼容性了。那么怎么用函数柯里化优化这个封装函数。\r\n\r\n```javascript\r\nvar addEvent = (function() {\r\n    if(window.addEventListener) {\r\n        return function(el, type, fn, capture) {\r\n            el.addEventListener(type, function(e) {\r\n                fn.call(el, e);\r\n            }, capture);\r\n        }\r\n    }else {\r\n        return function(ele, type, fn) {\r\n            el.attachEvent('on' + type, function(e) {\r\n                fn.call(el, e);\r\n            })\r\n        }\r\n    }\r\n})()\r\n```\r\n\r\njs 引擎在执行该段代码的时候就会进行兼容性判断,并且返回需要使用的事件监听封装函数。这里使用了函数柯里化的两个特点:提前返回和延迟执行。\r\n\r\n柯里化另一个典型的应用场景就是 bind 函数的实现。使用了函数柯里化的两个特点:参数复用和提前返回。\r\n\r\n```javascript\r\nFunction.prototype.bind = function(){\r\n\tvar fn = this;\r\n\tvar args = Array.prototype.slice.call(arguments);\r\n\tvar context = args.shift();\r\n\r\n\treturn function(){\r\n\t\treturn fn.apply(context, args.concat(Array.prototype.slice.call(arguments)));\r\n\t};\r\n};\r\n```\r\n\r\n\r\n\r\n#### 柯里化的实现\r\n\r\n那么如何通过函数柯里化实现面试题的功能呢?\r\n\r\n#### 通用版\r\n\r\n```javascript\r\nfunction curry(fn) {\r\n    var args = Array.prototype.slice.call(arguments, 1);\r\n    return function() {\r\n\tvar newArgs = args.concat(Array.prototype.slice.call(arguments));\r\n        return fn.apply(this, newArgs);\r\n    }\r\n}\r\n```\r\n\r\ncurry 函数的第一个参数是要动态创建柯里化的函数,余下的参数存储在 args 变量中。\r\n\r\n执行 curry 函数返回的函数接收新的参数与 args 变量存储的参数合并,并把合并的参数传入给柯里化了的函数。\r\n\r\n```javascript\r\nfunction multiFn(a, b, c) {\r\n    return a * b * c;\r\n}\r\nvar multi = curry(multiFn);\r\nmulti(2,3,4);\r\n```\r\n\r\n结果:\r\n\r\n![image](https://user-images.githubusercontent.com/20440496/44618906-70350200-a8b1-11e8-8e0b-bd015b263630.png)\r\n\r\n虽然得到的结果是一样的,但是很容易发现存在问题,就是代码相对于之前的闭包实现方式较复杂,而且执行方式也不是题目要求的那样 multi(2)(3)(4)。那么下面就来改进这版代码。\r\n\r\n#### 改进版\r\n\r\n就题目而言,是需要执行三次函数调用,那么针对柯里化后的函数,如果传入的参数没有 3 个的话,就继续执行 curry 函数接收参数,如果参数达到 3 个,就执行柯里化了的函数。\r\n\r\n```javascript\r\nfunction curry(fn, args) {\r\n    var length = fn.length;\r\n    var args = args || [];\r\n    return function(){\r\n        newArgs = args.concat(Array.prototype.slice.call(arguments));\r\n        if(newArgs.length \u003c length){\r\n            return curry.call(this,fn,newArgs);\r\n        }else{\r\n            return fn.apply(this,newArgs);\r\n        }\r\n    }\r\n}\r\nfunction multiFn(a, b, c) {\r\n    return a * b * c;\r\n}\r\nvar multi = curry(multiFn);\r\nmulti(2)(3)(4);\r\nmulti(2,3,4);\r\nmulti(2)(3,4);\r\nmulti(2,3)(4);\r\n```\r\n\r\n![image](https://user-images.githubusercontent.com/20440496/44619592-f5251900-a8bb-11e8-89d7-95a9939b3eb7.png)\r\n\r\n可以看到,通过改进版的柯里化函数,已经将题目定的实现方式扩展到好几种了。这种实现方案的代码扩展性就比较强了,但是还是有点不足,就是必须事先知道求值的参数个数,那能不能让代码更灵活点,达到随意传参的效果,例如: multi(2)(3)(4),multi(5)(6)(7)(8)(9) 这样的。\r\n\r\n#### 优化版\r\n\r\n```javascript\r\nfunction multi() {\r\n    var args = Array.prototype.slice.call(arguments);\r\n\tvar fn = function() {\r\n\t\tvar newArgs = args.concat(Array.prototype.slice.call(arguments));\r\n        return multi.apply(this, newArgs);\r\n    }\r\n    fn.toString = function() {\r\n        return args.reduce(function(a, b) {\r\n            return a * b;\r\n        })\r\n    }\r\n    return fn;\r\n}\r\n```\r\n\r\n![image](https://user-images.githubusercontent.com/20440496/44619613-5816b000-a8bc-11e8-88aa-098d968caf6a.png)\r\n\r\n这样的解决方案就可以灵活的使用了。不足的是返回值是 Function 类型。\r\n\r\n![image](https://user-images.githubusercontent.com/20440496/44619866-243c8a00-a8be-11e8-8ac5-2e00b7ea9bb4.png)\r\n\r\n\r\n\r\n### 总结\r\n\r\n* 就题目本身而言,是存在多种实现方式的,只要理解并充分利用闭包的强大。\r\n* 可能在实际应用场景中,很少使用函数柯里化的解决方案,但是了解认识函数柯里化对自身的提升还是有帮助的。\r\n* 理解闭包和函数柯里化之后,如果在面试中遇到类似的题型,应该就可以迎刃而解了。\r\n\r\n### 参考\r\n\r\n* https://segmentfault.com/q/1010000004014052\r\n* https://blog.csdn.net/crystal6918/article/details/77141741\r\n* [https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==\u0026mid=2651228431\u0026idx=1\u0026sn=c9d62a30a52f4572cc0cb4aaf2a82ef3](https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==\u0026mid=2651228431\u0026idx=1\u0026sn=c9d62a30a52f4572cc0cb4aaf2a82ef3)","author":{"url":"https://github.com/webproblem","@type":"Person","name":"webproblem"},"datePublished":"2018-08-26T13:52:04.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":10},"url":"https://github.com/4/Blog/issues/4"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:d8efc600-e46d-57af-51b4-5e239d779878
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE53E:2D9DEF:1D29EBC:2502761:6975D610
html-safe-nonce21e7fc6ebdf7444b503e49e86bbed2bfd66d4270401d459852348122ebbf9ab1
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNTNFOjJEOURFRjoxRDI5RUJDOjI1MDI3NjE6Njk3NUQ2MTAiLCJ2aXNpdG9yX2lkIjoiNTMyMTA3MTAxOTU1OTM0MzYzMiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac27cfc82c5e2c578d0dddf3718a5d3e0c4f04b69802f39e7341673e10618460ed
hovercard-subject-tagissue:354096564
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/webproblem/Blog/4/issue_layout
twitter:imagehttps://opengraph.githubassets.com/98cb072e2ea3e28e1169290c349886c83b056cc0a6305161808d12410a2f570d/webproblem/Blog/issues/4
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/98cb072e2ea3e28e1169290c349886c83b056cc0a6305161808d12410a2f570d/webproblem/Blog/issues/4
og:image:alt最近在整理面试资源的时候,发现一道有意思的题目,所以就记录下来。 题目 如何实现 multi(2)(3)(4)=24? 首先来分析下这道题,实现一个 multi 函数并依次传入参数执行,得到最终的结果。通过题目很容易得到的结论是,把传入的参数相乘就能够得到需要的结果,也就是 2X3X4 = 24。 简单的实现 那么如何实现 multi 函数去计算出结果值呢?脑海中首先浮现的解决方案是,闭包。...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamewebproblem
hostnamegithub.com
expected-hostnamegithub.com
None2bce766e7450b03e00b2fc5badd417927ce33a860e78cda3e4ecb9bbd1374cc6
turbo-cache-controlno-preview
go-importgithub.com/webproblem/Blog git https://github.com/webproblem/Blog.git
octolytics-dimension-user_id20440496
octolytics-dimension-user_loginwebproblem
octolytics-dimension-repository_id115346710
octolytics-dimension-repository_nwowebproblem/Blog
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id115346710
octolytics-dimension-repository_network_root_nwowebproblem/Blog
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
releasefcca2b8ef702b5f7f91427a6e920fa44446fe312
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://patch-diff.githubusercontent.com/webproblem/Blog/issues/4#start-of-content
https://patch-diff.githubusercontent.com/
Sign in https://patch-diff.githubusercontent.com/login?return_to=https%3A%2F%2Fgithub.com%2Fwebproblem%2FBlog%2Fissues%2F4
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://patch-diff.githubusercontent.com/login?return_to=https%3A%2F%2Fgithub.com%2Fwebproblem%2FBlog%2Fissues%2F4
Sign up https://patch-diff.githubusercontent.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=webproblem%2FBlog
Reloadhttps://patch-diff.githubusercontent.com/webproblem/Blog/issues/4
Reloadhttps://patch-diff.githubusercontent.com/webproblem/Blog/issues/4
Reloadhttps://patch-diff.githubusercontent.com/webproblem/Blog/issues/4
webproblem https://patch-diff.githubusercontent.com/webproblem
Bloghttps://patch-diff.githubusercontent.com/webproblem/Blog
Notifications https://patch-diff.githubusercontent.com/login?return_to=%2Fwebproblem%2FBlog
Fork 15 https://patch-diff.githubusercontent.com/login?return_to=%2Fwebproblem%2FBlog
Star 113 https://patch-diff.githubusercontent.com/login?return_to=%2Fwebproblem%2FBlog
Code https://patch-diff.githubusercontent.com/webproblem/Blog
Issues 10 https://patch-diff.githubusercontent.com/webproblem/Blog/issues
Pull requests 0 https://patch-diff.githubusercontent.com/webproblem/Blog/pulls
Actions https://patch-diff.githubusercontent.com/webproblem/Blog/actions
Projects 0 https://patch-diff.githubusercontent.com/webproblem/Blog/projects
Security 0 https://patch-diff.githubusercontent.com/webproblem/Blog/security
Insights https://patch-diff.githubusercontent.com/webproblem/Blog/pulse
Code https://patch-diff.githubusercontent.com/webproblem/Blog
Issues https://patch-diff.githubusercontent.com/webproblem/Blog/issues
Pull requests https://patch-diff.githubusercontent.com/webproblem/Blog/pulls
Actions https://patch-diff.githubusercontent.com/webproblem/Blog/actions
Projects https://patch-diff.githubusercontent.com/webproblem/Blog/projects
Security https://patch-diff.githubusercontent.com/webproblem/Blog/security
Insights https://patch-diff.githubusercontent.com/webproblem/Blog/pulse
New issuehttps://patch-diff.githubusercontent.com/login?return_to=https://github.com/webproblem/Blog/issues/4
New issuehttps://patch-diff.githubusercontent.com/login?return_to=https://github.com/webproblem/Blog/issues/4
从一道面试题认识函数柯里化https://patch-diff.githubusercontent.com/webproblem/Blog/issues/4#top
JavaScripthttps://github.com/webproblem/Blog/issues?q=state%3Aopen%20label%3A%22JavaScript%22
https://github.com/webproblem
https://github.com/webproblem
webproblemhttps://github.com/webproblem
on Aug 26, 2018https://github.com/webproblem/Blog/issues/4#issue-354096564
https://user-images.githubusercontent.com/20440496/44616464-dce4d800-a882-11e8-94be-fb73f543fce4.png
https://user-images.githubusercontent.com/20440496/44618906-70350200-a8b1-11e8-8e0b-bd015b263630.png
https://user-images.githubusercontent.com/20440496/44619592-f5251900-a8bb-11e8-89d7-95a9939b3eb7.png
https://user-images.githubusercontent.com/20440496/44619613-5816b000-a8bc-11e8-88aa-098d968caf6a.png
https://user-images.githubusercontent.com/20440496/44619866-243c8a00-a8be-11e8-8ac5-2e00b7ea9bb4.png
https://segmentfault.com/q/1010000004014052https://segmentfault.com/q/1010000004014052
https://blog.csdn.net/crystal6918/article/details/77141741https://blog.csdn.net/crystal6918/article/details/77141741
https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651228431&idx=1&sn=c9d62a30a52f4572cc0cb4aaf2a82ef3https://mp.weixin.qq.com/s?__biz=MjM5MTA1MjAxMQ==&mid=2651228431&idx=1&sn=c9d62a30a52f4572cc0cb4aaf2a82ef3
JavaScripthttps://github.com/webproblem/Blog/issues?q=state%3Aopen%20label%3A%22JavaScript%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.