Pass a Class
function callMethods(evt) {
const e = new evt
e.one()
e.two()
}callMethods(class {
one() {
console.log('one')
}two() {
console.log('two')
}})
This is so tempting for something I want to do… but too strange to use probably… maybe…
function callMethods(evt) {
const e = new evt
e.one()
e.two()
}callMethods(class {
one() {
console.log('one')
}two() {
console.log('two')
}})
This is so tempting for something I want to do… but too strange to use probably… maybe…
// read through the comments of this snippet...function dist1(x1, y1, x2, y2) {
const dx = x1 - x2
const dy = y1 - y2
return Math.sqrt(dx**2 + dy**2)
}function dist2({x1, y1, x2, y2}) {
const dx = x1 - x2
const dy = y1 - y2
return Math.sqrt(dx**2 + dy**2)
}// What's the difference here... welldist1(50, 50, 100, 100)
// vsdist2({ x1: 50, y1: 50, x2: 100, y2: 100 })
// so what?// With `dist2` the order of the arguments doesn't matter// and the arguments are named now as a result of being keys// in an object// How many times have you changed a core function or method as you're// working on a project?// Let's see another example:// circle(100, 200, 300, 'red', 'blue', 0, 0)// Can you guess what those arguments are? It's not really a big deal// and editors help with this, typescript helps with this... but what about:circle({
x: 10,
y: 110,
radius: 120,
fill: 'red',
stroke: 'blue',
velocityX: 0,
velocitY: 0
})
// how about...circle({ radius: 50, fill: 'blue' })
// or...circle({ stroke: 'green', x: 40, velocityX: 1 })
// etc...circle({
radius: 50,
stroke: 'black', x: 200,
fill: 'teal',
velocityY: 1, velocityX: -1 })
// In combination with default arguments we end up with a very easy pattern for functions/methods// with a complex argument signature. gsap (aka TweenLite/TweenMax) has used this pattern for many// years. I've seen similar things in many languages...// How does the circle function look?function circle({
x = 0, y = 0,
radius = 30,
fill = 'black',
stroke = 'transparent',
velocityX = 0, velocityY = 0}) {
const diam = radius * 2;
const circle = document.body.appendChild(
Object.assign(
document.createElement('div'),
{ style: `
position: absolute;
left: ${x}px;
top: ${y}px;
width: ${diam}px;
height: ${diam}px;
background: ${fill};
border: 3px solid ${stroke};
border-radius: 100%;
`
} ) )if (velocityX != 0 || velocityY != 0) {
setInterval(() => {
x += velocityX y += velocityYcircle.style.left = `${x}px`
circle.style.top = `${y}px`
}, 16)
} return circle}// here is a golfed distance function - for no reasond=(a,b,c,d,e=a-c,f=b-d)=>Math.sqrt(e*e+f*f)
console.log(
dist1(0, 0, 140, 140) ===
d(0, 0, 140, 140)
)