やってみた: 10分チャレンジ
やってみた: 10分チャレンジ:
やってみた: 10分でできないとつらいらしいやつ
出力部以外のHTMLはVSCodeに事前に準備(すでにあった)
やってみた: 10分でできないとつらいらしいやつ
準備
出力部以外のHTMLはVSCodeに事前に準備(すでにあった)
実施
- 課題の関数: 3分
- パターン: 0.5分
- コメント: 1.5分
- jsfiddleへ移動(したがVSCodeに戻した): 2分
- console.logからテキストエリア(HTML)への出力に変更: 3分
コード
function distribute(count, charsOfCard) {
const cardCount = charsOfCard.length - charsOfCard.length % count
// ---> 均等分配の余りを無視したカード枚数
const cards = charsOfCard.split('').slice(0, cardCount)
// ---> 余りは無視します
const result = Array(count).fill(0).map(_ => [])
// ---> 分配結果を格納する配列を用意します
cards.forEach((x, i) => {
result[i % count].push(x)
});
// ---> 分配します
return result
}
const output = document.getElementById('output')
const count = 3
const cardsPatterns = [
'12',
'123456',
'1234567890',
]
cardsPatterns.forEach(x => {
const result = distribute(count, x)
let s = `cardsPattern: ${x}\n`
result.forEach(y => s += `[${y.join()}]\n`)
output.textContent += s
})
振り返り
- 標準ビルトインオブジェクトのメソッドの恩恵を感じた(
String.prototype.split()など) - 高階関数の恩恵を感じた(
map()、forEach()など) - 終始VSCodeでよかった
- ローカル変数の命名が微妙
- コメントをわざと下付きにしたもののやはり微妙
- 出力先は最初からテキストエリア決めていてよかった
- なんとなくのテストケースまでは実装できた
- ちゃんとしたテストケースを実施するには至らず知識・経験不足
- 異常系が実装できていなかった
振り返った後のコード
- 引数チェックを入れた
- コメントを直した
- ローカル変数名を変更した
- テストケースに異常系を入れた(countは面倒なのでさぼった)
- 異常系のハンドリングまでやった
function distribute(count, charsOfCard) {
if (!(count > 0)) throw Error(`分配人数に1以上でない値が指定されました{count: ${count}}`)
if (!(typeof charsOfCard == 'string')) throw Error(`カード文字列に文字以外の値が指定されました{'typeof charsOfCard': ${typeof charsOfCard}}`)
// 均等分配の余りを無視しただけカードを生成します
const cardCount = charsOfCard.length - charsOfCard.length % count
const cards = charsOfCard.split('').slice(0, cardCount)
// 分配します
const hands = Array(count).fill(0).map(_ => [])
cards.forEach((x, i) => {
hands[i % count].push(x)
});
return hands
}
const output = document.getElementById('output')
const count = 3
const cardsPatterns = [
// 正常系
'', // カードなし
'12', // 分配無し
'123456', // 余りなし
'1234567890', // 余りあり
// 異常系
null,
123,
]
cardsPatterns.forEach(x => {
let s = `cardsPattern: ${x}\n`
let hands = null
try {
hands = distribute(count, x)
hands.forEach(y => { s += `[${y.join()}]\n` })
} catch (ex) {
s += `${ex}\n`
}
output.textContent += s
})
総括
- 問題に少しいまいちな点があった(引数が文字列なのはどうなの…)
- 簡単な問題はチョロッと書いて「ハイ終わり!」となりがち
- ちょっとした問題だからこそちゃんと実装する価値がありそう(目的にもよるが)
- 繰り返しになるが、ちょっとしたもので実験する癖は持っておきたい
コメント
コメントを投稿