The code below works but I am wondering if there is a better way that maybe uses some of the features of coffeescript that I am unfamiliar with.
The problem is this, I need to page items but the paging increases each time.
If I take the number 20 for example, it would create the following pages:
1 – 3
4 – 7
8 – 15
16 – 20
I have the following test and code which does pass:
module 'Remainder',
setup: ->
@remainder = 20
test 'splits remainder incrementally', ->
parts = @remainder.increasingSplit()
equal parts[0], '1 - 3', ''
equal parts[1], '4 - 7', ''
equal parts[2], '8 - 15', ''
equal parts[3], '16 - 20', ''
Number.prototype.increasingSplit = ->
start = 1
nextSplit = 3
parts = []
finished = false
while !finished
if nextSplit > @
parts.push "#{start} - #{@}"
break
parts.push "#{start} - #{nextSplit}"
start = nextSplit + 1
nextSplit = nextSplit * 2 + 1
parts
Without changing the algorithm too much, you can try this:
The changes were:
.prototypewith::,finishedvariable (which was not being used effectively because thebreakanyway) and thebreakaltogether and changing the condition tostart <= @,parts.push <part>, with the minimum betweennextSplitand@as the top.Also, i’d advice against extending the Number prototype in this case. Extending the prototype of primitive types can sometimes cause weird problems, like:
That happens because inside that function
@will be a Number object instead of a primitive number, thus making the=== 4comparison always fail. That would not happen if you defineisFouras a standalone function:So, i’d prefer this version of
incrasingSplit:Finally, if you don’t mind recursion, you can go with a more FP-style algorithm 🙂