问题你想要匹配两个或多个字符串。解决方案计算把一个字符串转换成另一个字符串所需的编辑距离或操作数。levenshtein = (str1, str2) -> l1 = str1.length l2 = str2.length prevDist = [0..l2] nextDist = [0..l2] for i in [1..l1] by 1 nextDist[0] = i for j in [1..l2] by 1 if (str1.charAt i-1) == (str2.
问题你想创建一个字符串,让它包含体现某个 CoffeeScript 变量的文本。解决方案使用 CoffeeScript 中类似 Ruby 的字符串插值,而不是 JavaScript 的字符串拼接。插值:muppet = "Beeker"favorite = "My favorite muppet is #{muppet}!"# => "My favorite muppet is Beeker!"square = (x) -> x * xmessage = "The square of 7 is #{square 7}."# =>
问题你想在一条消息中查找某个关键字第一次或最后一次出现的位置。解决方案分别使用 JavaScript 的 indexOf() 和 lastIndexOf() 方法查找字符串第一次和最后一次出现的位置。语法: string.indexOf searchstring, startmessage = "This is a test string. This has a repeat or two. This might even have a third."message.indexOf "This", 0# =>
问题你有一些通用方法,你想把他们包含到很多不同的类中。解决方案使用 mixOf 库函数,它会生成一个混合父类。mixOf = (base, mixins...) -> class Mixed extends base for mixin in mixins by -1 #earlier mixins override later ones for name, method of mixin:: Mixed::[name] = method Mixed...class DeepThought answer: ->
问题你想复制一个对象,包含其所有子对象。解决方案clone = (obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline?
问题你想创建类变量和实例变量(属性)。解决方案类变量class Zoo @MAX_ANIMALS: 50 MAX_ZOOKEEPERS: 3 helpfulInfo: => "Zoos may contain a maximum of #{@constructor.MAX_ANIMALS} animals and #{@MAX_ZOOKEEPERS} zoo keepers."Zoo.MAX_ANIMALS# => 50Zoo.MAX_ZOOKEEPERS# =>
问题你想创建类和实例的方法。解决方案类方法class Songs @_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property. @get_count: -> @_titles constructor: (@artist, @title) -> @constructor._titles++ # Refers to <Classname>._titles, in this case Songs.titlesSongs.