May 09, 2021 CoffeeScript
There are several ways to solve a problem, but you need to choose (or convert) these methods while the program is running.
Encapsulate your algorithm in a policy object.
For example, given an unordered list, we can change the sorting algorithm in different situations.
StringSorter = (algorithm) ->
sort: (list) -> algorithm list
bubbleSort = (list) ->
anySwaps = false
swapPass = ->
for r in [0..list.length-2]
if list[r] > list[r+1]
anySwaps = true
[list[r], list[r+1]] = [list[r+1], list[r]]
swapPass()
while anySwaps
anySwaps = false
swapPass()
list
reverseBubbleSort = (list) ->
anySwaps = false
swapPass = ->
for r in [list.length-1..1]
if list[r] < list[r-1]
anySwaps = true
[list[r], list[r-1]] = [list[r-1], list[r]]
swapPass()
while anySwaps
anySwaps = false
swapPass()
list
sorter = new StringSorter bubbleSort
unsortedList = ['e', 'b', 'd', 'c', 'x', 'a']
sorter.sort unsortedList
# => ['a', 'b', 'c', 'd', 'e', 'x']
unsortedList.push 'w'
# => ['a', 'b', 'c', 'd', 'e', 'x', 'w']
sorter.algorithm = reverseBubbleSort
sorter.sort unsortedList
# => ['a', 'b', 'c', 'd', 'e', 'w', 'x']
"No combat plan survives the first contact with an enemy." U sers do, but we can use the knowledge gained from changing circumstances to make adaptation changes. At the end of the example, for example, the latest items in the array are out of order, and knowing this detail, we can speed up the sorting by switching algorithms, as long as we simply re-assign them.