<>1, Object blending

In projects, you often encounter multiple objects that pass back the back end , The problem of merging into one object , We usually use Object.assign() function , So how do we copy this function ?
/** * Object blending , Object starting with the second parameter , Blend into first object */ function minxin(obj){ // Return when there is only one object if(
arguments.length <=1) return obj // Get parameter object list , Here we assume that what has been passed on as required is right and wrong var args = Array
.from(arguments) // Loop this list . for(var i=1;i<args.length;i++){ for(var prop in args[
i]){ // Put each attribute in the list , Copy to obj in , Which is our first parameter obj[prop] = args[i][prop] } } return obj }
<>2, deep / Shallow clone an object

We often need to clone an object in depth , except loadsh Clone method in , Can you write a deep clone yourself ? What about the next , It's the way I encapsulate objects that I can clone in depth
/** * Clone an object * @param {boolean} deep Deep clone or not */ function clone(obj, deep) { if (
Array.isArray(obj)) {// If it's an array if (deep) { // Deep clone var newArr = []
// Consider that the array may contain object data items , So loop through every data item and clone it for (var i = 0; i < obj.length; i++) {
return clone(obj[i], true) } return newArr } else {// Shallow clone , Directly return a new array return obj
.slice() } } else if (typeof obj === "object") {// Is an object var newObj = {} for (var
keyin obj) { if (obj.hasOwnProperty(key)) { // Do not clone values on prototype chain if (deep) {
// Deep cloning also needs to consider whether the attribute in the object is an object newObj[key] = clone(obj[key], true) } else { newObj[key] =
obj[key] } } } return newObj } else { // A normal value return obj } }
<>3, Function anti shake

Function anti shake is also a method we often use in a website . So what is function anti shake ? It's very simple , Is that we trigger the same event frequently over a period of time , May have a significant impact on Performance , therefore , We want to trigger only once in a while . This requires anti shake and throttling . for instance , Anti shake is triggered frequently ,1s The event handler is called when there is no more trigger in .
/** * Function anti shake */ function debounce(callback, time) { var timer; // Using closures , Can avoid polluting global variables
return function () { clearTimeout(timer) // Clear timer // Restart timing var args = arguments
timer= setTimeout(() => { callback.apply(null, args) }, time); } } // Test cases var
handle= debounce(function (a, b) { console.log(a, b) }, 1000) window.onresize =
function () { handle(1, 2) }
<>4, Function throttling

So what corresponds to anti shake is throttling , Throttling is only triggered once in a period of time !
/** * Function throttling */ function throttle(callback, time, immediately) { if (immediately)
{// Do you want to execute it once var t; return function () { // There was no time before or The time from the last execution has exceeded the specified value if (!t ||
Date.now() - t >= time) { callback.apply(null, arguments) // Current timestamp obtained t = Date.
now() } } } else {// If not executed immediately , So how long does this delay him before execution var timer; return function () {
if (timer) return var args = arguments timer = setTimeout(() => { callback.apply
(null, args) timer = null }, time); } } }
<>5, currying

Coriolism is to put a multi parameter function , A method of changing into a single parameter function , It can be said that JavaScript One of the toughest operations in , After all, in functional programming , The call of single parameter function is more convenient than that of multi parameter function .
/** * Coriolis function * In functional programming , The most important function of currierization is to change a multi parameter function into a single parameter function */ function curry(func) {
// Get parameters , Fix the parameters var args = Array.from(arguments).slice(1) var that = this
return function () { var curArgs = Array.from(arguments) var totalArgs = args.
concat(curArgs) if (totalArgs.length >= func.length) { return func.apply(null,
totalArgs) } else { totalArgs.unshift(func) return curry.apply(that, totalArgs)
} } } function f(x, y, z) { return (x + y) * z; } var g = curry(f, 1) var x = g(
2) console.log(x(3))
currying demo
<style> .container { border: 2px solid; padding: 30px; } </style> <div class="
container"> </div> <script> function createElement(container, name, props,
styles, content) { var ele = document.createElement(name); container.appendChild
(ele); for (var prop in props) { ele[prop] = props[prop]; } for (var prop in
styles) { ele.style[prop] = styles[prop]; } if (content) { ele.innerHTML =
content; } } var div = document.querySelector(".container"); var create = curry(
createElement, div, "div", {}, { height: "100px", background: "#008c8c", margin:
"30px", color:"#fff" }); create(" The first 1 Content "); create(" The first 2 Content "); create(" The first 3 Content ");
create(" The first 4 Content "); create(" The first 5 Content "); create(" The first 6 Content "); create(" The first 7 Content "); </script>
<>6, Single parameter function pipeline

