Skip to content

Instantly share code, notes, and snippets.

@afaur
Created March 25, 2017 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afaur/73d6a724516a93dbe03e08f0f5e46f08 to your computer and use it in GitHub Desktop.
Save afaur/73d6a724516a93dbe03e08f0f5e46f08 to your computer and use it in GitHub Desktop.
Add `Num(#).times` to Javascript (based on `#.times` in Ruby)
// Create a `Num` function that initializes a special object
// On the special object we define a property that acts like a function. This function
// calls a block/func the amount of times equal to the value passed in at the time of
// instance initialization.
var Num = function(num) {
var SpecialNumber = { value: num }
Object.defineProperty(SpecialNumber, 'times', {
get: function() {
return function (fn) {
for (let i=1; i<=SpecialNumber.value; i++) { fn() }
}
},
set: function(fn) {
for (let i=1; i<=SpecialNumber.value; i++) { fn() }
},
enumerable: false,
configurable: false
})
// If Symbol and Generator support then enable (for..of handler)
// Comment next 4 lines to disable support (implementation)
SpecialNumber.forTimes = {}
SpecialNumber.forTimes[Symbol.iterator] = function* () {
for (let i=1; i<=SpecialNumber.value; i++) { yield i }
}
return SpecialNumber
}
console.log('-----------Usage-ES5-----------')
console.log('ES5: Example 1')
Num(1).times = function() { console.log('- Example') }
console.log('ES5: Example 2')
var fn = Num(2).times
fn(function() { console.log('- Example') })
console.log('ES5: Example 3')
eval(Num(3).times)(function() { console.log('- Example') })
console.log('-----------Usage-ES6-----------')
console.log('ES6: Example 1')
Num(1).times = () => { console.log('- Example') }
console.log('ES6: Example 2')
var fn = Num(2).times
fn(() => console.log('- Example'))
console.log('ES6: Example 3')
eval(Num(3).times)(() => console.log('- Example'))
// If Symbol and Generator support then enable (for..of handler)
// Comment next 4 lines to disable support (example)
console.log('ES6: Example 4')
for (let num of Num(3).forTimes) {
console.log('- Example ', num)
}
console.log('-------------------------------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment