下面的代码可以工作,但我想知道是否有更好的方式,也许使用一些我不熟悉的coffeescript的功能。
问题是,我需要对项目进行分页,但分页次数每次都会增加。
如果我以数字20为例,它将创建以下页面:
1-3 4-7 8- 15 16 - 20
我有以下测试和代码可以通过:
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发布于 2012-10-28 07:42:11
在不过多更改算法的情况下,您可以尝试这样做:
Number::increasingSplit = ->
start = 1
nextSplit = 3
parts = []
while start <= @
parts.push "#{start} - #{Math.min nextSplit, @}"
start = nextSplit + 1
nextSplit = nextSplit * 2 + 1
parts这些变化是:
.prototype替换为::,finished变量(因为break无论如何都没有得到有效使用)和break,并将条件更改为仅使用一个D13、、
另外,我建议不要在这种情况下扩展Number原型。扩展原语类型的原型有时会导致奇怪的问题,例如:
Number::isFour = -> @ is 4
console.log 4.isFour() # -> false这是因为在函数@内部将是一个Number对象,而不是一个原始number,从而使=== 4比较总是失败。如果将isFour定义为独立函数,则不会发生这种情况:
isFour = (n) -> n is 4
console.log isFour 4 # -> true所以,我更喜欢这个版本的incrasingSplit
increasingSplit = (n) ->
start = 1
nextSplit = 3
parts = []
while start <= n
parts.push "#{start} - #{Math.min nextSplit, n}"
start = nextSplit + 1
nextSplit = nextSplit * 2 + 1
parts最后,如果您不介意递归,您可以使用更具FP风格的算法:)
increasingSplit = (n, start = 1, nextSplit = 3) ->
if start > n
[]
else
part = "#{start} - #{Math.min nextSplit, n}"
rest = increasingSplit n, nextSplit + 1, nextSplit * 2 + 1
[part, rest...]https://stackoverflow.com/questions/13104221
复制相似问题