Last active
May 2, 2018 09:16
-
-
Save atomless/3cb6ef770c2fde260e571d35ec36fa28 to your computer and use it in GitHub Desktop.
playing with object and function composition
This file contains 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
const series = (...fns) => (...args) => fns.map(f => f(...args)); | |
const tailFactory = (width) => { | |
let wag_to_width_ratio = Math.random(); | |
let wagspeed = Math.ceil(width * wag_to_width_ratio); | |
return { | |
setWagSpeed({ width = 0 } = {}) { | |
wagspeed = Math.ceil(width * wag_to_width_ratio); | |
}, | |
wag() { console.log(Array(wagspeed).fill('WAG', 0, wagspeed).join(',')); } | |
}; | |
}; | |
const truthFactory = () => ({ | |
truth() { console.log(`A ${this.roar? 'spiky' : 'shaggy'} ${this.type || 'mystery'} ${this.tail? 'tail' : ''}`); } | |
}); | |
const dogFactory = (name, width, height) => { | |
let w = width, o = height; | |
return { | |
woof() { console.log(`${name} says W${Array(w).fill('w', 0, w).join('')}${Array(o).fill('o', 0, o).join('')}of!`); }, | |
resizeWoof({ width = 0, height = 0 } = {}) { | |
w = width, | |
o = height; | |
}, | |
get type() { return 'dog'; } | |
} | |
}; | |
const dragonFactory = (name, width, height) => { | |
let o = width, a = height; | |
return { | |
roar() { console.log(`${name} says R${Array(o).fill('o', 0, o).join('')}${Array(a).fill('a', 0, a).join('')}r!`); }, | |
resizeRoar({ width = 0, height = 0 } = {}) { | |
o = width, | |
a = height; | |
}, | |
get type() { return 'dragon'; } | |
} | |
}; | |
const dogDragonWithATailFactory = ({ | |
name = 'fluffy', | |
w = Math.round(Math.random() * 70), | |
h = Math.round(Math.random() * 90), | |
has_a_tail = Math.random() < 0.5, | |
is_secretly_a_dragon = Math.random() > 0.5 | |
} = {}) => ({ | |
...dogFactory(name, w, h), | |
...(is_secretly_a_dragon) && dragonFactory(name, w, h), | |
...(has_a_tail) && { tail: tailFactory(w) }, | |
...truthFactory() | |
}); | |
const kennelFactory = () => { | |
let dogs = []; | |
return { | |
addDog : d => dogs.push(d), | |
resize : ({ width = Math.round(Math.random() * 70), height = Math.round(Math.random() * 90) } = {}) => { | |
dogs.forEach(d => { | |
series(...[d.resizeWoof, d.resizeRoar, d.tail? d.tail.setWagSpeed : undefined].filter(fn => typeof fn !== 'undefined'))({ width, height }); | |
series(...[d.truth.bind(d), d.woof, d.roar, d.tail? d.tail.wag : undefined].filter(fn => typeof fn !== 'undefined'))(); | |
}); | |
return 'Kennel Resized!'; | |
} | |
}; | |
}; | |
myKennel = kennelFactory(); | |
for(let i = (Math.random() * 20); i > 0; i--) { myKennel.addDog(dogDragonWithATailFactory()); } | |
myKennel.resize(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment