Giter VIP home page Giter VIP logo

blog's People

Watchers

 avatar  avatar

blog's Issues

form 验证

内置:身份证号验证 是否为空 max min字符串常见验证

export default function(rules, obj) {
    if (typeof rules !== 'object') {
        throw new TypeError('need object type rule')
    }
    if (typeof obj !== 'object' || !obj) {
        return { errMsg: 'the validated value should be a object' }
    }
    for (let key in rules) {
        let rule = rules[key]
        let value = obj[key]
        // const errMsg = rule.msg || `请检查${key}格式`
        // if (typeof value === 'string' && rule.trim === true) {
        //   value = obj[key] = value.trim();
        // }
        // treat null / '' / NaN as undefined
        if (rule.hasOwnProperty('max') && value.length > rule.max) {
            const errMsg = rule.msg || `${key}必须小于${rule.max}个字符`
            return {
                errMsg
            }
        }
        if (rule.hasOwnProperty('min') && value.length < rule.min) {
            const errMsg = rule.msg || `${key}必须大于${rule.min}个字符`
            return {
                errMsg
            }
        }
        const errMsg = rule.msg || `请检查${key}格式`
        // 添加内置是否为空 校验
        if ((value === '' || value === null || Number.isNaN(value))) {
            value = obj[key] = undefined
        }
        const has = value !== null && value !== undefined
        if (!has) {
            if (rule.required) {
                // const errMsg = rule.msg || `请检查${key}格式`
                return {
                    errMsg
                }
            }
        }
        // 添加内置身份证校验
        if (rule.identity && !IdentityCodeValid(value)) {
            // const errMsg = rule.msg || `请检查${key}格式`
            return {
                errMsg
            }
        }
        if (rule.test && rule.test instanceof RegExp && !rule.test.test(value)) {
            // const errMsg = rule.msg || `请检查${key}格式`
            return {
                errMsg
            }
        }
    }
}
function IdentityCodeValid (code) {
    const city = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江 ',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北 ',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏 ',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '**',
        71: '**',
        81: '香港',
        82: '澳门',
        91: '国外'
    }
    let pass = true
    // 验证身份证格式(6个地区编码,8位出生日期,3位顺序号,1位校验位),  这个 正则有问题  现在只是校验一下基本格式
    // if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    if (!code || !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/i.test(code)) {
        console.log(1)
        pass = false
    } else if (!city[code.substr(0, 2)]) {
        console.log(2)
        pass = false
    } else {
        // 18位身份证需要验证最后一位校验位
        if (code.length === 18) {
            code = code.split('')
            // ∑(ai×Wi)(mod 11)
            // 加权因子
            let factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]
            // 校验位
            let parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]
            let sum = 0
            let ai = 0
            let wi = 0
            for (var i = 0; i < 17; i++) {
                ai = code[i]
                wi = factor[i]
                sum += ai * wi
            }
            let last = parity[sum % 11]
            if (String(last) !== code[17]) {
                pass = false
            }
        }
    }
    return pass
}

node 获取本地IPv4

function getIPAdress(){  
    var interfaces = require('os').networkInterfaces();
    for(var devName in interfaces){  
          var iface = interfaces[devName];  
          for(var i=0;i<iface.length;i++){  
               var alias = iface[i];  
               if(alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal){  
                     return alias.address;  
               }  
          }  
    }  
}

// console.log(getIPAdress())



// index.js
console.log(process.argv);
console.log(process.execArgv);

数组转树, 括号返回值,数组转对象

数组转树

const fn = arr => {
  const res = []
  const map = arr.reduce((res, item) => ((res[item.id] = item), res), {})
  for (const item of Object.values(map)) {
    if (!item.pId) {
      res.push(item)
    } else {
      const parent = map[item.pId]
      parent.child = parent.child || []
      parent.child.push(item)
    }
  }
  return res
}

逗号操作符 对它的每个操作数求值(从左到右),并返回最后一个操作数的值。

(1,2,3) // 返回值  3 
(1,2,3, 5 // 返回值  5  
// 返回最后一个逗号


let a = {}
(a.value=[]// 返回 []
const vlaue = a.value=[]
vlaue === a.value // true
// 说明 返回是 a.value  不是一个新的[]

数组转对象 直接用reduce 比变量+循环优雅

  const map = arr.reduce((res, item) => ((res[item.id] = item), res), {})

el-dialog 修改本弹窗

<template>
  <transition
    name="fade">
    <div class="dialog__wrapper" v-show="visible" @click.self="handleWrapperClick">
      <div
        class="dialog"
        :class="[{ 'is-fullscreen': fullscreen, 'dialog--center': center }, customClass]"
        ref="dialog"
        :style="style">
        <div class="dialog__header" v-if="$slots.title">
          <slot name="title">
            <span class="dialog__title">{{ title }}</span>
          </slot>
        </div>
        <!-- 内容模块 -->
        <div class="dialog__body" v-if="rendered">
            <slot></slot>
            <!-- 内容模块 -->
        </div>
        <!-- 友好提示 -->
        <div class="popupTips" v-if="$slots.desc">
            <slot name= "desc"></slot>  
        </div>
        <!-- 页脚按钮 -->
        <div class="dialog__footer" v-if="$slots.footer">
          <slot name="footer"></slot>
        </div>
          <!-- 关闭按钮 -->
        <button
        type="button"
        class="dialog__closebtn"
        aria-label="Close"
        v-if="showClose"
        @click="handleClose">
        <i class="dialog__close icon icon-close"></i>
        <!-- 52555 -->
        </button>
      </div>
      
    </div>
  </transition>
</template>
<script>
export default {
    name: 'SignDialog',
    props: {
        visible: Boolean,
        closeOnClickModal: {
            type: Boolean,
            default: true
        },
        title: {
            type: String,
            default: ''
        },
        appendToBody: {
            type: Boolean,
            default: false
        },
        lockScroll: {
            type: Boolean,
            default: true
        },
        showClose: {
            type: Boolean,
            default: true
        },
        width: String,
        fullscreen: Boolean,
        customClass: {
            type: String,
            default: ''
        },
        top: {
            type: String,
            default: '15vh'
        },
        beforeClose: Function,
        center: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            closed: false,
            rendered: -1
        }
    },
    watch: {
        visible(val) {
            if (val) {
                this.closed = false
                // this.$emit('open')
                // this.$el.addEventListener('scroll', this.updatePopper)
                this.$nextTick(() => {
                    this.$refs.dialog.scrollTop = 0
                })
                if (this.appendToBody) {
                    document.body.appendChild(this.$el)
                }
            } else {
                if (!this.closed) this.$emit('close')
            }
        }
    },
    computed: {
        style() {
            let style = {}
            if (!this.fullscreen) {
                style.marginTop = this.top
                if (this.width) {
                    style.width = this.width
                }
            }
            return style
        }
    },
    methods: {
        handleWrapperClick() {
            if (!this.closeOnClickModal) return
            this.handleClose()
        },
        handleClose() {
            if (typeof this.beforeClose === 'function') {
                this.beforeClose(this.hide)
            } else {
                this.hide()
            }
        },
        hide(cancel) {
            if (cancel !== false) {
                this.$emit('update:visible', false)
                this.$emit('close')
                this.closed = true
            }
        },
        afterLeave() {
            this.$emit('closed')
        }
    },
    mounted() {
        if (this.visible) {
            this.rendered = true
            // this.open()
            if (this.appendToBody) {
                document.body.appendChild(this.$el)
            }
        }
    },
    destroyed() {
        // if appendToBody is true, remove DOM node after destroy
        if (this.appendToBody && this.$el && this.$el.parentNode) {
            this.$el.parentNode.removeChild(this.$el)
        }
    }
}
</script>
<style lang="scss">
    .dialog__wrapper {
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        overflow: auto;
        margin: 0;
        background-color: rgba(0, 0, 0, .6);
        z-index: 2001;
    }
    .dialog--center .dialog__footer {
        text-align: inherit;
    }
    .dialog__footer {
        padding: 10px 0;
        // padding-top: 10px;
        text-align: right;
        box-sizing: border-box;
    }
.dialog {
    position: relative;
    margin: 0 auto 10px;
    background: #fff;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0,0,0,.3);
    box-sizing: border-box;
    width: 80%;
    padding: 30px 20px;
    .dialog__body {
        position: relative;
        img {
            width: 100%;
        }
    }
}
.dialog--center {
    text-align: center;
}
.dialog__closebtn {
    position: absolute;
    left: calc(50% - 15px);
    bottom: -60px;
    width: 30px;
    height: 30px;
    // background-color: red;
    display: inline-block;
    padding: 0;
    background: transparent;
    border: none;
    outline: none;
    cursor: pointer;
    font-size: 16px;
}
.icon-close {
    display: inline-block;
    width: 100%;
    height: 100%;
    background-image: url("./signinImg/close.png");
    background-size: 100% 100%;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
.dialog-footer button:last-child {
    margin-left: 10px;
}
.popupTips > p, .popupTips > span, .popupTips > div {
            padding: 10 0;
            display:flex;
            flex-direction: column;
            font-size: 15px;
            line-height: 24px;
}
.signBtn2 {
            // width: 96px;
            height: 37px;
            border-radius: 5px;
            border:1px solid #ed554c;
            background-color: #fff;
            font-size: 13px;
        }

.sureBtn {
    color:#ed554c;
}
.canceBtn { 
    background-color:#ed554c;
    color:#ffffff;   
}
.signBtn {
            padding: 9px 21px;
            background: #f7584f;
            color: #fff;
            border: none;
            font-size: 13px;
            border-radius: 6px;
            margin:  0 auto;
}
</style>

控制并发 promise版本

const dataLists = [5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,10,2,5,8,7,5,6,1]
let mapLimit = (list, limit, asyncHandle) => {
    console.log('当前并发为:' + limit)
    return new Promise((resolve,reject) => {
        const len = list.length-1
        let done  = false
        let index = -1
        let results = []
        let running = 0
         function recursion() {
            if (running >= limit  || done) return
                running++
                index++
                asyncHandle(list[index], index)
                .then(data => {
                    results.push(data)
                    if (len === results.length-1) {
                        resolve(results)
                    }
                    if ( index >= len) {
                        done = true
                    }
                    running-=1
                    recursion()
                    return data
                }).catch(err => {
                    done = true
                    reject(err)
                })
                recursion()  
            }
            recursion()
    })
}
   
const sleep = (data, time)=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(data)
        },time)
    })
}
mapLimit(dataLists,3,async (item,index) => {
    console.log(item +  '第'+ index + '个')
    const result =  await sleep(item, item*1000)
    return result
}).then(result => {
    console.log(result)
}).catch((err)=> {
    console.log(err)
})
-----------------------------------------------------------------优化版本----------------------尽量用上新特性


