Created
March 24, 2017 03:38
-
-
Save DadgadCafe/3cfa80651b5873b058855715bf906d87 to your computer and use it in GitHub Desktop.
generator-like range, using Proxy.
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
function fakeGen (fromV = 0, toV, step = 1) { | |
// only one arg | |
if (toV == undefined) { | |
toV = fromV | |
fromV = 0 | |
} | |
// init status | |
const status = { | |
done: false, | |
value: fromV - step | |
} | |
function setStatusDone () { | |
status.value = undefined | |
status.done = true | |
nextFn = () => status | |
} | |
function nextFn () { | |
// prevent infinite range | |
if ((toV - fromV) * step < 0) { | |
setStatusDone() | |
} | |
else { | |
nextFn = () => { | |
if (!status.done) { | |
status.value += step | |
if (status.value >= toV) { | |
setStatusDone() | |
} | |
} | |
return status | |
} | |
} | |
return nextFn() | |
} | |
return new Proxy( | |
// nothing in the instance of generator | |
{}, | |
{ | |
get (target, key, receiver) { | |
if (key === 'next') { | |
return nextFn | |
} | |
return target[key] | |
} | |
} | |
) | |
} | |
// examples | |
const g = fakeGen(1, 4) | |
g.next() // { done: false, value: 1 } | |
g.next() // { done: false, value: 2 } | |
g.next() // { done: false, value: 3 } | |
g.next() // { done: true, value: undefined } | |
//--------------- | |
const g = fakeGen(3) | |
g.next() // { done: false, value: 0 } | |
g.next() // { done: false, value: 1 } | |
g.next() // { done: false, value: 2 } | |
g.next() // { done: true, value: undefined } | |
//--------------- | |
const g = fakeGen(1, 10, 3) | |
g.next() // { done: false, value: 1 } | |
g.next() // { done: false, value: 4 } | |
g.next() // { done: false, value: 7 } | |
g.next() // { done: true, value: undefined } | |
//--------------- | |
const g = fakeGen(1, 10, -1) // infinite gen wont work | |
g.next() // { done: true, value: undefined } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment