Underscore source code analysis, underscore source code

Source: Internet
Author: User

Underscore source code analysis, underscore source code

Some people said a few years ago that javascript is the most undervalued programming language. Since the emergence of nodejs, the concept of Full-end (All Stack/Full Stack) has gradually emerged, no one dares to underestimate it now. Javascrip is a type of C language. It can understand javascript code in a large way based on C language. However, as a scripting language, the flexibility of javascript is far from that of C, this will also cause some learning difficulties.

1. Set

1. First, there are several iterative methods.

_. Each = _. forEach = function (obj, iteratee, context) {iteratee = optimizeCb (iteratee, context); var I, length; if (isArrayLike (obj) {for (I = 0, length = obj. length; I <length; I ++) {iteratee (obj [I], I, obj) ;}} else {var keys = _. keys (obj); for (I = 0, length = keys. length; I <length; I ++) {iteratee (obj [keys [I], keys [I], obj) ;}// chained call return obj ;};

ES also adds the native forEach () method to the array. The difference is that the each (forEach) method can be used for all sets. The function accepts three parameters (set, iterative function, and execution environment ).

The optimizeCb function binds the corresponding execution environment for different iteration methods based on the number of iteration function parameters. The forEach iteration function also accepts three parameters (values, indexes, and sets ).

Next we will call the iterative function in the for loop.

_. Map: (use only one for loop)

Var keys =! IsArrayLike (obj )&&_. keys (obj), length = (keys | obj ). length, results = Array (length); for (var index = 0; index <length; index ++) {var currentKey = keys? Keys [index]: index; results [index] = iteratee (obj [currentKey], currentKey, obj);} return results; // reasonably used &, | ,? : Can greatly reduce the amount of code

There are two special points:

• The set is divided into class array sets and object sets. The isArrayLike function is used:

// Max precise integer var MAX_ARRAY_INDEX = Math. pow (2, 53)-1; var isArrayLike = function (collection) {var length = collection! = Null & collection. length; return typeof length = 'number' & length> = 0 & length <= MAX_ARRAY_INDEX ;}; // If the set has the Length attribute and is a number greater than 0 and smaller than the maximum exact integer, it is determined to be a class Array

• The _. keys function is used, and the Object also has a native keys function, which is used to return an attribute array whose collection obj can be enumerated. The implementation is relatively simple, and the hasOwnProperty () method is added for in.


The principle of the _. map, _. reduce method is similar.

The _. find function is similar to Array. some (). The difference is that the first element that makes the iteration result true is returned, rather than the Boolean value returned by Array. some.

_. Find = _. detect = function (obj, predicate, context) {var key; if (isArrayLike (obj) {key = _. findIndex (obj, predicate, context);} else {key = _. findKey (obj, predicate, context);} if (key! = Void 0 & key! =-1) return obj [key] ;}; function createIndexFinder (dir) {return function (array, predicate, context) {predicate = cb (predicate, context ); var length = array! = Null & array. length; // If dir is 1, index is 0, index + = 1, index is a forward-order loop // If dir is-1, index is length-1, index + =-1 back-order loop // index> = 0 & index <length is used to determine the cycle condition. Both the var index = dir> 0? 0: length-1; for (; index> = 0 & index <length; index + = dir) {if (predicate (array [index], index, array )) return index;} return-1 ;};}_. findIndex = createIndexFinder (1 );_. findLastIndex = createIndexFinder (-1 );

It is worth learning that a for loop can be configured with different cyclic sequence based on different input parameters.

1. Other methods in the set are basically implemented based on iterative methods.

_.max = function(obj, iteratee, context) {var result = -Infinity, lastComputed = -Infinity,  value, computed;if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) {  value = obj[i];  if (value > result) {   result = value;  } }} else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) {  computed = iteratee(value, index, list);  if (computed > lastComputed || computed === -Infinity && result === -Infinity) {   result = value;   lastComputed = computed;  } });}return result; }; 

The max method is used to find the maximum value in the set. It loops through all items in the list, and then compares the current item and result item. If the current item is greater than the result item, it is assigned to the result item, the final returned result.

2. convert a set to an array

_. ToArray = function (obj) {if (! Obj) return []; // if it is an Array, Array is used. prototype. slice. call (this, obj) this method if (_. isArray (obj) return slice. call (obj); // array object of the class, which is used instead of Slice. map iterates the set to return an array. _. Identity the value passed in by this method is equal to the returned value. (Mainly used for iteration) if (isArrayLike (obj) return _. map (obj, _. identity); // returns an array composed of attribute values. Return _. values (obj );};

Data Type

STL needs to differentiate vector, list, and so on because different data structures need or can be implemented differently. But what is the separation between Collections and Arrays in underscore? This also depends on the javascript data type.

Articles you may be interested in:
  • Introduction and application of the template function of Underscore. js
  • Summary of common Underscore. js Methods
  • Underscore. js 1.3.3 explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.