let mapLimit2 = (list, limit, asyncHandle) => {
    console.log('当前并发为:' + limit)
    return new Promise((resolve,reject) => {
        let done  = false
        let index = 0
        let results = []
        let running = 0
        const listIterator = list[Symbol.iterator]()    
        function recursion() {
            if (running >= limit  || done) return
                const currIterator = listIterator.next()
                if (currIterator.done) return
                running++
                asyncHandle(currIterator.value, index)
                .then(data => {
                    running-=1
                    results.push(data) 
                    if (running === 0) {
                        resolve(results)
                    }
                    recursion()
                }).catch(err => {
                    done = true
                    reject(err)
                })
                index++
                recursion()
            }
            recursion()
    })
} 
const sleep = (data, time)=> {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            resolve(data)
        },time)
    })
}

 const start = new Date().getTime()
mapLimit2(dataLists,15,async (item,index) => {
    console.log(item +  '第'+ index + '个')
    const result =  await sleep(item, item*1000)
    return result
}).then(result => {
    console.log( new Date().getTime()- start)  
    console.log(result)
}).catch((err)=> {
    console.log(err)
})

canvas 压缩图片

修改成 promise

   修改

 /**
     *
     *
     * @export
     * @param {fileObject} file 文件对象  
     * @param {quality}  Number 图片质量
     * @returns
     */
    export default  function compressIg(file, quality=0.7) {
            return new Promise(function (resolve, reject) {
                let ready = new FileReader()
                ready.readAsDataURL(file)
                ready.onload = function() {
                    let path = this.result
                    // canvasDataURL(re,w,objDiv)
                    let img = new Image()
                    img.src = path
                    img.onload = function() {
                        let that = this
                        if (quality <= 1 && quality > 0) {
                            quality =  0.7
                        }
                        // 默认按比例压缩
                        let w = that.width / quality 
                        let h = that.height  / quality 
                      
                        // 生成canvas
                        let canvas = document.createElement('canvas')
                        let ctx = canvas.getContext('2d')
                        // 创建属性节点
                        canvas.height = h
                        canvas.width = w
                        ctx.drawImage(that, 0, 0, w, h)
                        // 图像质量
                        // quality值越小,所绘制出的图像越模糊
                        canvas.toDataURL((blob)=> {
                                 resolve(blob)
                         },'image/jpeg')
                        // canvas.toBlob(callback, mimeType, qualityArgument)
                    }
                }
            })
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.