Created
April 21, 2015 10:54
-
-
Save pushandplay/d73e7da2f47e86f24f5a to your computer and use it in GitHub Desktop.
adapter-pattern
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
# a fragment of 3-rd party grid component | |
class AwesomeGrid | |
constructor: (@datasource)-> | |
@sort_order = 'ASC' | |
@sorter = new NullSorter # in this place we use NullObject pattern (another useful pattern) | |
setCustomSorter: (@customSorter) -> | |
@sorter = customSorter | |
sort: () -> | |
@datasource = @sorter.sort @datasource, @sort_order | |
# don't forget to change sort order | |
class NullSorter | |
sort: (data, order) -> # do nothing; it is just a stub | |
class RandomSorter | |
sort: (data)-> | |
for i in [data.length - 1..1] #let's shuffle the data a bit | |
j = Math.floor Math.random() * (i + 1) | |
[data[i], data[j]] = [data[j], data[i]] | |
return data | |
class RandomSorterAdapter | |
constructor: (@sorter) -> | |
sort: (data, order) -> | |
@sorter.sort data | |
agrid = new AwesomeGrid ['a', 'b', 'c', 'd', 'e', 'f'] | |
agrid.setCustomSorter new RandomSorterAdapter(new RandomSorter) | |
agrid.sort() # sort data with custom sorter through adapter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment