Underscore.js what is needed? Popular functions. Examples of... open

Underscore.js what is needed? Popular functions. Examples of use

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Underscore.js is a JavaScript library that provides a set of useful functions for working with data and functional programming. It is used to simplify data manipulation in JavaScript and provides a convenient and efficient way to work with arrays, objects, collections, and functions.

The main reasons to use Underscore.js include the following:

  • Data Manipulation: Underscore.js provides functions for filtering, sorting, transforming, joining, grouping, and other operations on arrays and objects. This allows you to perform complex data manipulations in a convenient and understandable way.
  • Functional Programming: Underscore.js supports functions for functional programming such as reduce, map, filter, compose and many others. This allows you to use functional approaches to solving tasks and make the code more elegant and expressive.
  • Cross-Browser Support: Underscore.js provides cross-browser level support that helps avoid differences in the implementation of JavaScript functionality between different environments.
  • Ease of use: The library has a simple and clear API that allows you to quickly get started with it. Underscore.js is relatively lightweight and small in size, allowing it to be quickly incorporated into projects and used in a variety of scenarios.

How add underscore to your project?

To connect the Underscore.js library to your project, you can follow these steps:

  1. Download the Underscore.js file: First of all, you need to download the Underscore.js file. You can download it from the official Underscore.js website (https://underscorejs.org/) or use a package manager like npm or Yarn to install the package.
  2. Link the file to your HTML: After downloading the Underscore.js file, you need to link it to your HTML file. Add the following script tag to the head section or before the closing body tag of your HTML file:

    <script src="path/to/underscore.js"></script>
    
  3. Use Underscore.js Functions: After successfully linking the library, you can use its functions in your JavaScript code.

Methods for working with collections and arrays

Here are some examples of Underscore.js methods for working with collections and arrays:

_.each(collection, iteratee) – This method allows you to iterate each element of the collection and apply the (iteratee) function to it.

_.each([1, 2, 3], function(num) {
  console.log(num);
});
// 
// 1
// 2
// 3

_.map(collection, iteratee) – This method creates a new array that contains the results of applying the function (iteratee) to each element of the collection.

var numbers = [1, 2, 3];
var squaredNumbers = _.map(numbers, function(num) {
  return num * num;
});
console.log(squaredNumbers);
//[ 1, 4, 9 ]

_.partition(array, predicate) – This method divides the array into two groups: one where the elements satisfy the condition (predicate) and another where they do not. An array consisting of two subarrays is returned.

var numbers = [1, 2, 3, 4, 5, 6];
var isEven = function(num) {
  return num % 2 === 0;
};
var result = _.partition(numbers, isEven);
console.log(result);
[2, 4, 6], [1, 3, 5]]

_.shuffle(array) – This method shuffles the array elements and returns a new array with the shuffled elements.

var numbers = [1, 2, 3, 4, 5];
var shuffledNumbers = _.shuffle(numbers);
console.log(shuffledNumbers);

_.filter(collection, predicate) – This method filters a collection or array by a given condition (predicate) and returns a new array that contains elements satisfying this condition.

var numbers = [1, 2, 3, 4, 5];
var evenNumbers = _.filter(numbers, function(num) {
  return num % 2 === 0;
});
console.log(evenNumbers);
//[2, 4]

_.reduce(collection, iteratee, [accumulator]) – This method reduces (reduces) a collection or array to a single value using the (iteratee) function. You can specify an initial value (accumulator), which will be used for the first call of the function.

var numbers = [1, 2, 3, 4, 5];
var sum = _.reduce(numbers, function(total, num) {
  return total + num;
}, 0);
console.log(sum);
//15

_.groupBy(collection, iteratee) – This method groups the elements of a collection or array by the value returned by the function (iteratee) and returns an object where the keys are the unique values according to the grouping and the values are the arrays of elements that belong to this groups

var persons = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
];
var groupedByAge = _.groupBy(persons, 'age');
console.log(groupedByAge);

will return

{
  '25': [
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 25 }
  ],
  '30': [
    { name: 'John', age: 30 },
    { name: 'Alice', age: 30 }
  ]
}

_.sortBy(collection, iteratee) – This method sorts the collection or array by the values returned by the function (iteratee) and returns a new array with the sorted elements.

var numbers = [5, 2, 8, 1, 4];
var sortedNumbers = _.sortBy(numbers);
console.log(sortedNumbers);
// Виведе: [1, 2,]

