记录一些在笔试过程中遇到的题目,做法不一定对,如果你对于题目有其他想法,欢迎讨论。
1、实现一个Event类,on为监听事件,trigger触发事件,off消除事件
class Event {
constructor() {
this._cache = {}
}
on(type, cb) {
let fns = (this._cache[type] = this._cache[type] || [])
if (fns.indexOf(cb) === -1) {
fns.push(cb)
}
return this
}
trigger(type, data) {
let fns = this._cache[type]
if (Array.isArray(fns)) {
fns.forEach(fn => {
fn(data)
})
}
return this
}
off(type, cb) {
let fns = this._cache[type]
if (Array.isArray(fns)) {
if (cb) {
let index = fns.indexOf(cb)
if (index !== -1) {
fns.splice(index, 1)
}
} else {
fns.length = 0
}
}
return this
}
}
const event = new Event()
event.on('test', a => {
console.log(a)
})
event.trigger('test', 'water')
event.off('test')
event.trigger('test', 'hello world')
2、给出一个整数,实现一个函数,输出该整数的千分位划分,如12345,输出12,345
// 正则 零宽断言
function exchange(num) {
num += ''
if (num.length <= 3) return num
num = num.replace(/\d{1,3}(?=(\d{3})+$)/g, function(v) {
return v + ','
})
return num
}
console.log(exchange(1234567))
//
const num = 2333333
num.toLocaleString()
3、假设你有一个函数,产生[0, 5)之间的随机整数,每个数字概率1/5,如何使用这个函数产生[0, 7)之间的随机整数,每个数字概率1/7
/**
利用rand5()函数生成1-25之间的数字,然后将其中的1-21映射成1-7,丢弃22-25。
**/
function rand7() {
var res = 0
do {
res = (rand5() - 1) * 5 + rand5()
} while(res > 21)
return 1 + res % 7
}
4、完成方法shuffle(arr),传入数组arr,返回随机打乱后的数组
function shuffle(arr) {
return arr.sort(function() {
return Math.random() - 0.5
})
}
5、完成方法count(str),传入字符串,返回字符串中出现次数最多的字符及次数
function count(str) {
return [...new Set(str.split(''))]
.map(v => [v, str.match(new RegExp(v, 'g')).length])
.sort((a, b) => b[1] - a[1])
.slice(0, 1)
}
6、完成方法subset(arr1,arr2),传入两个数组,判断数组arr1是否为数组arr2的子集
function subset(arr1, arr2) {
if ((!arr1 instanceof Array) || (!arr2 instanceof Array)) return false
if (arr2.length < arr1.length) return false
for (let i = 0, len = arr1.length; i < len; i++) {
if (arr2.indexOf(arr1[i]) === -1) return false
}
return true
}
7、有一个数组,定义一个函数,传入arr后,返回值为一个二维数组:
const arr = [[1,2],3,[4,5,6]];
[[1,3,4],[2,3,4],[1,3,5],[2,3,5],[1,3,6],[2,3,6]]
function multiply(arr) {
let ret = []
function cur(result, index) {
if (index === -1) {
ret.push(result)
} else {
let items = Array.isArray(arr[index]) ? arr[index] : [arr[index]]
items.forEach(item => {
cur([item, ...result], index - 1)
})
}
}
cur([], arr.length - 1)
return ret
}
const arr = [
[1, 2], 3, [4, 5, 6]
];
console.log(multiply(arr))
8、前端路由的简单实现
function Router() {
this.routes = {}
this.currentUrl = ''
}
Router.prototype.route = function(path, callback) {
this.routes[path] = callback || function() {}
}
Router.prototype.refresh = function() {
this.currentUrl = location.hash.slice(1) || '/'
this.routes[this.currentUrl]()
}
Router.prototype.init = function() {
window.addEventListener('load', this.refresh.bind(this), false)
window.addEventListener('hashchange', this.refresh.bind(this), false)
}
window.Router = new Router()
window.Router.init()
Router.route('/', function() {
console.log('white')
})
Router.route('/blue', function() {
console.log('blue')
})
Router.route('/green', function() {
console.log('green')
})
9、有一个已经排序的数组,比方[1,4,6,9,11,15,18],给你一个新的数,插入到数组中
var arr = [1, 4, 6, 9, 11, 15, 18]
function arrIndexOf(arr, val) {
var mid,
min = 0,
max = arr.length - 1
while (min <= max) {
mid = (min + max) >> 1
if (val > arr[mid]) {
min = mid + 1
} else if (val < arr[mid]) {
max = mid - 1
} else {
return mid
}
}
return min
}
function insert(arr, val) {
if (arr[0] === val) {
arr.unshift(val)
} else if (arr[arr.length - 1] === val) {
arr.push(val)
} else {
arr.splice(arrIndexOf(arr, val), 0, val)
}
return arr
}
// or
function insert(arr, val) {
arr.push(val)
return arr.sort((a, b) => {
return a - b
})
}
10、实现HardMan类,符合以下要求
HardMan("jack")
// 输出 'I am jack'
HardMan("jack").rest(10).learn("computer")
// 输出 'I am jack'
// 10s后输出
// 'Start learning after 10 second'
// 'Learning computer'
HardMan("jack").restFirst(5).learn("chinese")
// 5s后输出
// 'Start learning after 5 second'
// 'I am jack'
// 'Learning chinese'
const HardMan = name => {
class HardMan {
constructor(name) {
this.queue = [this.init(name)]
setTimeout(async () => {
for (let todo of this.queue) {
await todo()
}
}, 0)
}
init(name) {
return () => console.log(`I am ${name}`)
}
learn(subject) {
this.queue.push(() => console.log(`Learning ${subject}`))
// 链式调用
return this
}
holdon(time) {
return () => new Promise(resolve => setTimeout(() => {
resolve(console.log(`Start learning after ${time} second`))
}, time * 1000))
}
rest(time) {
this.queue.push(this.holdon(time))
return this
}
restFirst(time) {
this.queue.unshift(this.holdon(time))
return this
}
}
return new HardMan(name)
}
11、套待出租的房子,价格分别是 b1 、b2 ... bm;由于习惯了微信支付,团队中每个人身上的现金都有限,分别是 a1 a2 ... an,对了,一起出门的老板还带有 S 元的团队经费,这个经费是每个人都可以使用的那么考虑以下两个场景
场景1 团队成员都很有爱,都愿意借钱给其他同事,那么这时候团队最多能租到多少房子
function max(Array n, Array m, S) {
return num
}
场景2 团队成员都十分小气,是不愿意借钱给别人的
//请判断团队成员是否都能租到房子
function isAll(Array n, Array m, S){
return bool
}
做法待商榷
场景1:
function max(Array n, Array m, S) {
let count = 0
n.forEach(item => {
count += item
})
count += S
let num = 0
let mSort = m.slice().sort((a, b) => {
return a - b
})
mSort.forEach(item => {
count -= item
if (count >= 0) num++
})
return num
}
场景2:
function isAll(n, m, S) {
let bool = null;
let arr = new Array(n.length);
const avg = S/n;
n.forEach((item, index) => {
arr[index] = item + avg
});
let mSort = m.slice().sort((a, b) => {
return a - b
});
let arrSort = arr.slice().sort((a, b) => {
return a - b
});
for(let i = 0, len = arrSort.length; i < len; i++) {
if (arrSort[i] < mSort[i]) {
bool = false;
break;
}
bool = true;
}
return bool;
}
12、实现一个函数,输入70040,返回[70000, 40]
function toCount(num) {
let arr = num.toString().split('')
return arr.reduce((pre, next, index, array) => {
if (next === '0') {
return pre
} else {
let item = parseInt(next) * Math.pow(10, array.length - index - 1)
pre.push(item)
return pre
}
}, [])
}
//or
function toCount1(num) {
let arr = num.toString().split('')
let len = arr.length
let ret = []
arr.forEach((item, index) => {
if (item != 0) {
ret.push(parseInt(item + '0'.repeat(len - index - 1)))
}
})
return ret
}
console.log(toCount1(60040))
13、请给Array实现一个方法,去重后返回重复的字符(新数组)
Array.prototype.extraChar = function () {
var cacheExtraChar = []
var that = this
this.map(function (item) {
(that.indexOf(item) !== that.lastIndexOf(item)) &&
cacheExtraChar.indexOf(item) === -1 ? cacheExtraChar.push(item) : -1
})
return cacheExtraChar
}