资讯专栏INFORMATION COLUMN

前端笔试之手写代码

zhichangterry / 2880人阅读

摘要:扁平化嵌套数组实现描述将嵌套多层的数组展开平铺成只有一层的数组。方法一知识点方法二知识点方法三知识点展开语法其它方法数组去重描述将数组中重复的元素过滤掉。对于函数防抖,门外有人频繁敲门,门卫按最后一次敲门来决定是否开门。知识点发布订阅模式

1. 扁平化嵌套数组/flat实现

描述:将嵌套多层的数组展开平铺成只有一层的数组。

let array = [1, [1, 2, 3], [1, [2, {}]] ]
handle(array) // [1, 1, 2, 3, 1, 2, {}]

方法一

const handle = array => JSON.parse(`[${JSON.stringify(array).replace(/[|]/g,"")}]`)
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

知识点JSON.parse()/JSON.stringify()String.prototype.replace()

方法二

const handle = array => array.reduce((accumulator, currentValue) => accumulator.concat(Array.isArray(currentValue) ? handle(currentValue): currentValue), [])
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

知识点Array.prototype.reduce()Array.prototype.concat()

方法三

const handle = array => {
    while(array.some(item => Array.isArray(item))) {
        array = [].concat(...array)
    }
    return array
}
handle(array)   // [ 1, 1, 2, 3, 1, 2, {} ]

知识点whileArray.prototype.some()展开语法(Spread syntax)

其它方法:......

2. 数组去重

描述:将数组中重复的元素过滤掉。

let array = [1, 2, 1, "3", "3", 0 , 1]
handle(array)   // [1, 2, "3", 0]

方法一

const handle = array => [...new Set(array)]
handle(array)   // [ 1, 2, "3", 0 ]

知识点:Set

方法二

const handle = array => array.reduce((accumulator, currentValue) => {
    !accumulator.includes(currentValue) && accumulator.push(currentValue)
    return accumulator
}, [])
handle(array)   // [ 1, 2, "3", 0 ]

知识点:Array.prototype.includes()

方法三

const handle = array => {
    let map = new Map()
    return array.filter(item => map.has(item) ? false : map.set(item))
}
handle(array)   // [ 1, 2, "3", 0 ]

知识点MapArray.prototype.filter()

其它方法:......

3. 模拟bind实现
Function.prototype.bind = function () {
    let self = this, args = Array.from(arguments), context = args.shift();
    return function () {
        return self.apply(context, args.concat(...arguments))
    };
};

知识点apply、call、bind

4. 模拟New实现
const handle = function() {
    let fn = Array.prototype.shift.call(arguments)
    let obj = Object.create(fn.prototype)
    let o = fn.apply(obj, arguments)
    return typeof o === "object" ? o : obj;
}

知识点Object.create()

5. 格式化数字
const num = 123456789;
const handle = num => String(num).replace(/B(?=(d{3})+(?!d))/g, ",")
handle(num) // 123,456,789

知识点正则表达式String.prototype.replace()

6. 回文判断
const num = 123456654321;
const str = "abababababab";
const handle = params => {
    let str_1 = String(params).replace(/[^0-9A-Za-z]/g, "").toLowerCase();
    let str_2 = str_1.split("").reverse().join();
    return str_1 === str_2 ? true : false
}
handle(num) // true
handle(str) // false

知识点String.prototype.split()Array.prototype.join()

7. 函数节流 定时器
const handle = (fn, interval) => {
    let timeId = null;
    return function() {
        if (!timeId) {
            timeId = setTimeout(() => {
                fn.apply(this, arguments)
                timeId = null
            }, interval)
        }
    }
}

知识点window.setTimeout

