Drkcore

26 02 2012 Ruby coffeescript Node.js Tweet

RubyのgsubをCoffeeScriptで

Rubyのgsubはblockを受け取ってマッチするたびにブロック内の処理内容を変えられるので便利。

irb(main):002:0> i = 0
=> 0
irb(main):003:0> 'a-a-a-a'.gsub(/a/){i += 1}
=> "1-2-3-4"

Node.jsでも同じようなことがやりたかったのでRuby's String gsub in Javascriptをちょっと変更して配列を受け取れるようにしてみた。

gsub = (source, pattern, replacements) ->
  unless pattern? and replacements?
    return source

  result = ''
  while source.length > 0
    if (match = source.match(pattern))
      result += source.slice(0, match.index)
      result += replacements.shift()
      source = source.slice(match.index + match[0].length)
    else
      result += source
      source = ''
   result

console.log gsub('a-a-a-a', /a/, [1..4])

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021