记录 30 seconds of code 项目个人觉得中有价值的片段或者小技巧(四)

J - Z 系列

获取数组元素下标(findIndex的实现)

1const linearSearch = (arr, item) => { 2 for (const i in arr) { 3 if (arr[i] === item) return +i; 4 } 5 return -1; 6}; 7 8linearSearch([2, 9, 9], 9); // 1 9linearSearch([2, 9, 9], 7); // -1 10// 只返回数组中的第一个

绑定事件一次(前面也有类似函数)

1const listenOnce = (el, evt, fn) => 2 el.addEventListener(evt, fn, { once: true }); 3 // 可以传入 option(对象) 也可以传入 useCapture(布尔) 4 5listenOnce( 6 document.getElementById('my-id'), 7 'click', 8 () => console.log('Hello world') 9); // 'Hello world' will only be logged on the first click

给定键值对,转换为对象

1const objectFromPairs = arr => 2 // 结构赋值,直接获取了 key和value 3 arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); 4 5objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2}

检测用户是否是暗黑模式

1const prefersDarkColorScheme = () => 2 window && 3 window.matchMedia && 4 window.matchMedia('(prefers-color-scheme: dark)').matches; 5 6prefersDarkColorScheme(); // true

将字节单位大小转换为 KB,MB等

