ネイティブJSの拡張と実装
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
(global = global || self, global._ = factory());
}(this, function () {
//ツール・オブジェクト
const _ = {
// _自分自身を返すときにオブジェクト名を出す
noConflict() {
window._ = null
return this
},
/**
* 拡張メソッド
*/
extend(source, target) {
target = target || this
for (const key in source) {
if (!target[key]) target[key] = source[key]
}
}
}
//
_.extend({
eq(a, b) {
return a === b
},
//次のようなランダムな色を生成する#a2dd05
getRndColor() {
let colorStr = "#";
let str = "ABCDEF123456789";
for (let i = 0; i < 6; i++) {
colorStr += str[Math.floor(Math.random() * str.length)];
}
return colorStr;
},
loadingbar: {
config: {
color: "blue"
},
start() {
var loadingbar = document.getElementById("loadingbar")
if (!loadingbar) {
loadingbar = document.createElement("div")
loadingbar.setAttribute("id", 'loadingbar')
loadingbar.style.backgroundColor = this.config.color
document.body.appendChild(loadingbar)
}
loadingbar.style.display = "block"
},
finish() {
var loadingbar = document.getElementById("loadingbar")
if (loadingbar) loadingbar.style.display = "none"
}
},
formatMs2Obj(total) {
var h = _.repairZero(Math.floor(total / 3600))
var m = _.repairZero(Math.floor((total - h * 3600) / 60))
var s = _.repairZero(Math.floor(total - h * 3600 - m * 60))
return {
h,
m,
s
}
},
convertMysqlTime2JSTime(val) {
return new Date(new Date(val).toISOString().replace("T", ' ').split('.')[0])
},
getQueryParams() {
if (!location.search) return null
var query = location.search.replace("?", '')
return this.convertStr2Obj(query, '&')
},
convertStr2Obj(str, splitCode) {
var obj = {}
if (!str) return obj
var queryarr = str.split(splitCode)
queryarr.forEach(r => {
var temparr = r.split('=')
obj[temparr[0]] = temparr[1]
})
return obj
},
convertObj2Str(params) {
if (!params) return ''
return Object.keys(params).map(key => {
return key + "=" + params[key]
}).join('&')
},
log() {
//配列を特定の文字を含む文字列に変換する
console.log(Array.prototype.join.call(arguments, ' '))
},
/**
*
*/
repairZero(num) {
return num < 10 ? ("0" + num) : num
},
/**
* 文字列のマージ
*/
makeStr(...args) {
return args.join('')
},
/**
* スクリプトを読み込む
*/
loadScript(url, callback) {
const head = document.getElementsByTagName("head")[0]
var script = document.createElement("script")
script.src = this.makeStr(url, "?", this.random())
script.charset = "utf-8"
script.async = true
if (callback) script.onload = callback
head.appendChild(script)
},
isArray(obj) {
if (Array.isArray) return Array.isArray(obj)
return this.toString(obj) === '[object Array]'
},
isFuction(obj) {
return this.toString(obj) === '[object Function]'
},
toString(obj) {
return Object.prototype.toString.call(obj)
},
// 画面外を防ぐために最終位置を取得する
calcPostion(left, top, maxLeft, maxTop, minLeft = 0, minTop = 0) {
if (left < minLeft) left = minLeft
else if (left > maxLeft) left = maxLeft
if (top < minTop) top = minTop
else if (top > maxTop) top = maxTop
return {
left,
top
}
}
})
/**
* 機能関連の拡張
*/
_.extend({
//ブレ防止機能
debounce(fn, wait) {
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
timer = null
}, wait);
}
},
//スロットリング機能
throttling(fn, wait) {
let endTime = +new Date
return function () {
if (+new Date - endTime < wait) return console.log('too busy');
fn.apply(this, arguments)
endTime = +new Date
}
}
})
/**
* 文字列プロトタイプの拡張
*/
_.extend({
/**
* 均等性の判定
*/
equals(str) {
return this === str
},
/**
* 文字列が含まれているかどうかを判定する
*/
includes(str) {
return this.indexOf(str) > -1
},
/**
* 文字列が文字列で始まるかどうかを判定する
*/
startsWith(str) {
return this.indexOf(str) === 0
},
/**
*
*/
toNumber() {
var result = parseFloat(this)
return isNaN(result) ? 0 : result
},
/**
* 最初の大文字
*/
toCapitalized() {
return this[0].toUpperCase() + this.substring(1)
},
/**
* モザイク・チャン*
*/
mosaic(start, end, code = "*") {
if (!start && start !== 0) throw new Error("パラメータが間違っている")
if (isNaN(start) || start < 0 || start >= this.length)
throw new Error("パラメータが間違っている")
if (!end || end >= this.length) end = this.length
if (isNaN(end) || end <= start) throw new Error("パラメータが間違っている")
var left = this.substring(0, start)
var middle = code.repeat(end - start)
end = this.substring(end)
return left + middle + end
},
/**
* 文字列のオーバーフロー省略
*/
limit(count = 50) {
if (this.length <= count) return this
return this.substring(0, count) + "..."
}
}, String.prototype)
/**
* 文字列関連の拡張機能
*/
_.extend({
trim(str) {
if (!str) return ''
return str.trim()
},
checkStrNullOrEmpty(str) {
return !str || str.trim() === ''
},
checkStrHasVal(str) {
return !this.checkStrNullOrEmpty(str)
},
checkStrLength(str, len) {
return str && str.trim().length >= len
}
})
/**
* 時間拡張
*/
_.extend({
/**
* 書式付き時間テキストの取得
*/
getFormatText() {
var now = this
var yyyy = now.getFullYear()
var mm = _.repairZero(now.getMonth() + 1)
var dd = _.repairZero(now.getDate())
var hh = _.repairZero(now.getHours())
var mi = _.repairZero(now.getMinutes())
var ss = _.repairZero(now.getSeconds())
var str = "1日目、2日目、3日目、4日目、5日目、6日目"
var week = str[now.getDay()]
return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss} ${week}`
},
/**
* 年、月、日のテキストを取得する
*/
getFormatDate() {
return this.getFormatText().split(' ')[0]
},
/**
* 時、分、秒のテキストを取得する
*/
getFormatTime() {
return this.getFormatText().split(' ')[1]
},
/**
* 曜日テキストを取得する
*/
getFormatWeek() {
return this.getFormatText().split(' ')[2]
}
}, Date.prototype)
/**
* 配列の拡張
*/
_.extend({
/**
* 配列内で最初に出現する要素の位置
*/
indexOf(obj) {
for (let i = 0; i < this.length; i++) {
if (this[i] === obj) return i
}
return -1
},
/**
* 配列内の要素の最後の位置
*/
lastIndexOf(obj) {
for (let i = this.length - 1; i >= 0; i--) {
if (this[i] === obj) return i
}
return -1
},
/**
* 配列の末尾に要素を追加する
*/
push(obj) {
this[this.length] = obj
},
//配列を文字列に分割する
join(code = "") {
var str = ""
for (let i = 0; i < this.length; i++) {
str += (this[i] + code)
}
return str.substring(0, str.length - 1)
},
/*
* 要素を削除する
*/
remove(obj) {
var index = this.indexOf(obj)
if (index > -1) this.removeAt(index)
},
/**
* 添え字に基づいて要素を削除する
*/
removeAt(index) {
if (index >= 0 && index < this.length) {
this.splice(index, 1)
}
},
/**
* 要素を削除する
*/
removeAll(obj) {
//配列内の要素の位置を見つける
var index = this.indexOf(obj)
//もし
if (index > -1) {
//添え字に基づく配列からの削除
this.removeAt(index)
//要素が配列内で見つからない限り、自分自身を再度呼び出す。
arguments.callee.call(this, obj)
}
},
/**
* 添え字に基づいてセグメントを削除する
*/
splice(index, count) {
for (let i = index; i < this.length - 1; i++) {
this[i] = this[i + count]
}
for (let i = 0; i < count; i++) this.pop()
},
/**
* 最初の要素を削除する
*/
shift() {
var result = this[0]
this.splice(0, 1)
return result
},
/**
* 配列の反転
*/
reverse() {
for (let i = 0; i < Math.floor(this.length / 2); i++) {
var temp = this[i]
this[i] = this[this.length - 1 - i]
this[this.length - 1 - i] = temp
}
},
/**
* 指定した位置に要素を追加する
*/
insertAt(index, obj) {
if (index < 0 || index > this.length) throw new Error("パラメータが間違っている")
for (let i = this.length - 1; i >= index; i--) {
this[i + 1] = this[i]
}
this[index] = obj
return this.length
},
/**
* 先頭に要素を追加する
*/
unshift(obj) {
return this.insertAt(0, obj)
},
/**
* 最後の要素を削除する
*/
pop() {
var result = this[this.length - 1]
this.length -= 1
return result
},
forEach(fn) {
for (let i = 0; i < this.length; i++) {
fn(this[i], i)
}
},
some(fn) {
for (let i = 0; i < this.length; i++) {
if (fn(this[i], i)) return true
}
return false
},
every(fn) {
for (let i = 0; i < this.length; i++) {
if (!fn(this[i], i)) return false
}
return true
},
count(fn) {
var result = 0
this.forEach(function (item, i) {
if (fn(item, i)) result++
})
return result
},
filter(fn) {
var result = []
this.forEach(function (item, i) {
if (fn(item, i)) result.push(item)
})
return result
},
map(callback) {
var arr = []
for (let i = 0; i < this.length; i++) {
var result = callback(this[i], i)
arr.push(result)
}
return arr
},
includes(obj) {
return this.some(function (item) {
return item === obj
})
}
}, Array.prototype)
//Math
_.extend({
isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
},
//数字をアルファベットに変換する
toENChar(val) {
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[val]
},
/**
* 奇数かどうかを判定する
*/
isOdd(num) {
return num % 2 !== 0
},
/**
* 数が偶数かどうかを判定する
*/
isEven(num) {
return num % 2 === 0
},
/**
* ランダム整数(最大,min)
*/
rnd(max, min = 0) {
return Math.round(Math.random() * (max - min)) + min
}
}, Math)
//Cookie
_.extend({
setCookie(key, val, expires) {
if (typeof val === 'object')
val = JSON.stringify(val)
let now = new Date()
now.setMinutes(now.getMinutes() + expires)
document.cookie = `${key}=${encodeURI(val)};expires=${now.toUTCString()}`
},
removeCookie(key) {
this.setCookie(key, null, -1)
},
getCookie(key) {
let obj = {}
document.cookie.split('; ').forEach(r => {
let kv = r.split('=')
obj[kv[0]] = decodeURI(kv[1])
})
if (key) {
let res = null
try {
res = JSON.parse(obj[key])
} catch (error) {
res = obj[key]
}
return res
}
return obj
},
})
/**
* オブジェクト関連の拡張
*/
_.extend({
keys(obj) {
let arr = []
for (const key in obj) {
arr.push(key)
}
return arr
},
//vuexのmapStateメソッドのモック実装
mapState(fileds) {
let obj = {}
fileds.forEach(key => {
obj[key] = function () {
return this.$store.state[key]
}
})
return obj
}
})
/**
* グローバル・オブジェクトの公開
*/
return _
}))