This series uses LoDash 4.17.4

preface

There are no references to other documents in this document

The body of the

/** * Clamps' number 'within the inclusive' lower 'and' upper 'bounds. ** @since 4.0.0 * @category number * @param {number} number The number to clamp. * @param {number} lower The lower bound. * @param {number} upper The upper bound. *  @returns {number} Returns the clamped number. * @example * * clamp(-10, -5, 5) * // => -5 * * clamp(10, -5, 5) */ / => 5 */
function clamp(number, lower, upper) {
  number = +number
  lower = +lower
  upper = +upper
  lower = lower === lower ? lower : 0
  upper = upper === upper ? upper : 0
  if (number === number) {
    number = number <= upper ? number : upper
    number = number >= lower ? number : lower
  }
  return number
}

export default clamp
Copy the code

use

// Clamp function usage
// A low life whose power level is only 5
var me = {
    powerLevel:5
}

me.drinkElixirOfWrath = function() {
    this.powerLevel += 30
}
me.drinkElixirOfWrath() // I am now full of power!

// Hey, you are not allowed to be a monster after the founding of new China
me.powerLevel = clamp(me.powerLevel, null.10)   // Aww

me.powerLevel / / 10
Copy the code

Usage scenarios

I will try to summarize the practical application scenarios of clamp functions

1. Remove clipping from the input box

var height = 180  // centimeter

// after input
height = 500

height = clamp(height, null.270)
Copy the code

2….

Ok, actually I feel that there are a lot of places to use, but I have not thought of the specific use, please let me know in the comment section if you have actually used or have ideas in the project, thank you very much.

Source code analysis

The ES 2017 Math extension already has a native implementation. Point I see

Math.clamp(x, lower, upper)
Copy the code

Let’s see if there’s anything interesting in these dozens of lines of code.

The wonderful use of the plus sign

The plus sign is actually a numeric expression that returns an object. You can try this code

+ (new Date())   // 1513429205460 (timestamp, results may vary)
+'3'            / / 3
Copy the code

Most of what I’ve seen before is a combination of plus and Date objects, so you can quickly get the timestamp and do the calculation.

But there’s another wonderful use for the plus sign

+function() { console.log("Foo!"); } ();Copy the code

It forces the parser to treat anything after the plus sign as an expression, which can also be used in IIFE. Plus isn’t the only option, of course. The unary operators, such as, ~, and so on can work, so we often see the following instant-execution functions

!function(){/* code */} ();Copy the code

Self equal

var notANumber = +'keke'
notANumber === notANumber // false
Copy the code

Only NaN is not equal to itself, and this can also be used to determine if a variable is NaN

This article is from the Good Afternoon Pancake Project Web group – Liang Wang