Comments (19)
考点:函数柯里化
函数柯里化概念: 柯里化(Currying)是把接受多个参数的函数转变为接受一个单一参数的函数,并且返回接受余下的参数且返回结果的新函数的技术。
1)粗暴版
function add (a) {
return function (b) {
return function (c) {
return a + b + c;
}
}
}
console.log(add(1)(2)(3)); // 6
2)柯里化解决方案
- 参数长度固定
const curry = (fn) =>
(judge = (...args) =>
args.length === fn.length
? fn(...args)
: (...arg) => judge(...args, ...arg));
const add = (a, b, c) => a + b + c;
const curryAdd = curry(add);
console.log(curryAdd(1)(2)(3)); // 6
console.log(curryAdd(1, 2)(3)); // 6
console.log(curryAdd(1)(2, 3)); // 6
- 参数长度不固定
function add (...args) {
//求和
return args.reduce((a, b) => a + b)
}
function currying (fn) {
let args = []
return function temp (...newArgs) {
if (newArgs.length) {
args = [
...args,
...newArgs
]
return temp
} else {
let val = fn.apply(this, args)
args = [] //保证再次调用时清空
return val
}
}
}
let addCurry = currying(add)
console.log(addCurry(1)(2)(3)(4, 5)()) //15
console.log(addCurry(1)(2)(3, 4, 5)()) //15
console.log(addCurry(1)(2, 3, 4, 5)()) //15
from fe-interview.
除了typeof为function 正常运算都没问题
function add(num) {
const add2 = (num2) => {
num = num + num2;
add2.toString = () => num;
return add2;
}
return add2;
}
add(1)(2)(3) + 5 // 11
add(1)(2)(3)(4) // ƒ 10
from fe-interview.
const add = (a: number, b: number, c: number) => a + b + c;
const adding = (...args: number[]) => args.reduce((pre, cur) => pre + cur, 0);
//参数确定
const curry = (fn: Function) => {
let args = [];
return function temp(...newArgs) {
args.push(...newArgs);
if (args.length === fn.length) {
const val = fn.apply(this, args);
args = [];
return val;
} else {
return temp;
}
};
};
//参数不确定
const currying = (fn: Function) => {
let args = [];
return function temp(...newArgs) {
if (newArgs.length) {
args.push(...newArgs);
return temp;
} else {
const val = fn.apply(this, args);
args = [];
return val;
}
};
};
const curryAdd = curry(add);
console.log(curryAdd(1)(2)(3)); // 6
console.log(curryAdd(1, 2)(3)); // 6
console.log(curryAdd(1)(2, 3)); // 6
let addCurry = currying(adding);
console.log(addCurry(1)(2)(3)(4, 5)()); //15
console.log(addCurry(1)(2)(3, 4, 5)()); //15
console.log(addCurry(1)(2, 3, 4, 5)()); //15
from fe-interview.
function currying(){
let args = [...arguments]
temp.getValue = ()=>{
return args.reduce((a,b)=> a + b, 0)
}
function temp(...arg){
if(arg.length){
args = [
...args,
...arg
]
return temp
}
}
return temp
}
from fe-interview.
const add = a => b => c => a + b + c
from fe-interview.
function curry(...args1) {
const fn = args1[0]
const restArgs = args1.slice(1)
function curried(...args2) {
return curry.call(this, fn, ...[...restArgs, ...args2])
}
curried.toString = function() {
return fn.call(this, ...restArgs)
}
return curried
}
function sum(...args) {
let result = 0
args.forEach(arg => {
result += arg
})
return result
}
const add = curry(sum)
// toString 修改了但是不生效,需要自己利用 + 操作符进行转换
console.log(+add(1)(2)(3, 4, 5))
from fe-interview.
function curring(fn,arr = []){
var length = fn.length;
return (...args) => {
const currentArr = [...arr.push(args)]
if(arr.length < length){
return curring(fn,currentArr];
} else {
fn(...currentArr )
}
}
}
from fe-interview.
function currying(fn, args = []) {
return function temp(...innerArgs) {
if (innerArgs.length > 0) {
// 收集后面传入的参数
args = [...args, ...innerArgs];
// 返回函数供后面可以继续调用
return temp;
} else {
const val = fn.apply(this, args);
// 清空参数数组,为了保证下次执行函数可以继续迭代
args = [];
return val;
}
}
}
// 求和函数
const add = (...args) => args.reduce((a, b) => a + b);
let addCurry = currying(add)
console.log(addCurry(1)(2)(3)(4, 5)()) //15
console.log(addCurry(1)(2)(3, 4, 5)()) //15
console.log(addCurry(1)(2, 3, 4, 5)()) //15
from fe-interview.
有个疑问,就是参数长度不固定时,addCurry(1)(2)(3)(4, 5)(),最后的需要加函数执行的(),但是题目不是没有吗,也就是只要addCurry(1)(2)(3)(4, 5)这样
from fe-interview.
function curry(fn, ...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...args2) => curry(fn, ...args, ...args2);
}
function sum(a, b, c) {
return a + b + c;
}
let add = curry(sum);
console.log(add(1)(2)(3));
from fe-interview.
function add (...params) {
let result = params.reduceRight((a, b) => a + b)
const tmp = (...paramsInit) => {
result = [...paramsInit, result].reduceRight((a, b) => a + b)
return tmp
}
tmp.toString = () => `${result}`
tmp.valueOf = () => result
return tmp
}
可以这样实现
@ABoyCDog
from fe-interview.
const curryAdd = (...args) => {
const Add = (...args2) => {
return curry(...args, ...args2)
}
Add.toString = () => args.reduce((t, v) => t+v);
return Add
}
console.log(curryAdd(1)(2)(3,4))
from fe-interview.
function curry(fn, args) {
var length = fn.length;
args = args || [];
return function () {
newArgs = args.conct(Array.prototype.slice.call(arguments));
return newArgs.length < length
? curry.call(this, fn, newArgs)
: fn.apply(this, newArgs);
};
}
function multiFn(a, b, c) {
return a * b * c;
}
var multi = curry(multiFn);
console.log(multi(2)(3)(4));
from fe-interview.
const sum = (arr) => {
return arr.reduce((pre, cur, index) => {
return pre + cur
}, 0)
}
function add() {
const outArgs = Array.from(arguments)
let res = sum(outArgs);
function newAdd() {
if (arguments.length > 0) {
const innerArgs = Array.from(arguments);
res += sum(innerArgs)
return newAdd
} else {
return res;
}
}
newAdd.valueOf = function () {
return res
}
newAdd.toString = function () {
return res + ''
}
return newAdd
}
var result = add(1, 2)(3)(4)(5); // 参数可能为多个的情况下
console.log(result());
from fe-interview.
function curry(fn, args) {
const { length } = fn;
const params = args || [];
return function() {
const args = params.concat([].slice.call(arguments));
if (args.length < length) {
return curry.apply(this, fn, args);
} else {
return fn.apply(this, args);
}
}
}
from fe-interview.
const curryAdd = (...args) => { const Add = (...args2) => { return curry(...args, ...args2) } Add.toString = () => args.reduce((t, v) => t+v); return Add } console.log(curryAdd(1)(2)(3,4))
测一测吧,测好了再发出来。curry已经undefined了。
from fe-interview.
const curry = (fn) => {
const prevArgs = [];
const rec = (...currArgs) => {
prevArgs.push(...currArgs);
if(fn.length - prevArgs.length <= 0) {
return fn(...prevArgs);
}
return rec;
}
return rec;
}
const add = (a: number, b: number, c: number) => a + b + c;
const curryAdd = curry(add);
from fe-interview.
函数的柯里化的应用
const curry = (fn, args) => {
const length = fn.length;
let _args = args || [];
return function () {
let argArray = _args.slice(0);
for (let i = 0; i < arguments.length; i++) {
argArray.push(arguments[i]);
}
if (argArray.length < length) {
return curry(fn, argArray);
} else {
return fn.apply(this, argArray);
}
}
}
const add = curry(function (a, b, c) {
return a + b + c;
})
console.log(add(1)(2)(3));
from fe-interview.
function curry(fn) {
const length = fn.length
return function _curry(...args) {
if (args.length >= length) {
return fn.apply(this, args)
} else {
return _curry.bind(this, ...args)
}
}
}
// 测试
function add(x, y, z) {
return this.val + x + y + z
}
let fun1 = curry(add)
let obj = {
val: 10,
fun1
}
console.log(obj.fun1(1)(2)(3))
from fe-interview.
Related Issues (20)
- Day378:说一下什么是 Http 协议无状态?怎么解决 Http 协议无状态?
- Day379:如果让你来实现一个前端监控系统,应该考虑什么?如何去实现?
- Day380:实现一个系统,统计前端页面性能、页面 JS 报错、用户操作行为、PV/UV、用户设备等消息,并进行必要的监控报警。方案如何设计,用什么技术点,什么样的系统架构,难点会在哪里? HOT 3
- Day381:说一下 JavaScript 严格模式下有哪些不同?
- Day382:说一下 setTimeout 和 setInterval 的区别,包含内存方面的分析?
- Day383:说下 React 的 useEffect、useCallback、useMemo HOT 2
- Day384:JavaScript 中如何实现一个类?怎么实例化这个类? HOT 2
- Day385:在一个 DOM 上同时绑定两个点击事件:一个用捕获,一个用冒泡。事件会执行几次?先执行冒泡还是捕获? HOT 9
- Day386:写一个通用的事件侦听器函数 HOT 3
- 定时函数 HOT 1
- 小程序不维护了吗? HOT 10
- --
- 小程序里面的内容还有其他地方能学习吗
- 求小程序哇!!不然学习效率太低了 HOT 1
- 现在还能在哪里看题目答案吗?小程序关闭了😭😭 HOT 1
- #### 1)为什么会有Event Loop
- > > > @Genzhen 请教一下大佬,如果在render里面结构赋值也会影响性能吗?比如 const { page, size } = this.state这种的? HOT 1
- 考察原型链
- issue路径错误,提不了pr,可见下图
- vue中&nextTick的原理
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fe-interview.