These are just a few examples of Underscore.js methods for working with collections and arrays. The library has many other useful methods that can be used in various scenarios of working with data. For more detailed information about all methods, I recommend that you read the documentation on the official Underscore.js website (https://underscorejs.org/).

Methods which work only with arrays

Here are a few Underscore.js methods that are specifically designed to work with arrays:

_.first(array) – Returns the first element of the array.

var numbers = [1, 2, 3, 4, 5];
var firstElement = _.first(numbers);
console.log(firstElement);
// 1

_.last(array) – Returns the last element of the array.

var numbers = [1, 2, 3, 4, 5];
var lastElement = _.last(numbers);
console.log(lastElement);

_.compact(array) – Returns a new array, removing all “false” values such as false, null, 0, “”, undefined, and NaN.

var values = [1, 0, false, '', undefined, NaN, 5];
var compactArray = _.compact(values);
console.log(compactArray);
// [1, 5]

_.flatten(array, [shallow]) – Returns a new array in which all nested arrays are “expanded” (put above), at the specified depth. By default, shallow is set to false, which means to expand all nested arrays.

var nestedArray = [1, [2, [3, [4]]]];
var flattenedArray = _.flatten(nestedArray);
console.log(flattenedArray);
// [1, 2, 3, 4]

_.without(array, *values) – Returns a new array that does not contain the specified values.

var numbers = [1, 2, 3, 4, 5];
var filteredArray = _.without(numbers, 2, 4);
console.log(filteredArray);
// [1, 3, 5]

These are just a few methods that are specifically designed to work with arrays in Underscore.js. The library also provides many other methods such as _.union(), _.intersection(), _.difference() and _.uniq() that help perform various operations on arrays.

Methods for working with functions

Underscore.js provides several methods for working with functions. Here are a few of them:

_.bind(func, context, [arguments…]) – This method returns a new function in which the context (this) of the function func is bound to the context object. Additional arguments (if specified) will be passed to the initial function.

var greet = function() {
  console.log('Hello, ' + this.name);
};

var person = {
  name: 'John'
};

var boundGreet = _.bind(greet, person);
boundGreet();
//"Hello, John"

_.debounce(func, wait, [immediate]) – This method returns a new function that limits the frequency of calls to func to once per wait milliseconds. If the immediate parameter is set to true, the function will be called immediately on the first call, not after a wait of milliseconds.

var saveChanges = function() {
  console.log('Changes saved.');
};

var debounceSaveChanges = _.debounce(saveChanges, 1000);

debounceSaveChanges();
debounceSaveChanges();
debounceSaveChanges();
//Will output: "Changes saved." (after 1 second)

_.throttle(func, wait) – This method returns a new function that limits the frequency of calling func to once per wait milliseconds. Function calls that occurred during the wait period will be ignored.

var logMessage = function() {
  console.log('Message logged.');
};

var throttledLogMessage = _.throttle(logMessage, 1000);

throttledLogMessage();
throttledLogMessage();
throttledLogMessage();
// Output: "Message logged." (only after the first call, after 1 second)

_.delay(func, wait, [arguments…]) – This method calls the func function after the specified wait delay (in milliseconds). You can also pass additional arguments to be passed to the function.

var greet = function(name) {
  console.log('Hello, ' + name);
};

_.delay(greet, 2000, 'John');

_.defer(func, [arguments…]) – This method defers the execution of func until the call stack is empty. You can also pass additional arguments to be passed to the function.

var logMessage = function() {
  console.log('Message logged.');
};

_.defer(logMessage);
console.log('After defer');
// Виведе: "After defer" перед "Message logged."

Utilities

The utilities in the Underscore.js library represent a set of useful functions that are not related to working with collections, functions, or arrays. They provide additional functionality for working with data. Here are some examples of utilities in Underscore.js:

_.isEmpty(value) – This function checks if value is empty. Returns true if the value is empty and false if it is not.

console.log(_.isEmpty({})); // true
console.log(_.isEmpty([])); //  true
console.log(_.isEmpty('')); // true
console.log(_.isEmpty({ name: 'John' })); // false
console.log(_.isEmpty([1, 2, 3])); // false
console.log(_.isEmpty('Hello')); // false

_.isArray(value) – This function checks if value is an array. Returns true if the value is an array and false if it is not.

console.log(_.isArray([1, 2, 3])); // true
console.log(_.isArray({ name: 'John' })); // false
console.log(_.isArray('Hello')); //  false

_.isFunction(value) – This function checks if value is a function. Returns true if the value is a function and false if it is not.

console.log(_.isFunction(function() {})); // true
console.log(_.isFunction({ name: 'John' })); //  false
console.log(_.isFunction('Hello')); // false

_.extend(destination, *sources) – This function merges the contents of several objects into one destination object. Values from recent objects overlap values from previous objects with the same key.

var obj1 = { name: 'John', age: 30 };
var obj2 = { profession: 'Developer' };
var obj3 = { age: 35 };

var mergedObj = _.extend(obj1, obj2, obj3);
console.log(mergedObj);

_.times(n, iteratee, [context]) – This method executes the function iteratee n times. It is called with an index from 0 to n-1. If necessary, you can pass the context parameter, which will be used as this in the iteratee function.

_.times(3, function(n) {
  console.log(n);
});
//  0, 1, 2

_.random(min, max) – This method generates a random number between min and max. It can be an integer or a floating point number.

var randomNum = _.random(1, 10);
console.log(randomNum);

Method template

The _.template method in the Underscore.js library is used to create string templates. It allows you to replace certain parts of a template with values from an object or data array.

_.template(templateString, [data], [settings])

templateString: A template string containing wildcards.

data (optional): An object or array of data used to substitute values into the pattern. By default, the template uses the with construct to access the properties of the data object.

settings (optional): Template settings.

var templateString = "<h1>Hello, <%= name %>!</h1>";
var data = { name: "John" };

var compiledTemplate = _.template(templateString);
var result = compiledTemplate(data);

console.log(result);
//<h1>Hello, John!</h1>

The template uses <%= name %> to substitute the value of the name property from the data object. After compiling the template, the resulting function is called, to which the data object is passed, and the resulting result is returned.

The _.template method also supports various extensions, such as using a different character for template tags, inserting JavaScript code using <% %> and others. For details on using the _.template method and configuring it, see the Underscore.js documentation.

However, it is worth noting that Underscore.js has lost some of its popularity as of now. This is due to the emergence of other libraries, such as Lodash and Ramda, which provide similar functionality but with better performance and additional features. Lodash, in particular, is an improved alternative to Underscore.js, as it provides faster performance and more features.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation