Last active
November 2, 2021 15:21
-
-
Save RoseCrime/51d57fbb65012c962804879bbb516f58 to your computer and use it in GitHub Desktop.
Stuff I keep using over and over again
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Logging | |
const log = val => console.log(val), | |
error = message => console.error(message), | |
type = val => log(typeof val) | |
//Math | |
let random = (min, max) => Math.random() * (max - min + 1) + min, | |
floor = val => Math.floor(val), | |
abs = val => Math.abs(val) | |
//Re-maps value from one range to another. | |
const map = (value, in_min, in_max, out_min, out_max) => (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min | |
//Work with elements | |
const elementInfo = element => { | |
let x = element.getBoundingClientRect().left + window.scrollX, | |
y = element.getBoundingClientRect().top + window.scrollY, | |
width = element.getBoundingClientRect().width, | |
height = element.getBoundingClientRect().height, | |
center = { | |
x: x + 1 / 2 * width, | |
y: y + 1 / 2 * height | |
} | |
return { | |
x: x, | |
y: y, | |
width: width, | |
height: height, | |
center: center | |
} | |
} | |
//contains 'x' 'y' 'width' 'height' , 'center.x' , 'center.y' | |
const distance = (elt1, elt2) => { | |
let x1 = elementInfo(elt1).center.x, | |
y1 = elementInfo(elt1).center.y, | |
x2 = elementInfo(elt2).center.x, | |
y2 = elementInfo(elt2).center.y, | |
w1 = elementInfo(elt1).width, | |
h1 = elementInfo(elt1).height, | |
w2 = elementInfo(elt2).width, | |
h2 = elementInfo(elt2).height, | |
intersectX = abs(x1 - x2) < w1 / 2 + w2 / 2, | |
intersectY = abs(y1 - y2) < h1 / 2 + h2 / 2, | |
intersection = false, | |
x, y | |
x1 != x2 ? ( | |
x1 < x2 ? | |
(x = (x2 - w2 / 2) - (x1 + w1 / 2)) : | |
(x = (x1 - w1 / 2) - (x2 + w2 / 2)) | |
) : | |
(x = 0) | |
y1 != y2 ? ( | |
y1 < y2 ? | |
(y = (y2 - h2 / 2) - (y1 + h1 / 2)) : | |
(y = (y1 - h1 / 2) - (y2 + h2 / 2)) | |
) : | |
(y = 0) | |
if (intersectX && intersectY) intersection = true | |
return { | |
x: x, | |
y: y, | |
inretsects: intersection | |
} | |
} | |
//Count distance between 2 DOM elements , checks if it intersects. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment