- Spec files
npm-lodash
Describes: pkg:npm/lodash@4.5.x
- Description
- Comprehensive JavaScript utility library with 300+ methods for arrays, objects, strings, functions, and more.
- Author
- tessl
- Last updated
math-number-methods.md docs/
1# Math & Number Methods23Mathematical utilities for arithmetic, aggregation, and numerical processing. These methods provide essential mathematical operations and number manipulation functions.45## Capabilities67### Basic Arithmetic89#### Core Math Operations10Perform basic mathematical operations with proper handling of edge cases.1112```javascript { .api }13/**14* Adds two numbers15* @param augend - The first number in an addition16* @param addend - The second number in an addition17* @returns Returns the sum18*/19function add(augend, addend);2021/**22* Subtracts two numbers23* @param minuend - The first number in a subtraction24* @param subtrahend - The second number in a subtraction25* @returns Returns the difference26*/27function subtract(minuend, subtrahend);2829/**30* Multiplies two numbers31* @param multiplier - The first number in a multiplication32* @param multiplicand - The second number in a multiplication33* @returns Returns the product34*/35function multiply(multiplier, multiplicand);3637/**38* Divides two numbers39* @param dividend - The first number in a division40* @param divisor - The second number in a division41* @returns Returns the quotient42*/43function divide(dividend, divisor);44```4546### Rounding & Precision4748#### Rounding Functions49Round numbers to specified precision.5051```javascript { .api }52/**53* Computes number rounded up to precision54* @param number - The number to round up55* @param precision - The precision to round up to56* @returns Returns the rounded up number57*/58function ceil(number, precision = 0);5960/**61* Computes number rounded down to precision62* @param number - The number to round down63* @param precision - The precision to round down to64* @returns Returns the rounded down number65*/66function floor(number, precision = 0);6768/**69* Computes number rounded to precision70* @param number - The number to round71* @param precision - The precision to round to72* @returns Returns the rounded number73*/74function round(number, precision = 0);75```7677### Array Aggregation7879#### Min & Max80Find minimum and maximum values in arrays.8182```javascript { .api }83/**84* Computes the maximum value of array85* @param array - The array to iterate over86* @returns Returns the maximum value87*/88function max(array);8990/**91* Like max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked92* @param array - The array to iterate over93* @param iteratee - The iteratee invoked per element94* @returns Returns the maximum value95*/96function maxBy(array, iteratee);9798/**99* Computes the minimum value of array100* @param array - The array to iterate over101* @returns Returns the minimum value102*/103function min(array);104105/**106* Like min except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked107* @param array - The array to iterate over108* @param iteratee - The iteratee invoked per element109* @returns Returns the minimum value110*/111function minBy(array, iteratee);112```113114#### Sum & Mean115Calculate totals and averages.116117```javascript { .api }118/**119* Computes the sum of the values in array120* @param array - The array to iterate over121* @returns Returns the sum122*/123function sum(array);124125/**126* Like sum except that it accepts iteratee which is invoked for each element in array to generate the value to be summed127* @param array - The array to iterate over128* @param iteratee - The iteratee invoked per element129* @returns Returns the sum130*/131function sumBy(array, iteratee);132133/**134* Computes the mean of the values in array135* @param array - The array to iterate over136* @returns Returns the mean137*/138function mean(array);139140/**141* Like mean except that it accepts iteratee which is invoked for each element in array to generate the value to be averaged142* @param array - The array to iterate over143* @param iteratee - The iteratee invoked per element144* @returns Returns the mean145*/146function meanBy(array, iteratee);147```148149### Number Utilities150151#### Range Operations152Constrain and test number ranges.153154```javascript { .api }155/**156* Clamps number within the inclusive lower and upper bounds157* @param number - The number to clamp158* @param lower - The lower bound159* @param upper - The upper bound160* @returns Returns the clamped number161*/162function clamp(number, lower, upper);163164/**165* Checks if number is between start and up to, but not including, end166* @param number - The number to check167* @param start - The start of the range168* @param end - The end of the range169* @returns Returns true if number is in the range, else false170*/171function inRange(number, start = 0, end);172```173174#### Random Number Generation175Generate random numbers within specified ranges.176177```javascript { .api }178/**179* Produces a random number between the inclusive lower and upper bounds180* @param lower - The lower bound181* @param upper - The upper bound182* @param floating - Specify returning a floating-point number183* @returns Returns the random number184*/185function random(lower = 0, upper = 1, floating);186```187188## Usage Examples189190```javascript191import {192add, subtract, multiply, divide,193ceil, floor, round,194max, min, sum, mean,195clamp, inRange, random196} from "lodash";197198// Basic arithmetic199console.log(add(6, 4)); // 10200console.log(subtract(6, 4)); // 2201console.log(multiply(6, 4)); // 24202console.log(divide(6, 4)); // 1.5203204// Precision rounding205console.log(ceil(4.006)); // 5206console.log(ceil(6.004, 2)); // 6.01207console.log(ceil(6040, -2)); // 6100208209console.log(floor(4.006)); // 4210console.log(floor(0.046, 2)); // 0.04211console.log(floor(4060, -2)); // 4000212213console.log(round(4.006)); // 4214console.log(round(4.006, 2)); // 4.01215console.log(round(4060, -2)); // 4100216217// Array aggregation218const numbers = [4, 2, 8, 6];219console.log(max(numbers)); // 8220console.log(min(numbers)); // 2221console.log(sum(numbers)); // 20222console.log(mean(numbers)); // 5223224// Working with objects225const users = [226{ name: 'John', age: 30, score: 85 },227{ name: 'Jane', age: 25, score: 92 },228{ name: 'Bob', age: 35, score: 78 }229];230231console.log(maxBy(users, 'age')); // { name: 'Bob', age: 35, score: 78 }232console.log(minBy(users, 'score')); // { name: 'Bob', age: 35, score: 78 }233console.log(sumBy(users, 'score')); // 255234console.log(meanBy(users, 'age')); // 30235236// Number range operations237console.log(clamp(10, 5, 15)); // 10 (within range)238console.log(clamp(3, 5, 15)); // 5 (clamped to lower)239console.log(clamp(20, 5, 15)); // 15 (clamped to upper)240241console.log(inRange(3, 2, 4)); // true242console.log(inRange(4, 8)); // true (0 to 8)243console.log(inRange(4, 2)); // false244console.log(inRange(2, 2)); // false245console.log(inRange(-3, -2, -6)); // true246247// Random number generation248console.log(random(0, 5)); // Random integer between 0-5249console.log(random(5)); // Random integer between 0-5250console.log(random(1.2, 5.2)); // Random float between 1.2-5.2251console.log(random(0, 1, true)); // Random float between 0-1252253// Practical examples254255// Calculate statistics for test scores256const testScores = [85, 92, 78, 96, 88, 91, 84];257258const stats = {259count: testScores.length,260sum: sum(testScores),261average: mean(testScores),262highest: max(testScores),263lowest: min(testScores),264range: max(testScores) - min(testScores)265};266267console.log(stats);268// {269// count: 7,270// sum: 614,271// average: 87.71428571428571,272// highest: 96,273// lowest: 78,274// range: 18275// }276277// Financial calculations with proper rounding278const prices = [19.99, 25.50, 12.75, 8.25];279const taxRate = 0.08;280281const subtotal = sum(prices);282const tax = round(multiply(subtotal, taxRate), 2);283const total = round(add(subtotal, tax), 2);284285console.log(`Subtotal: $${subtotal.toFixed(2)}`);286console.log(`Tax: $${tax.toFixed(2)}`);287console.log(`Total: $${total.toFixed(2)}`);288289// Progress bar calculation290function calculateProgress(current, total) {291const percentage = divide(current, total) * 100;292return clamp(round(percentage, 1), 0, 100);293}294295console.log(calculateProgress(250, 1000)); // 25.0296console.log(calculateProgress(1200, 1000)); // 100.0 (clamped)297298// Random sampling utility299function sampleNumbers(count, min, max, floating = false) {300return Array.from({ length: count }, () =>301random(min, max, floating)302);303}304305console.log(sampleNumbers(5, 1, 10)); // [3, 7, 1, 9, 5]306console.log(sampleNumbers(3, 0, 1, true)); // [0.234, 0.876, 0.123]307308// Grade calculation system309function calculateGrade(scores, weights) {310if (scores.length !== weights.length) {311throw new Error('Scores and weights must have same length');312}313314const weightedScores = scores.map((score, index) =>315multiply(score, weights[index])316);317318const totalWeightedScore = sum(weightedScores);319const totalWeight = sum(weights);320321return round(divide(totalWeightedScore, totalWeight), 2);322}323324const examScores = [85, 92, 88];325const examWeights = [0.3, 0.4, 0.3]; // 30%, 40%, 30%326327console.log(calculateGrade(examScores, examWeights)); // 88.5328329// Budget allocation with constraints330function allocateBudget(totalBudget, categories) {331const totalRequested = sumBy(categories, 'requested');332333if (totalRequested <= totalBudget) {334// If under budget, allocate as requested335return categories.map(cat => ({336...cat,337allocated: cat.requested338}));339}340341// If over budget, proportionally reduce342const ratio = divide(totalBudget, totalRequested);343344return categories.map(cat => ({345...cat,346allocated: round(multiply(cat.requested, ratio), 2)347}));348}349350const budget = 10000;351const categories = [352{ name: 'Marketing', requested: 4000, minimum: 2000 },353{ name: 'Development', requested: 5000, minimum: 3000 },354{ name: 'Operations', requested: 3000, minimum: 1500 }355];356357console.log(allocateBudget(budget, categories));358359// Statistical analysis helper360function analyzeDataset(values) {361if (!values || values.length === 0) {362return null;363}364365const sorted = [...values].sort((a, b) => a - b);366const length = values.length;367368return {369count: length,370sum: sum(values),371mean: mean(values),372median: length % 2 === 0373? mean([sorted[length / 2 - 1], sorted[length / 2]])374: sorted[Math.floor(length / 2)],375min: min(values),376max: max(values),377range: max(values) - min(values)378};379}380381const dataset = [12, 15, 18, 22, 25, 28, 30, 35, 38, 42];382console.log(analyzeDataset(dataset));383```