JavaScript中的函数:您从未听说过的秘密

每个专业的JavaScript程序员应该知道什么

哈Ha!我们邀请课程“ JavaScript Developer。Professional”的未来学生参加有关“在NodeJs上创建交互式Telegram bot”主题的开放式网络研讨会

我们还将分享有用文章的传统翻译。


每个程序员都可以编写函数。它们通常被称为一流对象,因为它们是JavaScript的关键概念。但是您知道如何有效使用它们吗?

今天,我将提供一些高级功能的提示。希望您发现它们有用。本文包含几个部分:

  • 纯功能

  • 高阶函数

  • 功能缓存

  • 懒函数

  • 咖喱

  • 功能组成

纯功能

什么是纯函数?

如果同时满足以下两个条件,则该函数被称为纯函数:

  • ;

  • .

1

function circleArea(radius){
  return radius * radius * 3.14
}

, . , . .

2

let counter = (function(){
  let initValue = 0
  return function(){
    initValue++;
    return initValue
  }
})()



- , .

3

let femaleCounter = 0;
let maleCounter = 0;
function isMale(user){
  if(user.sex = 'man'){
    maleCounter++;
    return true
  }
  return false
}

isMale , , . maleCounter, .

?

? . , .

1. , .

. .

2. .

.

for (int i = 0; i < 1000; i++){
    console.log(fun(10));
}

fun , fun(10) 1000 .

fun , . , , .

let result = fun(10)
for (int i = 0; i < 1000; i++){
    console.log(result);
}

3. .

. assert , .

. 1.

const incrementNumbers = function(numbers){
  // ...
}

:

let list = [1, 2, 3, 4, 5];
assert.equals(incrementNumbers(list), [2, 3, 4, 5, 6])

, , .

?

:

  • ;

  • .

, .

, . , , .

:

const arr1 = [1, 2, 3];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
    arr2.push(arr1[i] * 2);
}

JavaScript map().

map(callback) , .

const arr1 = [1, 2, 3];
const arr2 = arr1.map(function(item) {
  return item * 2;
});
console.log(arr2);

map — .

, . .

, :

function computed(str) {    
    // Suppose the calculation in the funtion is very time consuming        
    console.log('2000s have passed')
      
    // Suppose it is the result of the function
    return 'a result'
}

, , . ?

cached . , , , . cached , Object Map.

function cached(fn){
  // Create an object to store the results returned after each function execution.
  const cache = Object.create(null);

  // Returns the wrapped function
  return function cachedFn (str) {

    // If the cache is not hit, the function will be executed
    if ( !cache[str] ) {
        let result = fn(str);

        // Store the result of the function execution in the cache
        cache[str] = result;
    }

    return cache[str]
  }
}

:

, .

, «» , . .

, foo, Date, .

let fooFirstExecutedDate = null;
function foo() {
    if ( fooFirstExecutedDate != null) {
      return fooFirstExecutedDate;
    } else {
      fooFirstExecutedDate = new Date()
      return fooFirstExecutedDate;
    }
}

. , . - .

:

var foo = function() {
    var t = new Date();
    foo = function() {
        return t;
    };
    return foo();
}

.  — .

.

DOM - , IE. :

function addEvent (type, el, fn) {
    if (window.addEventListener) {
        el.addEventListener(type, fn, false);
    }
    else if(window.attachEvent){
        el.attachEvent('on' + type, fn);
    }
}

addEvent . , :

function addEvent (type, el, fn) {
  if (window.addEventListener) {
      addEvent = function (type, el, fn) {
          el.addEventListener(type, fn, false);
      }
  } else if(window.attachEvent){
      addEvent = function (type, el, fn) {
          el.attachEvent('on' + type, fn);
      }
  }
  addEvent(type, el, fn)
}

, , , , . , .

 — .

, , , ; — , .

?

  • .

  • . .

  • .

add. .

function add(a,b,c){
 return a + b + c;
}

( ) , , ( ).

add(1,2,3) --> 6 
add(1,2) --> NaN
add(1,2,3,4) --> 6 //Extra parameters will be ignored.

?

:

function curry(fn) {
    if (fn.length <= 1) return fn;
    const generator = (...args) => {
        if (fn.length === args.length) {

            return fn(...args)
        } else {
            return (...args2) => {

                return generator(...args, ...args2)
            }
        }
    }
    return generator
}

:

, , :

bitfish, HELLO, BITFISH

, :

  • ;

  • .

:

let toUpperCase = function(x) { return x.toUpperCase(); };
let hello = function(x) { return 'HELLO, ' + x; };
let greet = function(x){
    return hello(toUpperCase(x));
};

, (greet) . , greet : fn3(fn2(fn1(fn0(x)))).

compose, :

let compose = function(f,g) {
    return function(x) {
        return f(g(x));
    };
};

, greet compose:

let greet = compose(hello, toUpperCase);
greet('kevin');

compose , , .

compose , , .

underscore compose .

function compose() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
        var i = start;
        var result = args[start].apply(this, arguments);
        while (i--) result = args[i].call(this, result);
        return result;
    };
};

, , .


- "JavaScript Developer. Professional".

- " Telegram NodeJs" .




All Articles