撸代码的题

2020-06-08  本文已影响0人  行走的蛋白质

function trans(arr) {
  let start = 0;
  let end = 0;
  const result = [];
  for (let i = 0; i < arr.length; i++) {
    end = i;
    if (arr[i + 1] - arr[i] !== 1) {
      if (start === end) {
        result.push(arr[i]);
      } else {
        result.push(`${arr[start]}-${arr[end]}`);
      }
      start = i + 1;
    }
  }
  return result;
}
console.log(trans(arr1));

function sleep1(wait) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, wait)
    })
}
sleep1(1000).then(_ => {
    console.log('promise sleep')
})

function sleep2(wait) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, wait)
    })
}
async function asyncawait(wait) {
    await sleep2(wait)
    console.log('async await sleep')
}
asyncawait(1000)

function sleep3(fun, wait) {
    if(fun.constructor === Function) {
        setTimeout(fun, wait)
    }
}
function es5sleep() {
    console.log('es5 sleep')
}
sleep3(es5sleep, 1000)

function* sleep4(wait) {
    yield new Promise((resolve, reject) => {
        setTimeout(resolve, wait)
    })
}
let s4 = sleep4(1000)
s4.next().value.then(_ => {
    console.log('generator sleep')
})

var a = 10;
(function () {
    console.log(a)
    a = 5
    console.log(window.a)
    var a = 20;
    console.log(a)
})()

let a = {
    v: 1,
    /*toString() {
        return a.v++
    }*/
    valueOf() {
        return a.v++
    }
}
if( a == 1 && a == 2 && a == 3 ) {
  console.log(1);
}

var arr=[1,2,3,[4,5],[6,[7,[8]]]]

function flat1() {
    let result = []
    return function flat(arr) {
        arr.forEach(o => {
            if(o.constructor === Array) {
                result.concat(flat(o))
            } else {
                result.push(o)
            }
        })
        return result
    }
}
console.log(flat1()(arr))

function flat2(arr) {
    return arr.reduce((pre, cur) => {
        return cur.constructor === Array ? pre.concat(flat2(cur)) : pre.concat(cur)
    }, [])
}
console.log(flat2(arr))

let arr1 = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'D1', 'D2']
let arr2 = ['A', 'B', 'C', 'D']

function comArr(arr1, arr2) {
    let num = 0
    while(arr2.length) {
        let firstEle = arr2.shift()
        for(let i = num; i <= arr1.length; i++) {
            if(arr1[i] === undefined) {
                arr1.push(firstEle)
                break
            }
            if(!arr1[i].includes(firstEle)) {
                num = i + 1
                arr1.splice(i, 0, firstEle)
//                debugger
                break;
            }
        }
        
    }
    return arr1
}

console.log(comArr(arr1, arr2))
上一篇下一篇

猜你喜欢

热点阅读