收集一些基础的、精彩的JavaScript代码片段。
查找算法
二分查找(适用于有序数据)O(logn)
// 从中间开始,查找元素x,比x小,从右侧元素找
const find = function (arr, findEl) {let min = 0let count = 0let max = arr.length - 1while (min < max) {count++let middle = Math.floor((min + max) / 2)let middleEl = arr[middle]if (middleEl === findEl) {console.log('循环了多少次:', count)return middle}if (middleEl < findEl) {min = middle + 1} else {max = middle - 1}}
}
console.log('find', find([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9))
选择排序(每次都找到当前数组中最小的插入到新数组,然后再次找剩下元素中的最小元素)
// 找到最小的
const findSmallest = function (arr) {let smallest = arr[0]let smallest_index = 0for (let i = 0; i < arr.length; i++) {if (arr[i] < smallest) {smallest = arr[i]smallest_index = i}}return smallest_index
}
const selectionSort = function (arr) {let newArr = []let idx = arr.length - 1while (idx >= 0) {if (idx < 0) returnconst smallest_index = findSmallest(arr)const el = arr.splice(smallest_index, 1)newArr.push(el[0])idx--}return newArr
}
console.log('selectionSort([5, 3, 6, 2, 10])', selectionSort([5, 3, 6, 2, 10]))
快速排序 O(n*logn)
// 找一个基准数,比它小的放左边子数组,比它大的放右边子数组,重复步骤,知道只剩下一个元素
const quicksort = function (arr) {if (arr.length < 2) return arrconst middle = arr.splice(Math.floor(arr.length / 2), 1)[0]const less = arr.filter(v => v < middle)const greater = arr.filter(v => v > middle)return quicksort(less).concat([middle]).concat(quicksort(greater))
}
console.log('quicksort([10, 5, 2, 3])', quicksort([10, 5, 2, 3]))
散列函数
// 对于输入点一个固定的数,得到的总会是一个固定的值
const sanlieFun = function (el) {let obj = {a: 1,b: 2}return obj[el]
}
图-广度优先搜索(非加权图 寻找从a到b的最‘短’路径)
// 有序的图 为 拓扑排序
// 从上往下 不能从下往上的 为 树
// 图-狄克斯特拉算法(加权图 只适用于有向无环图 寻找从a到b的最‘快’路径)
// 不能将狄克斯特拉算法用于包含负权边的图 。在包 含负权边的图中,要找出最短路径,可使用另一种算法——贝尔曼-福 德算法
let processed = {}
const findLowestCostNode = function (costs) {let lowest_cost = Infinitylowest_cost_node = nullfor (const node in costs) {if (Object.hasOwnProperty.call(costs, node)) {const cost = costs[node]if (cost < lowest_cost && !processed.node) {lowest_cost = costlowest_cost_node = node}}}return lowest_cost_node
}
const dkstlsfFun = function () {let graph = {start: {a: 6,b: 2},a: {fin: 1},b: {a: 3,fin: 5},fin: {}}let costs = {a: 6,b: 2,fin: Infinity}let parents = {a: 'start',b: 'start',fin: null}let node = findLowestCostNode(costs)while (!processed.node) {const cost = costs[node]let neighbors = graph[node]for (let i = 0; i < Object.keys(neighbors).length; i++) {const v = Object.keys(neighbors)[i]const new_cost = cost + neighbors[v]if (costs[v] > new_cost) {costs[v] = new_costparents[v] = node}}processed.node = truenode = findLowestCostNode(costs)}console.log('graph', graph, costs, parents)
}
dkstlsfFun()
工具类
根据秒值转时分秒展示
利用momentjs库快捷获取时分秒值,判断拼接文本,return出拼接文本和原始值
import moment from 'moment'
const GetDateTextBySeconds = function (val) {const duration = moment.duration(val, 'seconds')const hours = Math.floor(duration.asHours())const minutes = Math.floor(duration.minutes())const seconds = Math.floor(duration.seconds())let res = ''if (hours > 0) {res += hours + '时 '}if (minutes > 0 || hours > 0) {res += minutes + '分 '}res += seconds + '秒'return {text: res,seconds: val}
}
检查和展示有效的经纬度坐标
经度范围-180~180,0表示本初子午线,值为正数则表示东经E,负数表示西经W。
维度范围-90~90,0表示赤道,值为正数则表示北纬N,值为负数表示南纬S。
按照这条规则,可以封装判断是否为有效的经纬度值,并且组合展示经纬度文本。这儿展示时经纬度展示了小数点后6位。
const ValidLatitude = function (lat) {return isFinite(lat) && Math.abs(lat) <= 90
}
const ValidLongitude = function (lon) {return isFinite(lon) && Math.abs(lon) <= 180
}
const ValidCoordinates = function (lon, lat) {return ValidLongitude(lon) && ValidLatitude(lat)
}// 显示有效的经纬度
const ShowLatitude = function (lat) {if (!ValidLatitude(lat)) returnconst res = parseFloat(lat).toFixed(6)if (res >= 0) {return 'N' + res} else {return 'S' + res}
}
const ShowLongitude = function (lon) {if (!ValidLongitude(lon)) returnconst res = parseFloat(lon).toFixed(6)if (res >= 0) {return 'E' + res} else {return 'W' + res}
}
const FormatCoordinates = function (lng, lat) {return ShowLongitude(lng) + ', ' + ShowLatitude(lat)
}