patternjavascriptModerate
Coffeescript beautification and refactoring
Viewed 0 times
coffeescriptandbeautificationrefactoring
Problem
As much as I try, I cannot seem to get this Coffeescript code to look beautiful (I'd like to think it is possible). I have tried both Javascript and Coffeescript. Just to be clear, this code works fine, but it is hard to read, for reasons that I am unable to pinpoint.
How can it be refactored, reorganized, and what changes to coding style can be made to make it more appealing to read?
``
# typed).
updateLineNumbers: (change = 0) ->
$gutter = this.gutter()
count = this.lines().children("li").length
current = $gutter.children("span").length
count += change
# Add lines
if (count > current)
for i in [current..(count - 1)]
How can it be refactored, reorganized, and what changes to coding style can be made to make it more appealing to read?
``
define [
"plugins/ui/ui",
"./js/highlight"
], (ui, highlight) ->
editor = {}
jQuery ($) ->
# A widget to view source code.
$.widget 'core.editor',
_create: ->
$editor = $(this.element)
$editor
.addClass('editor')
.append($(' '))
# Move the gutter along with the editable area.
this.lines().bind 'scroll', (event) ->
$this = $(this)
$this.siblings(".gutter").css(top: $this.scrollTop() * -1)
# Highlight the sourceview using the given language.
# The language's JSON rule file is loaded.
highlight: (language) ->
this.language = language
require ["text!plugins/editor/js/#{ language }.json"], (json) =>
this._rules = JSON.parse(json)
return
# Update the left of the based on the gutter width.
# Each time the number of digits in the gutter changes, it becomes wider or
# narrower, and the editor needs the shift accordingly.
updateGutterWidth: () ->
# The 8 is the gutter's left padding.
this.lines().css(left: this.gutter().width() + 8)
# Add or remove line numbers if the number of lines has changed.
# change` is a modification the the line count (In case the character was not yet# typed).
updateLineNumbers: (change = 0) ->
$gutter = this.gutter()
count = this.lines().children("li").length
current = $gutter.children("span").length
count += change
# Add lines
if (count > current)
for i in [current..(count - 1)]
Solution
One more thing. I almost always rewrite my own version of setTimeout and setInterval when using CoffeeScript, so I can use a cleaner syntax when callbacks are the last argument.
after = (ms, cb) -> setTimeout cb, ms
every = (ms, cb) -> setInterval cb, ms
// that way, instead of this
setTimeout(() ->
doSomething()
doMore()
), 100)
// you can use this
after 100, () ->
doSomething()
doMore()
Context
StackExchange Code Review Q#1462, answer score: 12
Revisions (0)
No revisions yet.