When we encounter multiple consecutive function calls , The parameter of the next function is the return result of the previous function , At this point, you can use the single parameter function pipeline , He can simplify the process we call , Make the call easier .

/** * Function pipeline * Method 1 */ function pipe() { // Get pipeline function list var args = Array.from(
arguments); return function (val) { // Clever use reduce Summation function , The settlement result of the previous function , As an argument to the next function
return args.reduce(function (result, func) { return func(result); }, val); } }
/** * Function pipeline * Method 2 */ function pipe() { // Get pipeline function list var args = Array.from(arguments
); return function (val) { // Loop through each function , And save the calculation results of the previous function for (var i = 0; i <
args.length; i++) { var func = args[i]; // The result of keeping the previous function , Use the next function as an argument val = func(
val); } return val; } }
<>7, Copy one apply method

We all know that apply,call and bind You can change the this point , So how can we make a change on our own this Pointed method .
Function.prototype.newApply = function(ctx,arr){ //ctx: Execution context , That's what we're going to bind this point
var ctx = ctx // stay ctx Create a temporary variable in fn Store current this ctx.fn = this var result if(!arr){
result= ctx.fn() }else{ var args = [] for(var i=0;i<arr.length;i++){ args.push(
"arr["+i+"]") } result = eval('ctx.fn('+args.join(',') + ')') } // Delete temporary variable fn
delete ctx.fn return result } // test case let person = { name:"zhang" } function obj(
name,age){ console.log(this.name) return { name:name, age:age } } var newObj =
obj.newApply(person,['zhangsan','30']) console.log(newObj)
<>8, Encapsulate a type method

We all know typeof The type of value you can get , But this method is not accurate , Then we can achieve one by ourselves type method
function type(target){ // Define an output dictionary var template = { "[object Array]" : "array",
"[object Object]" : "object", "[object Number]" : "number - object", "[object
String]" : "string - object", "[object Boolean]" : "boolean - object" } if(
typeof(target) === null){ // solve null yes object Problems of return null; } if(typeof(target) ==
"object"){ var str = Object.prototype.toString(target) return template[str]; }
else{ return typeof(target); } }
<>9, Array de duplication

The method of array de duplication , But I don't know if you will ? We use a temporary object method to store every value in the array
// Array de duplication Array.prototype.unique = function(){ var temp = {}, arr = [], len =
this.length; for(var i=0;i<len;i++){ if(!temp[this[i]]){ // undefined Reverse temp[
this[i]] = "a"; arr.push(this[i]); } } return arr; }
<>10, Grail mode ( inherit )

use prototype Carry on you will never , How can you get into the big factory
/* * Target Is the heir Origin Is the heir */ function inherit(Target,Origin){
// By creating a new F Constructor as middle layer // Prevent heirs from modifying prototype Time has an impact on the heirs function F(){} F.prototype =
Origin.prototype; Target.prototype = new F(); Target.prototype.constuctor =
Target; Target.prototype.uber = Origin.protoype; } /* * yahoo Holy Grail mode provided in */ var
inherit= (function(){ var F = function(){}; // Mesosphere F Set constructor F Change to privatization variable return function
(Target,Origin){ // Return inherited function F.prototype = Origin.prototype; Target.prototype = new
F(); Target.prototype.constuctor = Target; Target.prototype.uber = Origin; }; }(
))

Technology
©2019-2020 Toolsou All rights reserved,
The project followed for a year , The customer finally said no Go language Array initialization and basic operations uboot set up nfs parameter ——linux kernel use nfs Mode to load the root file system rootfs( Six )ToastUtils Use of ( Essence )2020 year 7 month 12 day webpack Use of common plug-ins Obviously post Why does the request display parameters in the address bar ?keras Data generator -- Data enhancement Keras Summary of training data loading ( Essence )2020 year 7 month 13 day Wechat applet Inter communication page pytorch of ResNet18( Yes cifar10 The accuracy of data classification is achieved 94%)