8 JavaScript code snippets necessary for engineering

  • 2021-11-24 00:29:44
  • OfStack

Directory 1. Get file suffix 2. Copy content to clipboard 3. How many milliseconds sleep 4. Generate random string 5. Simple deep copy 6. Array de-duplication 7. Object converted to FormData object 8. Keep to n bit after decimal point

1. Get the file suffix name

Usage scenario: Upload a file to judge the suffix name


/**
 *  Get the file suffix name 
 * @param {String} filename
 */
 export function getExt(filename) {
    if (typeof filename == 'string') {
        return filename
            .split('.')
            .pop()
            .toLowerCase()
    } else {
        throw new Error('filename must be a string type')
    }
}

Usage


getExt("1.mp4") //->mp4

2. Copy content to clipboard


export function copyToBoard(value) {
    const element = document.createElement('textarea')
    document.body.appendChild(element)
    element.value = value
    element.select()
    if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(element)
        return true
    }
    document.body.removeChild(element)
    return false
}

Usage:


// Returns if replication succeeds true
copyToBoard('lalallala')

Principle:

Create 1 textare Element and call the select() Method selection document.execCommand('copy') Method to copy the current selection to the clipboard.

3. How many milliseconds sleep


/**
 *  Dormancy xxxms
 * @param {Number} milliseconds
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

// Usage 
const fetchData=async()=>{
 await sleep(1000)
}

4. Generate random strings


/**
 *  Generating random id
 * @param {*} length
 * @param {*} chars
 */
export function uuid(length, chars) {
    chars =
        chars ||
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    length = length || 8
    var result = ''
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)]
    return result
}

Usage:


// No. 1 1 Parameters specify the number of digits, the 2 A string specifies characters, all of which are optional parameters. If they are not passed, they will be generated by default 8 Bit 
uuid()  

Usage scenario: Used to generate random ID at the front end. After all, both Vue and React need to be bound with key now

5. Simple deep copy


/**
 * Deep copy 
 * @export
 * @param {*} obj
 * @returns
 */
export function deepCopy(obj) {
    if (typeof obj != 'object') {
        return obj
    }
    if (obj == null) {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}

Vulnerability: Copying only objects, arrays, and arrays of objects is sufficient for most scenarios


const person={name:'xiaoming',child:{name:'Jack'}}
deepCopy(person) //new person

6. Array de-duplication


/**
 *  Array de-duplication 
 * @param {*} arr
 */
export function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
        throw new Error('The first parameter must be an array')
    }
    if (arr.length == 1) {
        return arr
    }
    return [...new Set(arr)]
}

The principle is to use Set The property that duplicate elements cannot appear in


getExt("1.mp4") //->mp4
0

7. Convert an object to an FormData object


getExt("1.mp4") //->mp4
1

Usage scenario: When uploading files, we need to create a new one FormData Object, and then how many parameters are there append How many times can you use this function to simplify the logic

Usage:


getExt("1.mp4") //->mp4
2

8. Keep n bits after decimal point


//  Keep a few decimal places after the decimal point, and the default 2 Bit 
export function cutNumber(number, no = 2) {
    if (typeof number != 'number') {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}

Usage scenario: JS The floating point number of is too long, and sometimes the page needs to be displayed with 2 decimal places

Conclusion:


Related articles: