1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

制約付きのfizzbuzz(javascript)

Last updated at Posted at 2025-03-19

最近以下の2つの記事を読みました。
参考サイト1
参考サイト2

自分はあまり制約をつけたプログラミングをやらないので新鮮でした
参考サイト2を読んだときにふと思いついたことがあります。
それは参考サイト1、参考サイト2の制約を両方同時に満たすプログラムをかけるのではないかということです。
そこで両方のサイトに書かれているプログラムを参考に自分なりに両方の制約を満たすプログラムを書いてみました。
もしも制約違反を見つけたら教えてください。

function s(cond, whenTrue, whenFalse) {
  return { true: whenTrue, false: whenFalse }[cond];
}
function mod(i,x) {
  with(Number(i)) {
    with(toString(x)) {
      return s(Boolean(parseInt(at(indexOf()), x)),false,true);
    }
  }
}
function genarate(n){
  with(Array){
    with(from(Array(n))){
      with(map((d,i)=>i)){
        push(length)
        return slice(1,length);
      }
    }
  }
}
function FizzBuzz(n,
  patterns = [{ pred: (v)=>mod(v,3), str: "Fizz" },
              { pred: (v)=>mod(v,5), str: "Buzz" }]
) {
  with(Array){
    with(genarate(n)){
      return reduce((a,c)=>{
        with(patterns){
          with(`${a}${"\n"}${s(
            some(({pred,str})=>pred(c)),
            reduce((a,{pred,str})=>`${a}${s(pred(c),str,"")}`,""),
            c
          )}`){
            return slice(1,length);
          }
        }
      },"")
    }
  }
}
with(console) {
  log(FizzBuzz(100));
}

反応次第でさらに制約を追加してみようと考えています。
今頭で考えているのは文字列、数字禁止の追加です。ちょっとずるい方法ですがすでに方針は決まっています。
追記(2025/3/20)
@mikecat_mixcさんがコメントで制約違反を指摘してくれました。修正を行いました。ありがとうございました。また、制約の回避用の関数が多かったので仕組みを見直して使わないようにしました。

1
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?