最近面试常常遇到手写xx实现。。有空特意实现了一番,整理记录
/**
call 的手写实现
*/
Function.prototype.myCall = function(context) {
let temp=Symbol('call');
context= context || window;
context[temp]=this;
let args=[]
for(let i=1; i<arguments.length; i++){
args.push(arguments[i])
}
let result= context[temp](...args)
delete context[temp]
return result;
}
关于bind的理解:
和call apply 的作用很相似,唯一的区别就是绑定this 指向后,不会立即执行。
/**
* bind 手写实现
* @returns {function(): *}
*/
Function.prototype.myBind = function () {
let that=this, thatArgs=arguments[0], args = Array.prototype.slice.call(arguments, 1)
if(typeof that !== 'function') {
throw new TypeError('myBind callback is not a function');
}
return function (){
return that.apply(thatArgs, args);
}
}
/**
* new的 手写实现
**/
function _news (fn, ...args) {
let obj= {}
obj.__proto__= fn.prototype;
let result =fn.apply(obj,...args)
return result instanceof Object ? result : false
}
/**
* 斐波拉契,求和
* 0 1 2 3 5 8 13
* @param n
* @returns {*}
*/
function Fibonacci(n) {
let val = new Array(n).fill(0) // 初始化数组长度为n,默认值为0
val[1] = 1;
val[2] = 2;
for (let i = 3; i <= n; ++i) {
val[i] = val[i - 1] + val[i - 2];
}
return val
}
let count = Fibonacci(2).reduce(function (pre, current) {
return pre + current
})
console.error('val=====>', count);
插入排序:
从数组下标1 开始,每遍历一次,比较的元素在原基础上加1,越往后遍历次数越多。
![696c12ffb323545b0d01d7b2c0d16085.png](https://i-blog.csdnimg.cn/blog_migrate/5ffc3c941ff834fe0ef0fedbecf90305.jpeg)
function insertSort (arr) {
for (var i = 1;i < arr.length;i++){
for(var j = i;j > 0 && arr[j] < arr[j-1];j--){
// 当前值和之前的每个值进行比较,发现有比当前值小的值就进行交换
let temp = arr[j]; //先取出 next 值,即 小的那个
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
return arr
}
// 优化版 少一次赋值
function insertSort(arr) {
var len = arr.length;
var temp;
for (var i = 1; i < len; i++) {
temp = arr[i]
for (var j = i; j > 0 && temp < arr[j - 1]; j--) {
// 当前值和之前的每个值进行比较,发现有比当前值小的值就进行重新赋值
arr[j] = arr[j - 1];
}
arr[j] = temp;
}
return arr;
}
快速排序:
参见阮一峰老师的博客,很通俗易懂:
快速排序(Quicksort)的Javascript实现 - 阮一峰的网络日志www.ruanyifeng.com![b83b399ce8a969171d37c6c6e229224e.png](https://i-blog.csdnimg.cn/blog_migrate/c28c601a31e011abadd14f54f149f852.jpeg)
/**
* 核心思想:
(1)在数据集之中,选择一个元素作为"基准"(pivot)。
(2)所有小于"基准"的元素,都移到"基准"的左边;所有大于"基准"的元素,
都移到"基准"的右边。
(3)对"基准"左边和右边的两个子集,不断重复第一步和第二步,
直到所有子集只剩下一个元素为止。
*/
function quickSort(array) {
if (array.length <= 1) { return array }
let left=[], right =[];
let middleIndex = Math.floor(array.length/2);
let middleValue= arr.splice(middleIndex,1)[0]
for (let index = 0; index < array.length; index++) {
if(array[index] < middleValue) {
left.push (array[index])
}else{
right.push (array[index])
}
}
return quickSort(left).concat([middleValue],quickSort(right))
}