Last active
March 20, 2022 19:41
-
-
Save joshuakfarrar/a26ee3f6c185d77f6eb040bd812b084f to your computer and use it in GitHub Desktop.
purely functional carousel for JavaScript Arrays
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
// is this possible with a purely-functional doubly-linked list in JavaScript? | |
function carousel(items) { | |
return { | |
_fastForward: function(n) { | |
if (n === 0) return carousel(items) | |
else return carousel([].concat(items.slice(1), items[0]))._fastForward(n - 1) | |
}, | |
_rewind: function (n) { | |
if (n === 0) return carousel(items); | |
else return carousel([].concat(items[items.length - 1], items.slice(0, items.length - 1)))._rewind(n - 1); | |
}, | |
previous: function (n) { | |
return function (results) { | |
if (n === 0) return [results.reverse(), Object.assign({}, carousel(items), { | |
next: function(n) { | |
return carousel(items)._fastForward(n).next(n) | |
} | |
})]; | |
else return carousel(items)._rewind(1).previous(n - 1)([].concat(results, items[items.length - 1])); | |
}; | |
}, | |
next: function (n) { | |
return function (results) { | |
if (n === 0) return [results, Object.assign({}, carousel(items), { | |
previous: function(n) { | |
return carousel(items)._rewind(n).previous(n) | |
} | |
})] | |
else return carousel(items)._fastForward(1).next(n - 1)([].concat(results, items[0])); | |
}; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment