Funciones en JavaScript: secretos de los que no ha oído hablar

Lo que todo programador profesional de JavaScript debe saber

¡Hola, Habr! Invitamos a los futuros alumnos del curso "JavaScript Developer. Professional" a participar en un webinar abierto sobre el tema "Cómo hacer un bot de Telegram interactivo en NodeJs" .

También compartimos la traducción tradicional de un artículo útil.


Todo programador puede escribir funciones. A menudo se les conoce como objetos de primera clase porque son un concepto clave de JavaScript. Pero, ¿sabe cómo utilizarlos de forma eficaz?

Hoy daré algunos consejos para funciones avanzadas. Espero que te sean de utilidad. El artículo contiene varias secciones:

  • Funciones puras

  • Funciones de orden superior

  • Caché de funciones

  • Funciones perezosas

  • Zurra

  • Composición de funciones

Funciones puras

¿Qué es una función pura?

Una función se llama limpia si se cumplen las dos condiciones siguientes:

  • ;

  • .

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