文字列の(セパレータを挟んだ)繰り返し

文字列繰り返し - Higé au lait
敢えて再帰でという趣向かな。でも空気読まずに普通に書く。

String.prototype.repeat = function(n, sep, a){
  (a = [this]).length = n;
  return a.join((sep || '') + this);
};

既に模範解答があるので少し奇を衒ってみた。

['hoge'] * 3 * '|' # => "hoge|hoge|hoge"

メソッドを定義するまでも無いのだった。流石。

!SequenceableCollection methodsFor: 'repeating'!
repeat: n
  ^self species streamContents: [:s| n timesRepeat: [ s nextPutAll: self ] ]!
repeat: n with: sep
  ^self species streamContents: [:s|
    (1 to: n) do: [:x| s nextPutAll: self ] separatedBy: [ s nextPutAll: sep ] ]!

#species と #do:separatedBy: の使い方が判明。

String::repeat: method(n, sep: ""){
  return n < 1 ? "" : [this].cycle.take(n).join(sep);
}

無限イテレータを介するのがイディオムらしい。