Performance measuring, scroll to top, array flattening
This commit is contained in:
9
snippets/flatten-array.md
Normal file
9
snippets/flatten-array.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Flatten array
|
||||
|
||||
Use recursion.
|
||||
Use `reduce()` to get all elements that are not arrays, flatten each element that is an array.
|
||||
|
||||
```js
|
||||
var flatten = arr =>
|
||||
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? flatten(v) : v ), []);
|
||||
```
|
||||
12
snippets/measure-time-taken-by-function.md
Normal file
12
snippets/measure-time-taken-by-function.md
Normal file
@ -0,0 +1,12 @@
|
||||
### Measure time taken by function
|
||||
|
||||
Use `performance.now()` to get start and end time for the function, `console.log()` the time taken.
|
||||
First argument is the function name, subsequent arguments are passed to the function.
|
||||
|
||||
```js
|
||||
var timeTaken = (f,...args) => {
|
||||
var t0 = performance.now(), r = f(...args);
|
||||
console.log({performance.now() - t0);
|
||||
return r;
|
||||
}
|
||||
```
|
||||
14
snippets/scroll-to-top.md
Normal file
14
snippets/scroll-to-top.md
Normal file
@ -0,0 +1,14 @@
|
||||
### Scroll to top
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
Scroll by a fraction of the distance from top. Use `window.requestFrame()` to animate the scrolling.
|
||||
|
||||
```js
|
||||
var scrollToTop = _ => {
|
||||
var c = document.documentElement.scrollTop || document.body.scrollTop;
|
||||
if(c > 0) {
|
||||
window.requestAnimationFrame(scrollToTop);
|
||||
window.scrollTo(0, c - c/8);
|
||||
}
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user