Skip to content

Instantly share code, notes, and snippets.

@bjrmatos
Forked from therealklanni/README.md
Last active August 29, 2015 14:23
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 bjrmatos/d5d29821f235b6fff5fd to your computer and use it in GitHub Desktop.
Save bjrmatos/d5d29821f235b6fff5fd to your computer and use it in GitHub Desktop.

repeat(a) -> [a]

Inspired by Haskell, I wanted to see if I could replicate, using ES6 features, the repeat function:

repeat :: a -> [a]

So as you can see in repeat.js, I have done exactly that. However there are some caveats.

First, I still need to make the result behave like a normal array (with all of Array's prototype methods), but it's a good start anyway.

You can access any index in the array and get the repeated value. You can even loop over it as much as you want and keep taking the repeated value each time. Infinitely, as far as I know (of course I didn't test how far it would go, because that would literally take forever, but even a number more than 10 digits long still produced the repeated value and that was good enough for me).

var batman = repeat('nana')

// don't try this at home, kids!
for (i=0;;i++) {
  console.log(batman[i])
}

Another caveat is that it also does this for literally any value given to the accessor.

var repeatBeep = repeat('boop')

repeatBeep['foobar'] // => "boop"

Obviously I can fix this easily by adding a type check to the get method passed into Proxy, but I just wanted to get the very basic functionality working (because it's 5am and I've been up all night).

The final caveat of course being the fact that there's almost no support for Proxy at this point. Literally only FireFox and Edge at this time. So feel free to drop that repeat function in the FF console and play around with infinitely-repeating arrays. Keep in mind, again, that the Array methods are still missing from this implementation, so don't expect to be able to slice() that array or anything fancy right now.

Of course, this proof-of-concept could have other (more useful?) applications as well. Don't like having to call .next().value on generators? Would you rather treat it like an array? I think we can accomodate.

That's it for now, but I'll probably update this when I get around to making the proxy more Array-like.

var repeat = (a) => new Proxy([], {
get: () => a
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment