【JavaScript】その他

# 配列をシャッフルする

Fisher-Yates法というそうです
配列(Array)を拡張

__関数__

```js
Array.prototype.shuffle = function() {
    var tmp;
    for(var i = this.length -1;i>0;i--){
        var r = Math.floor(Math.random()*(i+1));
        tmp = this[i];
        this[i] = this[r];
        this[r] = tmp;
    }
    return this;
};
```

__使用方法__

```js
var a = [1,2,3,4,5,6,7,8,9];
console.log( a.shuffle() );
```

__関連リンク__

[Fisher-Yates法](https://ja.wikipedia.org/wiki/%E3%83%95%E3%82%A3%E3%83%83%E3%82%B7%E3%83%A3%E3%83%BC_-_%E3%82%A4%E3%82%A7%E3%83%BC%E3%83%84%E3%81%AE%E3%82%B7%E3%83%A3%E3%83%83%E3%83%95%E3%83%AB)

---

# 日付を取得する

__概要__

日付を取得する

__スクリプト__

```js
function hirgetDate(){//日付取得
    var stoday = new Date();
    var syear = stoday.getFullYear();
    var smonth = stoday.getMonth()+1;

    return {
        year: syear ,
        month:smonth ,
        date:stoday.getDate() ,
        hours:stoday.getHours(),
        minutes:stoday.getMinutes(),
        seconds:stoday.getSeconds()
    }
}
```

---

# スクロール禁止＆復活

__概要__

スクロール禁止＆復活

__施策__

__スクロール禁止用関数__

``` js
//スクロール禁止用関数
function no_scroll(){
    //PC用
    var scroll_event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
    $(document).on(scroll_event,function(e){
        e.preventDefault();
    });
    //SP用
    $(document).on('touchmove.noScroll', function(e) {
        e.preventDefault();
    });
}
```

__スクロール復活用関数__

``` js
//スクロール復活用関数
function return_scroll(){
    //PC用
    var scroll_event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
    $(document).off(scroll_event);
    //SP用
    $(document).off('.noScroll');
}
```     

---

# ダウンロードイベント

__スクリプト__

```js
(function(){

    Element.prototype.downLoadEventListener = function(o){
        var method,action,serial;

        if(o.method){
            method = o.method;
        }else{
            method = 'GET';
        }

        if(o.data){
            serial = o.data;
        }else{
            serial = '';
        }
        if(o.url){
            action = o.url;
        }

        if(method==='POST'){
            var obj = {};
            var serAry = serial.split('&');
            for(var prop in serAry){
                var sr = serAry[prop];
                var sAry = sr.split('=');
                obj[sAry[0]] = sAry[1].replace(/%2F/g,'/');
            }
            serial = obj;
        }

        this.req = $.ajax({
            cache: false,
            type: method,
            url: action,
            data: serial,
            xhrFields: {
                responseType: 'blob'
            },
            xhr:function(){
                var xhr = $.ajaxSettings.xhr();
                xhr.addEventListener("progress",this.progress);
                return xhr;
            },
            progress:function(ev){
                if(o.progress){
                    o.progress(ev);
                }
            },
            success: function (response, status, xhr) {
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');

                if (disposition) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                }else{
                    var actAry = action.split('/');
                    filename = actAry[actAry.length-1];
                }

                try {
                    var blob = new Blob([response], { type: 'application/octet-stream' });

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        window.navigator.msSaveBlob(blob, filename);
                    } else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);
                        if (filename) {

                            var ua = window.navigator.userAgent.toLowerCase();

                            var a = document.createElement("a");

                            if (ua.indexOf('safari') !== -1 && ua.indexOf('chrome')===-1){
                                function saveAs(uri, filename) {
                                    var link = document.createElement('a');
                                    if (typeof link.download === 'string') {
                                        link.href = uri;
                                        link.download = filename;
                                        document.body.appendChild(link);
                                        link.click();
                                        document.body.removeChild(link);
                                    } else {
                                        window.location = uri;
                                    }
                                }

                                var reader = new FileReader();

                                reader.onloadend = function() {
                                    var base64data = reader.result;
                                    saveAs(base64data, filename);
                                };
                                reader.readAsDataURL(blob);
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.target = "_blank";
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
                    }

                } catch (ex) {
                    console.log(ex);
                }

                if(o.success){
                    o.success();
                }
            },
            error: function () {
                if(o.error){
                    o.error();
                }
            }
        });

        this.abort = function(){
            this.req.abort();
        };

        return this;
    };///


})();

```

__使用方法__

```js
$(function(){

    $('a').on('click',function(){
        try{
            var de = this.downLoadEventListener({
                method:'POST',
                url :'test.jpg',
                data :'a=1&b=2',
                success:function(){
                    console.log('success');
                },
                progress:function(ev){
                    console.log(ev);
                }
            });

        }catch (e){
            console.log(e);
        }
        return false;
    });
});
```

---

# スムーズスクロール

__施策__

``` js
(function() {
    ////////////////
    function IlrSmoothScroll(){
        this.init();
    }
    IlrSmoothScroll.prototype = {
        w : window,
        arvPos : 0,
        pos : 0,
        speed : 5,
        lastTime : 0,
        vendors : ['ms', 'moz', 'webkit', 'o'],
        wheel : 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll',
        init : function(){

            var _me = this;
            _me.isTouch = ('ontouchstart' in window);
            _me.isPointer = ('onpointerenter' in window);

            if(_me.isTouch){
            }else{
                _me.set();
                _me.ready(function(){
                    _me.on(_me.w, _me.wheel + '.wheel' , function(e){
                        _me.onWheel(e);
                    });

                    _me.on(_me.w, 'scroll.pageScroll' , function () {
                        _me.arvPos = _me.w.pageYOffset;
                    });
                });
                _me.on(_me.w, 'load.pageScroll' , function () {
                    setTimeout(function(){
                        _me.pos = _me.arvPos = _me.w.pageYOffset;
                        _me.interval();
                    },50);
                });
            }
        },
        set : function(){
            var _me = this;

            for(var x = 0; x < _me.vendors.length && !_me.requestAnimationFrame; ++x) {
                _me.requestAnimationFrame = _me.w[_me.vendors[x]+'RequestAnimationFrame'];
                _me.cancelAnimationFrame = _me.w[_me.vendors[x]+'CancelAnimationFrame']
                    || _me.w[_me.vendors[x]+'CancelRequestAnimationFrame'];
            }

            if (!_me.requestAnimationFrame){
                _me.requestAnimationFrame = function(callback) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16 - (currTime - _me.lastTime));
                    var id = _me.w.setTimeout(function() { callback(currTime + timeToCall); },
                        timeToCall);
                    _me.lastTime = currTime + timeToCall;
                    return id;
                };
            }

            if (!_me.cancelAnimationFrame){
                _me.cancelAnimationFrame = function(id) {
                    clearTimeout(id);
                };
            }
        },
        ready : function(eventHandler){
            if (document.readyState === 'complete' || document.readyState !== 'loading') {
                eventHandler();
            } else {
                document.addEventListener('DOMContentLoaded', eventHandler);
            }
        },
        on:function(elem , event, cb, opts){
            if( !elem.namespaces ) // save the namespaces on the DOM element itself
                elem.namespaces = {};

            elem.namespaces[event] = cb;
            var options = opts || false;

            elem.addEventListener(event.split('.')[0], cb, options);
        },
        off:function(elem , event) {
            elem.removeEventListener(event.split('.')[0], elem.namespaces[event]);
            delete elem.namespaces[event];
        },
        onWheel:function(e) {
            var _me = this;
            if(!e) e = _me.w.event; //for legacy IE

            e.preventDefault();

            var delta = e.deltaY ? -(e.deltaY) : e.wheelDelta ? e.wheelDelta : -(e.detail);

            _me.pos = _me.pos - delta;

            var bdy = document.querySelector('body');

            if(_me.pos<0){
                _me.pos = 0;
            }else if(_me.pos > bdy.offsetHeight - _me.w.innerHeight ){
                _me.pos = bdy.offsetHeight - _me.w.innerHeight;
            }
        },
        interval : function() {
            var _me = this;
            requestAnimationFrame(function(){
                _me.interval();
            });
            _me.arvPos += (_me.pos - _me.arvPos)/_me.speed;
            _me.w.scroll(0, _me.arvPos);
        },
        scrollTop:function(n){
            var _me = this;
            _me.pos = n;
        },
        noConflict:function(){
            return this;
        }
    };

    ////////////////
    window.ilrSmoothScroll = new IlrSmoothScroll();

})();
```

---

# IEでconsole.logエラーを出さないようにする

``` js
if (!('console' in window)) {
     window.console = {};
     window.console.log = function(str){
        return str;
     };
}
```

---

# 画像読み込み時のプログレス取得

__概要__

画像読み込み時のプログレス取得

__スクリプト__

``` js
Image.prototype.onChangeSize;
Image.prototype.load = function(url){
  var _this = this;
  var req   = ((XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
  req.open('GET', url, true);
  req.responseType = 'arraybuffer';
  req.onload = function(e) {
    if(req.response) {
      var blob = new Blob([req.response]);
      _this.src = window.URL.createObjectURL(blob);
    }
  };
  req.onprogress = function(e) {
    if(_this.onChangeSize) {
      _this.onChangeSize(e.loaded, e.total);
    }
  };
  req.send();
};
```

__使用方法__

``` js
var getLoadingPercentage = function (imgUrl){
  var img = new Image();
  img.onChangeSize = function(loaded, total) {
    var loadingPercentage = parseInt((loaded / total) * 100);
  };
  img.onload = function() {
    //読み込み完了
  };
  img.onerror = function(){
    //エラー
  };
  img.load(imgUrl);
};

getLoadingPercentage(画像パス);

```

---

# グーグルカスタム検索　オートコンプリート編集

__概要__

グーグルカスタム検索のオートコンプリート編集をCSVで管理してXMLで書き出す

__CSV__

```
term,type,score,language
図書館,1,10,
```

__スクリプト__

XMLへの変換はgulpで行います。

```js
////////////////////////////////
const gulp = require("gulp");
const fs = require('fs');
const iconv = require('iconv-lite');
const Converter = require("csvtojson").Converter;
const jsonxml = require('jsontoxml');
////////////////////////////////

const converter = new Converter({});

gulp.task('customsearch', function(){

    converter.on("end_parsed", function (jsonArray) {
        comp(jsonArray);
    });

    fs.createReadStream("custom-search/cse.csv")
        .pipe(iconv.decodeStream('SJIS'))
        .pipe(iconv.encodeStream('UTF-8'))
        .pipe(converter);

    function comp(json){

        var ary = [];
        for(var prop in json){
            var obj = {
                name:'Autocompletion',
                attrs:json[prop]
            };
            ary.push(obj);
        }

        var jsn = {
            Autocompletions:ary
        };

        var xml = jsonxml(jsn,{ xmlHeader:true });
        fs.writeFile('custom-search/cse.xml', xml, function(err) {
            if (err) throw err;
            console.log('file saved');
        });
    }

});
```

__実行__

ターミナルから実行

```js
gulp customsearch
```

__XML__

```
<?xml version="1.0" encoding="utf-8"?>
<Autocompletions>
<Autocompletion term="図書館" type="1" score="8" language=""/>
</Autocompletions>
```