Lodash provides rich mathematical calculation methods. Here is a detailed answer about Lodash mathematical calculations:
Lodash Mathematical Calculations Overview
Lodash's mathematical calculation methods provide various numerical processing functions, including sum, average, maximum, minimum, etc.
1. Basic Mathematical Calculations
_.sum(array)
Calculates the sum of all elements in an array.
javascript_.sum([4, 2, 8, 6]); // => 20 _.sum([1, 2, 3, 4, 5]); // => 15 // Handle array of objects var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.sumBy(objects, 'n'); // => 20 // Calculate using function var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 3 }]; _.sumBy(objects, function(o) { return o.a; }); // => 6
_.mean(array)
Calculates the average of all elements in an array.
javascript_.mean([4, 2, 8, 6]); // => 5 _.mean([1, 2, 3, 4, 5]); // => 3 // Handle array of objects var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.meanBy(objects, 'n'); // => 5 // Calculate using function var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 3 }]; _.meanBy(objects, function(o) { return o.a; }); // => 2
_.max(array)
Gets the maximum value in an array.
javascript_.max([4, 2, 8, 6]); // => 8 // Handle array of objects var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.maxBy(objects, 'n'); // => { 'n': 8 } // Calculate using function var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 3 }]; _.maxBy(objects, function(o) { return o.a; }); // => { 'a': 3 } // Handle empty array _.max([]); // => undefined
_.min(array)
Gets the minimum value in an array.
javascript_.min([4, 2, 8, 6]); // => 2 // Handle array of objects var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; _.minBy(objects, 'n'); // => { 'n': 2 } // Calculate using function var objects = [{ 'a': 1 }, { 'a': 2 }, { 'a': 3 }]; _.minBy(objects, function(o) { return o.a; }); // => { 'a': 1 } // Handle empty array _.min([]); // => undefined
2. Number Range Operations
_.clamp(number, [lower], upper)
Clamps number within the inclusive lower and upper bounds.
javascript_.clamp(-10, -5, 5); // => -5 _.clamp(10, -5, 5); // => 5 _.clamp(0, -5, 5); // => 0 // Real application: Limit number range function ensureValidPercentage(value) { return _.clamp(value, 0, 100); } ensureValidPercentage(150); // => 100 ensureValidPercentage(-20); // => 0 ensureValidPercentage(50); // => 50
_.inRange(number, [start=0], end)
Checks if number is between start and up to, but not including, end.
javascript_.inRange(3, 2, 4); // => true _.inRange(4, 8); // => true _.inRange(4, 2); // => false _.inRange(2, 2); // => false _.inRange(1.2, 2); // => true // Real application: Validate number range function isValidAge(age) { return _.inRange(age, 18, 65); } isValidAge(25); // => true isValidAge(17); // => false isValidAge(70); // => false
3. Random Number Generation
_.random([lower=0], [upper=1], [floating])
Produces a random number between the inclusive lower and upper bounds.
javascript_.random(0, 5); // => integer between 0 and 5 _.random(5); // => integer between 0 and 5 _.random(5, true); // => floating point number between 0 and 5 _.random(1.2, 5.2); // => floating point number between 1.2 and 5.2 // Real application: Generate random ID function generateRandomId() { return _.random(100000, 999999); } generateRandomId(); // => 123456 // Real application: Generate random color function generateRandomColor() { const r = _.random(0, 255); const g = _.random(0, 255); const b = _.random(0, 255); return `rgb(${r}, ${g}, ${b})`; } generateRandomColor(); // => 'rgb(123, 45, 67)'
4. Number Rounding
_.ceil(number, [precision=0])
Computes number rounded up to precision.
javascript_.ceil(4.006); // => 5 _.ceil(6.004, 2); // => 6.01 _.ceil(6040, -2); // => 6100 // Real application: Round price up function calculateTotalPrice(price, quantity) { return _.ceil(price * quantity, 2); } calculateTotalPrice(19.99, 3); // => 59.97
_.floor(number, [precision=0])
Computes number rounded down to precision.
javascript_.floor(4.006); // => 4 _.floor(0.046, 2); // => 0.04 _.floor(4060, -2); // => 4000 // Real application: Round price down function calculateDiscountedPrice(price, discount) { return _.floor(price * (1 - discount), 2); } calculateDiscountedPrice(100, 0.15); // => 85.00
_.round(number, [precision=0])
Computes number rounded to precision.
javascript_.round(4.006); // => 4 _.round(4.006, 2); // => 4.01 _.round(4060, -2); // => 4100 // Real application: Standard rounding function roundToNearest(value, nearest) { return _.round(value / nearest) * nearest; } roundToNearest(123, 10); // => 120 roundToNearest(127, 10); // => 130
5. Number Conversion
_.toInteger(value)
Converts value to an integer.
javascript_.toInteger(3.2); // => 3 _.toInteger(Number.MIN_VALUE); // => 0 _.toInteger(Infinity); // => 1.7976931348623157e+308 _.toInteger('3.2'); // => 3 _.toInteger(null); // => 0
_.toLength(value)
Converts value to an integer suitable for use as the length of an array-like object.
javascript_.toLength(3.2); // => 3 _.toLength(Number.MIN_VALUE); // => 0 _.toLength(Infinity); // => 4294967295 _.toLength('3.2'); // => 3 _.toLength(null); // => 0
_.toNumber(value)
Converts value to a number.
javascript_.toNumber('3.2'); // => 3.2 _.toNumber(Number.MIN_VALUE); // => 5e-324 _.toNumber(Infinity); // => Infinity _.toNumber('0b111110111'); // => 495 _.toNumber('0o767'); // => 503
_.toFinite(value)
Converts value to a finite number.
javascript_.toFinite(3.2); // => 3.2 _.toFinite(Number.MIN_VALUE); // => 5e-324 _.toFinite(Infinity); // => 1.7976931348623157e+308 _.toFinite('3.2'); // => 3.2 _.toFinite(NaN); // => 0
6. Number Comparison
_.maxBy(array, [iteratee])
This method is like _.max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked.
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.maxBy(objects, function(o) { return o.n; }); // => { 'n': 2 } _.maxBy(objects, 'n'); // => { 'n': 2 } // Real application: Find student with highest score var students = [ { name: 'Alice', score: 85 }, { name: 'Bob', score: 92 }, { name: 'Charlie', score: 78 } ]; var topStudent = _.maxBy(students, 'score'); // => { name: 'Bob', score: 92 }
_.minBy(array, [iteratee])
This method is like _.min except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked.
javascriptvar objects = [{ 'n': 1 }, { 'n': 2 }]; _.minBy(objects, function(o) { return o.n; }); // => { 'n': 1 } _.minBy(objects, 'n'); // => { 'n': 1 } // Real application: Find student with lowest score var students = [ { name: 'Alice', score: 85 }, { name: 'Bob', score: 92 }, { name: 'Charlie', score: 78 } ]; var lowestStudent = _.minBy(students, 'score'); // => { name: 'Charlie', score: 78 }
Real-World Application Examples
Statistical Analysis
javascriptclass StatisticsCalculator { static calculateStatistics(numbers) { if (_.isEmpty(numbers)) { return null; } return { sum: _.sum(numbers), mean: _.mean(numbers), min: _.min(numbers), max: _.max(numbers), range: _.max(numbers) - _.min(numbers), median: this.calculateMedian(numbers), variance: this.calculateVariance(numbers), standardDeviation: this.calculateStandardDeviation(numbers) }; } static calculateMedian(numbers) { const sorted = _.sortBy(numbers); const mid = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { return (sorted[mid - 1] + sorted[mid]) / 2; } else { return sorted[mid]; } } static calculateVariance(numbers) { const mean = _.mean(numbers); const squaredDifferences = _.map(numbers, num => Math.pow(num - mean, 2)); return _.mean(squaredDifferences); } static calculateStandardDeviation(numbers) { const variance = this.calculateVariance(numbers); return Math.sqrt(variance); } } // Usage example const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const stats = StatisticsCalculator.calculateStatistics(numbers); console.log(stats); // => { // sum: 55, // mean: 5.5, // min: 1, // max: 10, // range: 9, // median: 5.5, // variance: 8.25, // standardDeviation: 2.8722813232690143 // }
Price Calculation
javascriptclass PriceCalculator { static calculateSubtotal(items) { return _.sumBy(items, item => item.price * item.quantity); } static calculateTax(subtotal, taxRate) { return _.round(subtotal * taxRate, 2); } static calculateDiscount(subtotal, discountRate) { return _.floor(subtotal * discountRate, 2); } static calculateTotal(subtotal, tax, discount) { return _.ceil(subtotal + tax - discount, 2); } static calculateOrderTotal(items, taxRate, discountRate) { 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, tax, discount, total }; } } // Usage example const cartItems = [ { name: 'Product A', price: 19.99, quantity: 2 }, { name: 'Product B', price: 29.99, quantity: 1 }, { name: 'Product C', price: 9.99, quantity: 3 } ]; const orderTotal = PriceCalculator.calculateOrderTotal(cartItems, 0.08, 0.10); console.log(orderTotal); // => { // subtotal: 89.95, // tax: 7.20, // discount: 8.99, // total: 88.16 // }
Data Validation
javascriptclass DataValidator { static validateNumber(value, min = -Infinity, max = Infinity) { const number = _.toNumber(value); if (_.isNaN(number)) { return { valid: false, error: 'Invalid number' }; } if (!_.inRange(number, min, max + 1)) { return { valid: false, error: `Number must be between ${min} and ${max}` }; } return { valid: true, value: number }; } static validatePercentage(value) { const number = _.toNumber(value); if (_.isNaN(number)) { return { valid: false, error: 'Invalid percentage' }; } const clamped = _.clamp(number, 0, 100); if (clamped !== number) { return { valid: true, value: clamped, warning: 'Percentage was clamped to valid range' }; } return { valid: true, value: number }; } static validateAge(age) { const result = this.validateNumber(age, 0, 150); if (!result.valid) { return result; } if (result.value < 18) { return { valid: false, error: 'Must be at least 18 years old' }; } return result; } } // Usage example console.log(DataValidator.validateNumber(25, 0, 100)); // => { valid: true, value: 25 } console.log(DataValidator.validateNumber(150, 0, 100)); // => { valid: false, error: 'Number must be between 0 and 100' } console.log(DataValidator.validatePercentage(85)); // => { valid: true, value: 85 } console.log(DataValidator.validatePercentage(150)); // => { valid: true, value: 100, warning: 'Percentage was clamped to valid range' } console.log(DataValidator.validateAge(25)); // => { valid: true, value: 25 } console.log(DataValidator.validateAge(17)); // => { valid: false, error: 'Must be at least 18 years old' }
Random Data Generation
javascriptclass RandomDataGenerator { static generateRandomNumber(min, max, precision = 0) { const number = _.random(min, max, precision > 0); return precision > 0 ? _.round(number, precision) : number; } static generateRandomArray(length, min, max, precision = 0) { return _.times(length, () => this.generateRandomNumber(min, max, precision)); } static generateRandomScore(min = 0, max = 100) { return this.generateRandomNumber(min, max, 0); } static generateRandomPrice(min = 0, max = 1000) { return this.generateRandomNumber(min, max, 2); } static generateRandomPercentage(min = 0, max = 100) { return this.generateRandomNumber(min, max, 1); } } // Usage example console.log(RandomDataGenerator.generateRandomNumber(1, 100)); // => 42 console.log(RandomDataGenerator.generateRandomArray(5, 1, 100)); // => [23, 67, 45, 89, 12] console.log(RandomDataGenerator.generateRandomScore()); // => 85 console.log(RandomDataGenerator.generateRandomPrice(10, 100)); // => 45.67 console.log(RandomDataGenerator.generateRandomPercentage()); // => 67.5
Summary
Lodash's mathematical calculation methods include:
-
Basic Mathematical Calculations:
_.sum()- Calculate sum_.mean()- Calculate average_.max()- Get maximum value_.min()- Get minimum value
-
Number Range Operations:
_.clamp()- Limit number range_.inRange()- Check if number is in range
-
Random Number Generation:
_.random()- Generate random number
-
Number Rounding:
_.ceil()- Round up_.floor()- Round down_.round()- Round to nearest
-
Number Conversion:
_.toInteger()- Convert to integer_.toLength()- Convert to length integer_.toNumber()- Convert to number_.toFinite()- Convert to finite number
-
Number Comparison:
_.maxBy()- Get max by iteratee_.minBy()- Get min by iteratee
These methods can be used individually or combined to provide powerful numerical processing capabilities. In actual development, they are often used in statistical analysis, price calculation, data validation, random data generation, and other scenarios.