时间戳
const handle = (fn, interval) => {
    let lastTime = 0
    return function () {
        let now = Date.now();
        if (now - lastTime > interval) {
            fn.apply(this, arguments)
            lastTime = now
        }
    }
}
8. 函数防抖
const handle = (fn, delay) => {
    let timeId;
    return function() {
        if (timeId) clearTimeout(timeId)
        timeId = setTimeout(() => {
            fn.apply(this, arguments)
        }, delay)
    }
}

函数节流、函数防抖区别:函数节流和函数防抖较容易混淆,可以这么比喻,对于函数节流,门外有人频繁敲门,但是门卫按固定时间来决定是否开门。对于函数防抖,门外有人频繁敲门,门卫按最后一次敲门来决定是否开门。

知识点window.clearTimeout

9. 发布订阅模式
class Pubsub {
    constructor() {
        this.handles = {}
    }
    subscribe(type, handle) {
        if (!this.handles[type]) {
            this.handles[type] = []
        }
        this.handles[type].push(handle)
    }
    unsubscribe(type, handle) {
        let pos = this.handles[type].indexOf(handle)
        if (!handle) {
            this.handles.length = 0
        } else {
            ~pos && this.handles[type].splice(pos, 1)
        }
    }
    publish() {
        let type = Array.prototype.shift.call(arguments)
        this.handles[type].forEach(handle => {
            handle.apply(this, arguments)
        })
    }
}

const pub = new Pubsub()
pub.subscribe("a", function() {console.log("a", ...arguments)})
pub.publish("a", 1, 2, 3)
// a 1 2 3

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/102041.html

相关文章

  • 一篇字节跳动前端面经

    摘要:为了避免它,只需分配将要使用的必要构造函数。示例对于此示例,就需要保持父构造函数继续正常工作。结论手动设置或更新构造函数可能会导致不同且有时令人困惑的后果。为了防止它,只需在每个特定情况下定义构造函数的角色。 hr小姐姐说一共有1轮笔试 + 3轮技术面 + 1轮hr面,面试地点在中关村天使大厦,岗位是1-3年前端 笔试 笔试分为多选 简答 判断 手写代码四部分,下面只写了印象比较深的几...

    caige 评论0 收藏0
  • 记录一下自己的春招,唯品会、360、京东offer已收、腾讯offer_call已达!!!

    摘要:春招结果五月份了,春招已经接近尾声,因为到了周五晚上刚好有空,所以简单地记录一下自己的春招过程。我的春招从二月初一直持续到四月底,截止今天,已经斩获唯品会电商前端研发部大数据与威胁分析事业部京东精锐暑假实习生的腾讯的是早上打过来的。 春招结果 五月份了,春招已经接近尾声,因为到了周五晚上刚好有空,所以简单地记录一下自己的春招过程。我的春招从二月初一直持续到四月底,截止今天,已经斩获唯品...

    freewolf 评论0 收藏1
  • 我的春招求职经验分享(已拿阿里京东网易等 5 个 offer)

    摘要:面经因为我完全没有面试经验,从来没有经历过面试,于是想着在去这类大公司面试之前先找成都的小公司练练手,积累点面试经验。于是三月份开始就有成都的小公司开始约我面试。 前序 从我高考成绩出来那一刻开始,从我在高考志愿上填上计算机科学与技术这几个当时在心中堪称神圣的几个字开始,我就已经把进入中国互联网最高殿堂BAT作为我整个大学奋斗的目标,哪怕我就读的是一所位于内陆的双非一本大学我也认为我能...

    Winer 评论0 收藏1
  • 前端面试手写代码

    摘要:虽然构造函数或者对象字面量的方法都可以用来创建对象,但是这些方法使用同一个接口创建很多对象,会产生大量的重复代码。参考资料冴羽的专题系列中高级前端面试手写代码无敌秘籍前端笔试之手写代码一本系列会从面试的角度出发围绕JavaScript,Node.js(npm包)以及框架三个方面来对常见的模拟实现进行总结,具体源代码放在github项目上,长期更新和维护 showImg(https://use...

    niceforbear 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<