وظائف في JavaScript: أسرار لم تسمع بها من قبل

ما يجب أن يعرفه كل مبرمج جافا سكريبت محترف

مرحبا هبر! ندعو الطلاب المستقبليين لدورة "JavaScript Developer. Professional" للمشاركة في ندوة مفتوحة عبر الويب حول موضوع "إنشاء برنامج Telegram تفاعلي على NodeJs" .

نشارك أيضًا الترجمة التقليدية لمقال مفيد.


يمكن لكل مبرمج كتابة وظائف. غالبًا ما يشار إليها على أنها كائنات من الدرجة الأولى لأنها مفهوم 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