zoukankan      html  css  js  c++  java
  • [Javascript] What is JavaScript Function Currying?

    Currying is a core concept of functional programming and a useful tool for any developer's toolbelt. 

    Example 1:

    let f = a => b => c => a+b+c;
    
    let result = f(1)(2)(3);
    console.log(result); // 6

    Example 2:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.18.0/ramda.min.js"></script>
    </head>
    <body>
    <div id="one" style=" 100px;height: 100px;border: 2px solid black">One</div>
    <div id="two" style=" 100px;height: 100px;border: 2px solid black">Two</div>
    <div id="three" style=" 100px;height: 100px;border: 2px solid black">Three</div>
    </body>
    </html>
    let one = document.getElementById('one');
    let tow = document.getElementById('two');
    let three = document.getElementById('three');
    
    let f = a => b => c => a.addEventListener(b, (event)=>{
      event.target.style.background = c;
    });
    
    f(one)('click')('red');

    Example 3: 

    let one = document.getElementById('one');
    let tow = document.getElementById('two');
    let three = document.getElementById('three');
    
    let f = a => b => c => a.addEventListener(b, (event)=>{
      event.target.style.background = c;
    });
    
    let oneClickEvent = f(one);
    let twoClickEvent = f(two);
    
    
    oneClickEvent('mouseover')('red');
    twoClickEvent('mouseout')('blue');

    Example 4: include ramda library:

    let one = document.getElementById('one');
    let tow = document.getElementById('two');
    let three = document.getElementById('three');
    
    let f = R.curry((a,b,c) =>{
      a.addEventListener(b, (event)=>{
        event.target.style.background = c;
      });
    });
    
    // with placeholder from Ramda
    const clickGreen = f(R.__, 'click', 'green');
    clickGreen(one);

    Example 5: multi placeholders:

    let one = document.getElementById('one');
    let tow = document.getElementById('two');
    let three = document.getElementById('three');
    
    let f = R.curry((a,b,c) =>{
      a.addEventListener(b, (event)=>{
        event.target.style.background = c;
      });
    });
    
    // with placeholder from Ramda
    const clickColor = f(R.__, 'click', R.__);
    clickColor(one, 'yellow');
    clickColor(two, 'grey');
    clickColor(three, 'pink');

  • 相关阅读:
    爬虫-基于scrapy-redis两种形式的分布式爬虫
    爬虫-Scrapy框架(CrawlSpider)
    爬虫-User-Agent和代理池
    爬虫-scrapy框架之递归解析和post请求
    爬虫-scrapy数据的持久化存储
    爬虫-scrapy框架简介和基础应用
    爬虫-移动端数据爬取
    爬虫-图片懒加载技术、selenium和PhantomJS
    爬虫-验证码处理
    爬虫-requests模块
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5003880.html
Copyright © 2011-2022 走看看