Skip to content

Commit

Permalink
lodashを使うなどによりリファクタ
Browse files Browse the repository at this point in the history
  • Loading branch information
jun68ykt committed Jul 16, 2019
1 parent c1a6133 commit f1a798a
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions index.html
Expand Up @@ -4,32 +4,35 @@
<meta charset="UTF-8">
<title>Q200759</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.min.js"></script>
<script>
$(function() {
$('.button').hide();

$('input[name="check"]').change(function() {
$('.button').hide();
if ($('input[name="check"]:checked').length >= 3) {
var _tmp = [];
$('input[name="check"]:checked').each(function() {
_tmp.push($(this).parents('li').attr('class').split(' '));
});

_tmp = Array.prototype.concat.apply([], _tmp);
// チェックされているボックスを取得します。
const checkedBoxes = $('input[name="check"]:checked');

var data={};
for(var i=0;i<_tmp.length;i++){
var key=_tmp[i];
if(data[key]==undefined) data[key]=0;
data[key]++;
}
if (checkedBoxes.length >= 3) {

var showClasses = Object.entries(data).filter(([_, value]) => value >= 3).map(e => e[0]);
// _tmpは、こんな風にも作れます。
const _tmp = checkedBoxes.toArray().reduce((ary, e) =>
[...ary, ...e.parentNode.classList], [])

// _tmp に出現する異なる要素をプロパティとし、各々の個数を値とするオブジェクトは以下で得られます。
const counts = _.countBy(_tmp);

// counts の中で個数が3以上のものだけをピックアップしたオブジェクトは以下で得られます。
const countsGte3 = _.pickBy(counts, v => v >= 3);

// show()を適用するボタンのセレクタを作成します。
const buttonsSelectorToShow = Object.keys(countsGte3).map(x => `.button.${x}`).join(',');

// 上記のセレクタを使って、show()を適用します。
$(buttonsSelectorToShow).show()

showClasses.forEach(clazz => {
$(`.button.${clazz}`).show();
});
};
});
});
Expand Down

0 comments on commit f1a798a

Please sign in to comment.