Created
October 30, 2019 18:51
-
-
Save gemmadlou/c2d4e3b7f85c62ffff9bd55d80e9108b to your computer and use it in GitHub Desktop.
Slider Use Case
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
let baseState | |
= ({ | |
page = 1, | |
totalPages = 1, | |
canGoNext = false, | |
canGoPrev = false, | |
position = 0, | |
direction = null | |
} = {}) => ({ | |
page, | |
totalPages, | |
canGoNext, | |
canGoPrev, | |
position, | |
direction | |
}) | |
const getPosition | |
= (totalPages, page) => totalPages === 1 ? 0 : ((1 / totalPages) * (page - 1)) | |
const isLastPage | |
= (totalPages, page) => page === totalPages | |
const isFirstPage | |
= (page) => page === 1 | |
const decreasePage | |
= (page) => page - 1 | |
const increasePage | |
= (page) => page + 1 | |
const getNewPage | |
= (totalPages, currentPage, direction) => direction === 'next' | |
? isLastPage(totalPages, currentPage) ? currentPage : increasePage(currentPage) | |
: isFirstPage(currentPage) ? currentPage : decreasePage(currentPage) | |
const Compute | |
= (state = baseState()) => { | |
let newPage = state.direction === 'next' || state.direction === 'prev' | |
? getNewPage(state.totalPages, state.page, state.direction) | |
: state.page | |
return { | |
...state, | |
page: newPage, | |
position: getPosition(state.totalPages, newPage), | |
canGoNext: !isLastPage(state.totalPages, state.page), | |
canGoPrev: !isFirstPage(state.page) | |
} | |
} | |
const Actions | |
= (state = baseState()) => ({ | |
init: (newState = baseState()) => Actions(Compute({ | |
...state, | |
...newState | |
})), | |
next: () => Actions(Compute({ | |
...state, | |
direction: 'next' | |
})), | |
prev: () => Actions(Compute({ | |
...state, | |
direction: 'prev' | |
})), | |
get: () => ({ | |
...state | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment