乐闻世界logo
搜索文章和话题

What numerical calculation methods are available in Lodash? Please provide examples of their usage

2月18日 22:00

Lodash provides rich numerical calculation methods. Here is a detailed answer about Lodash numerical calculations:

Lodash Numerical Calculation Methods Overview

Lodash provides many numerical calculation methods for processing number collections and performing mathematical operations. These methods are more powerful and flexible than native Math methods.

1. Basic Mathematical Operations

_.add(augend, addend)

Adds two numbers.

javascript
_.add(6, 4); // => 10 // Real application: Calculate total function calculateTotal(prices) { return _.reduce(prices, (sum, price) => _.add(sum, price), 0); } const prices = [10, 20, 30, 40]; console.log(calculateTotal(prices)); // => 100

_.subtract(minuend, subtrahend)

Subtracts two numbers.

javascript
_.subtract(6, 4); // => 2 // Real application: Calculate discount price function calculateDiscountPrice(price, discount) { return _.subtract(price, discount); } console.log(calculateDiscountPrice(100, 20)); // => 80

_.multiply(multiplier, multiplicand)

Multiplies two numbers.

javascript
_.multiply(6, 4); // => 24 // Real application: Calculate total price function calculateTotalPrice(price, quantity) { return _.multiply(price, quantity); } console.log(calculateTotalPrice(25, 4)); // => 100

_.divide(dividend, divisor)

Divides two numbers.

javascript
_.divide(6, 4); // => 1.5 // Real application: Calculate average function calculateAverage(numbers) { const sum = _.sum(numbers); return _.divide(sum, numbers.length); } console.log(calculateAverage([10, 20, 30, 40])); // => 25

2. Number Rounding

_.ceil(number, [precision=0])

Rounds up a number.

javascript
_.ceil(4.006); // => 4 _.ceil(6.004, 2); // => 6.01 _.ceil(6040, -2); // => 6100 // Real application: Calculate page count function calculatePageCount(totalItems, itemsPerPage) { return _.ceil(_.divide(totalItems, itemsPerPage)); } console.log(calculatePageCount(105, 10)); // => 11

_.floor(number, [precision=0])

Rounds down a number.

javascript
_.floor(4.006); // => 4 _.floor(0.046, 2); // => 0.04 _.floor(4060, -2); // => 4000 // Real application: Calculate discount amount function calculateDiscountAmount(price, discountRate) { return _.floor(_.multiply(price, discountRate), 2); } console.log(calculateDiscountAmount(99.99, 0.15)); // => 14.99

_.round(number, [precision=0])

Rounds a number.

javascript
_.round(4.006); // => 4 _.round(4.006, 2); // => 4.01 _.round(4060, -2); // => 4100 // Real application: Format price function formatPrice(price) { return _.round(price, 2); } console.log(formatPrice(99.995)); // => 100.00

_.clamp(number, [lower], upper)

Clamps a number within the specified range.

javascript
_.clamp(-10, -5, 5); // => -5 _.clamp(10, -5, 5); // => 5 // Real application: Limit value range function limitValue(value, min, max) { return _.clamp(value, min, max); } console.log(limitValue(150, 0, 100)); // => 100 console.log(limitValue(-50, 0, 100)); // => 0

3. Number Statistics

_.sum(array)

Calculates the sum of all numbers in an array.

javascript
_.sum([4, 2, 8, 6]); // => 20 // Real application: Calculate order total function calculateOrderTotal(order) { return _.sum(_.map(order.items, item => item.price * item.quantity)); } const order = { items: [ { price: 10, quantity: 2 }, { price: 20, quantity: 1 }, { price: 30, quantity: 3 } ] }; console.log(calculateOrderTotal(order)); // => 130

_.sumBy(array, [iteratee])

Calculates the sum based on an iteratee function.

javascript
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.sumBy(objects, function(o) { return o.n; }); // => 20 _.sumBy(objects, 'n'); // => 20 // Real application: Calculate sum of object array properties function calculateTotalSalary(employees) { return _.sumBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(calculateTotalSalary(employees)); // => 165000

_.mean(array)

Calculates the average of all numbers in an array.

javascript
_.mean([4, 2, 8, 6]); // => 5 // Real application: Calculate average score function calculateAverageScore(scores) { return _.mean(scores); } console.log(calculateAverageScore([85, 90, 78, 92, 88])); // => 86.6

_.meanBy(array, [iteratee])

Calculates the average based on an iteratee function.

javascript
var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.meanBy(objects, function(o) { return o.n; }); // => 5 _.meanBy(objects, 'n'); // => 5 // Real application: Calculate average of object array properties function calculateAverageAge(users) { return _.meanBy(users, 'age'); } const users = [ { name: 'John', age: 25 }, { name: 'Jane', age: 30 }, { name: 'Bob', age: 28 } ]; console.log(calculateAverageAge(users)); // => 27.666666666666668

_.max(array)

Calculates the maximum value in an array.

javascript
_.max([4, 2, 8, 6]); // => 8 _.max([]); // => undefined // Real application: Find highest score function findHighestScore(scores) { return _.max(scores); } console.log(findHighestScore([85, 90, 78, 92, 88])); // => 92

_.maxBy(array, [iteratee])

Calculates the maximum value based on an iteratee function.

javascript
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; }); // => { 'n': 2 } _.maxBy(objects, 'n'); // => { 'n': 2 } // Real application: Find highest paid employee function findHighestPaidEmployee(employees) { return _.maxBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(findHighestPaidEmployee(employees)); // => { name: 'Jane', salary: 60000 }

_.min(array)

Calculates the minimum value in an array.

javascript
_.min([4, 2, 8, 6]); // => 2 _.min([]); // => undefined // Real application: Find lowest score function findLowestScore(scores) { return _.min(scores); } console.log(findLowestScore([85, 90, 78, 92, 88])); // => 78

_.minBy(array, [iteratee])

Calculates the minimum value based on an iteratee function.

javascript
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } _.minBy(objects, 'n'); // => { 'n': 1 } // Real application: Find lowest paid employee function findLowestPaidEmployee(employees) { return _.minBy(employees, 'salary'); } const employees = [ { name: 'John', salary: 50000 }, { name: 'Jane', salary: 60000 }, { name: 'Bob', salary: 55000 } ]; console.log(findLowestPaidEmployee(employees)); // => { name: 'John', salary: 50000 }

4. Number Range

_.range([start=0], end, [step=1])

Creates an array of numbers from start to end (exclusive).

javascript
_.range(4); // => [0, 1, 2, 3] _.range(-4); // => [0, -1, -2, -3] _.range(1, 5); // => [1, 2, 3, 4] _.range(0, 20, 5); // => [0, 5, 10, 15] _.range(0, -4, -1); // => [0, -1, -2, -3] // Real application: Generate pagination array function generatePageNumbers(totalPages, currentPage) { const range = 5; const start = Math.max(1, currentPage - Math.floor(range / 2)); const end = Math.min(totalPages, start + range); return _.range(start, end + 1); } console.log(generatePageNumbers(10, 5)); // => [3, 4, 5, 6, 7]

_.rangeRight([start=0], end, [step=1])

Similar to _.range, but generates from right to left.

javascript
_.rangeRight(4); // => [3, 2, 1, 0] _.rangeRight(-4); // => [-3, -2, -1, 0] _.rangeRight(1, 5); // => [4, 3, 2, 1] _.rangeRight(0, 20, 5); // => [15, 10, 5, 0]

5. Number Random

_.random([lower=0], [upper=1], [floating])

Generates a random number.

javascript
_.random(0, 5); // => an integer between 0 and 5 _.random(5); // => also an integer between 0 and 5 _.random(5, true); // => a floating-point number between 0 and 5 _.random(1.2, 5.2); // => a floating-point number between 1.2 and 5.2 // Real application: Generate random ID function generateRandomId() { return _.random(100000, 999999); } console.log(generateRandomId()); // => 543210 // Real application: Random selection function randomPick(array) { const index = _.random(0, array.length - 1); return array[index]; } const items = ['apple', 'banana', 'orange', 'grape']; console.log(randomPick(items)); // => randomly selects a fruit

6. Number Comparison

_.inRange(number, [start=0], end)

Checks if a number is within the specified range.

javascript
_.inRange(3, 2, 4); // => true _.inRange(4, 8); // => true _.inRange(4, 2); // => false _.inRange(2, 2); // => false _.inRange(1.2, 2); // => true _.inRange(5.2, 4); // => false // Real application: Validate number range function validateAge(age) { if (!_.inRange(age, 18, 65)) { throw new Error('Age must be between 18 and 65'); } return age; } console.log(validateAge(25)); // => 25 console.log(validateAge(70)); // => Error: Age must be between 18 and 65

7. Number Utilities

_.maxBy(array, [iteratee])

Calculates the maximum value based on an iteratee function.

javascript
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; }); // => { 'n': 2 } _.maxBy(objects, 'n'); // => { 'n': 2 }

_.minBy(array, [iteratee])

Calculates the minimum value based on an iteratee function.

javascript
var objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } _.minBy(objects, 'n'); // => { 'n': 1 }

_.inRange(number, [start=0], end)

Checks if a number is within the specified range.

javascript
_.inRange(3, 2, 4); // => true _.inRange(4, 8); // => true _.inRange(4, 2); // => false

Real-World Application Examples

Statistics Analyzer

javascript
class StatisticsAnalyzer { constructor(data) { this.data = data; } getSum() { return _.sum(this.data); } getMean() { return _.mean(this.data); } getMax() { return _.max(this.data); } getMin() { return _.min(this.data); } getRange() { return _.subtract(this.getMax(), this.getMin()); } getStatistics() { return { sum: this.getSum(), mean: this.getMean(), max: this.getMax(), min: this.getMin(), range: this.getRange(), count: this.data.length }; } } const scores = [85, 90, 78, 92, 88, 76, 95, 82]; const analyzer = new StatisticsAnalyzer(scores); console.log(analyzer.getStatistics()); // => { // sum: 686, // mean: 85.75, // max: 95, // min: 76, // range: 19, // count: 8 // }

Price Calculator

javascript
class PriceCalculator { static calculateSubtotal(items) { return _.sumBy(items, item => _.multiply(item.price, item.quantity)); } static calculateTax(subtotal, taxRate) { return _.multiply(subtotal, taxRate); } static calculateDiscount(subtotal, discountRate) { return _.multiply(subtotal, discountRate); } static calculateTotal(subtotal, tax, discount) { const afterDiscount = _.subtract(subtotal, discount); return _.add(afterDiscount, tax); } static calculateOrderTotal(items, taxRate = 0.1, discountRate = 0) { const subtotal = this.calculateSubtotal(items); const tax = this.calculateTax(subtotal, taxRate); const discount = this.calculateDiscount(subtotal, discountRate); const total = this.calculateTotal(subtotal, tax, discount); return { subtotal: _.round(subtotal, 2), tax: _.round(tax, 2), discount: _.round(discount, 2), total: _.round(total, 2) }; } } const cart = [ { name: 'Product A', price: 29.99, quantity: 2 }, { name: 'Product B', price: 49.99, quantity: 1 }, { name: 'Product C', price: 19.99, quantity: 3 } ]; const orderTotal = PriceCalculator.calculateOrderTotal(cart, 0.08, 0.1); console.log(orderTotal); // => { // subtotal: 149.95, // tax: 11.996, // discount: 14.995, // total: 146.951 // }

Range Validator

javascript
class RangeValidator { static validate(value, min, max, fieldName = 'Value') { if (!_.isNumber(value)) { throw new Error(`${fieldName} must be a number`); } if (!_.inRange(value, min, max + 1)) { throw new Error(`${fieldName} must be between ${min} and ${max}`); } return value; } static clamp(value, min, max) { return _.clamp(value, min, max); } static validateAge(age) { return this.validate(age, 18, 65, 'Age'); } static validateScore(score) { return this.validate(score, 0, 100, 'Score'); } static validatePercentage(percentage) { return this.validate(percentage, 0, 100, 'Percentage'); } } console.log(RangeValidator.validateAge(25)); // => 25 console.log(RangeValidator.clamp(150, 0, 100)); // => 100 console.log(RangeValidator.validateScore(85)); // => 85

Summary

Lodash provides rich numerical calculation methods, including:

  1. Basic Mathematical Operations: _.add, _.subtract, _.multiply, _.divide
  2. Number Rounding: _.ceil, _.floor, _.round, _.clamp
  3. Number Statistics: _.sum, _.sumBy, _.mean, _.meanBy, _.max, _.maxBy, _.min, _.minBy
  4. Number Range: _.range, _.rangeRight
  5. Number Random: _.random
  6. Number Comparison: _.inRange

These numerical calculation methods are more powerful and flexible than native Math methods, supporting arrays and object arrays. In actual development, it's recommended to use these methods for numerical calculations to improve code readability and maintainability.

标签:Lodash