1const prettyBytes = (num, precision = 3, addSpace = true) => { 2 const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 3 if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; 4 const exponent = Math.min( 5 Math.floor(Math.log10(num < 0 ? -num : num) / 3), 6 UNITS.length - 1 7 ); 8 const n = Number( 9 ((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision) 10 ); 11 return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; 12}; 13 14prettyBytes(1000); // '1 KB' 15prettyBytes(-27145424323.5821, 5); // '-27.145 GB' 16prettyBytes(123456789, 3, false); // '123MB'

返回提供日期的季度

1const quarterOfYear = (date = new Date()) => [ 2 Math.ceil((date.getMonth() + 1) / 3), 3 date.getFullYear() 4]; 5 6quarterOfYear(new Date('07/10/2018')); // [ 3, 2018 ] 7quarterOfYear(); // [ 4, 2020 ]

将url问号后参数转换为键值对

1const queryStringToObject = url => 2 [...new URLSearchParams(url.split('?')[1])].reduce( 3 (a, [k, v]) => ((a[k] = v), a), 4 {} 5 ); 6 7queryStringToObject('https://google.com?page=1&count=10'); 8// {page: '1', count: '10'}

数组快速排序

1const quickSort = arr => { 2 const a = [...arr]; 3 if (a.length < 2) return a; 4 // 向下取整 5 const pivotIndex = Math.floor(arr.length / 2); 6 const pivot = a[pivotIndex]; 7 const [lo, hi] = a.reduce( 8 (acc, val, i) => { 9 if (val < pivot || (val === pivot && i != pivotIndex)) { 10 acc[0].push(val); 11 } else if (val > pivot) { 12 acc[1].push(val); 13 } 14 return acc; 15 }, 16 [[], []] 17 ); 18 return [...quickSort(lo), pivot, ...quickSort(hi)]; 19}; 20 21quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]

生成指定长度随机字符串

1const randomAlphaNumeric = length => { 2 let s = ''; 3 Array.from({ length }).some(() => { 4 s += Math.random().toString(36).slice(2); 5 return s.length >= length; 6 }); 7 return s.slice(0, length); 8}; 9 10randomAlphaNumeric(5); // '0afad'

随机16进制颜色

1const randomHexColorCode = () => { 2 let n = (Math.random() * 0xfffff * 1000000).toString(16); 3 return '#' + n.slice(0, 6); 4}; 5 6randomHexColorCode(); // '#e34155'

随机范围数组

1const randomIntArrayInRange = (min, max, n = 1) => 2 Array.from( 3 { length: n }, 4 () => Math.floor(Math.random() * (max - min + 1)) + min 5 ); 6 7randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]

随机数

1const randomIntegerInRange = (min, max) => 2 Math.floor(Math.random() * (max - min + 1)) + min; 3 4randomIntegerInRange(0, 5); // 2

创建一个生成器,该生成器使用给定的步长生成给定范围内的所有值

1const rangeGenerator = function* (start, end, step = 1) { 2 let i = start; 3 while (i < end) { 4 yield i; 5 i += step; 6 } 7}; 8 9// for of 用于遍历集合 (迭代器对象) 10for (let i of rangeGenerator(6, 10)) console.log(i); 11// Logs 6, 7, 8, 9

requestAnimationFrame 动画帧的形式,调用回调,同时提供取消方法

1const recordAnimationFrames = (callback, autoStart = true) => { 2 let running = false, 3 raf; 4 const stop = () => { 5 if (!running) return; 6 running = false; 7 cancelAnimationFrame(raf); 8 }; 9 const start = () => { 10 if (running) return; 11 running = true; 12 run(); 13 }; 14 const run = () => { 15 raf = requestAnimationFrame(() => { 16 callback(); 17 if (running) run(); 18 }); 19 }; 20 if (autoStart) start(); 21 return { start, stop }; 22}; 23 24const cb = () => console.log('Animation frame fired'); 25const recorder = recordAnimationFrames(cb); 26// logs 'Animation frame fired' on each animation frame 27recorder.stop(); // stops logging 28recorder.start(); // starts again 29const recorder2 = recordAnimationFrames(cb, false); 30// `start` needs to be explicitly called to begin recording frames

根据提供函数,过滤数组对象,并且保留需要的键值对

1const reducedFilter = (data, keys, fn) => 2 data.filter(fn).map(el => 3 keys.reduce((acc, key) => { 4 acc[key] = el[key]; 5 return acc; 6 }, {}) 7 ); 8 9const data = [ 10 { 11 id: 1, 12 name: 'john', 13 age: 24 14 }, 15 { 16 id: 2, 17 name: 'mike', 18 age: 50 19 } 20]; 21reducedFilter(data, ['id', 'name'], item => item.age > 24); 22// [{ id: 2, name: 'mike'}] 23// 有点意思,将保留的键数组,利用reduce再重组下

回到顶部,带动画

1const scrollToTop = () => { 2 const c = document.documentElement.scrollTop || document.body.scrollTop; 3 if (c > 0) { 4 window.requestAnimationFrame(scrollToTop); 5 window.scrollTo(0, c - c / 8); 6 } 7}; 8 9// requestAnimationFrame api的运用,同时可以扩展(滚动到指定元素或者其他方向) 10// c - c / 8 距离的计算可以学习下(类似缓动动画?)

数组打乱顺序

1const shuffle = ([...arr]) => { 2 let m = arr.length; 3 while (m) { 4 const i = Math.floor(Math.random() * m--); 5 // 变量交换位置 6 [arr[m], arr[i]] = [arr[i], arr[m]]; 7 } 8 return arr; 9}; 10 11const foo = [1, 2, 3]; 12shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

去掉html标签

1const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); 2 3stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'

reduce的求和

1const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); 2 3sum(1, 2, 3, 4); // 10 4sum(...[1, 2, 3, 4]); // 10
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

记录 30 seconds of code 项目个人觉得中有价值的片段或者小技巧(二)

DF系列1、防抖函数,限制高频触发jsconstdebounce(fn,ms0)lettimeoutId;returnfunction(...args)clearTimeout(timeoutId);timeoutIdsetTimeout(()fn.apply(this,args),ms);

记录 30 seconds of code 项目个人觉得中有价值的片段或者小技巧 (一)

AC系列1、号的隐式类型转换使用js3//31,2,3.slice(1)//将3转换为了32、日期的转换jsconstaddDaysToDate(date,n)constdnewDate(date);d.setDate(d.getDate()n);returnd.toISOS