Funções em JavaScript: segredos que você nunca ouviu falar

O que todo programador profissional de JavaScript deve saber

Olá, Habr! Convidamos futuros alunos do curso "JavaScript Developer. Professional" a participar de um webinar aberto sobre o tema "Fazendo um bot de Telegram interativo em NodeJs" .

Também compartilhamos a tradução tradicional de um artigo útil.


Todo programador pode escrever funções. Eles são frequentemente chamados de objetos de primeira classe porque são um conceito chave do JavaScript. Mas você sabe como usá-los de forma eficaz?

Hoje darei algumas dicas para o manuseio de funções avançadas. Espero que você os ache úteis. O artigo contém várias seções:

  • Funções puras

  • Funções de ordem superior

  • Cache de função

  • Funções preguiçosas

  • Escovando

  • Composição de funções

Funções puras

O que é uma função pura?

Uma função é chamada limpa se ambas as condições a seguir forem atendidas:

  • para os mesmos argumentos, ele retorna o mesmo valor;

  • nenhum efeito colateral ocorre durante a execução da função.

Exemplo 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