Skip to content

Instantly share code, notes, and snippets.

@hnq90
Last active August 30, 2017 07:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hnq90/1c63e82377b5cac9ec0ed7a1d93269d2 to your computer and use it in GitHub Desktop.
Save hnq90/1c63e82377b5cac9ec0ed7a1d93269d2 to your computer and use it in GitHub Desktop.
ES6 YubinBango
/**
* 郵便番号自動入力クラス
* YubinBango
*
* [SOURCE]
* https://github.com/kobabasu/micro-flux
*
* [LATEST VERSION]
* https://gist.github.com/hnq90/1c63e82377b5cac9ec0ed7a1d93269d2
*
* [HOW TO USE]
* new YubinBango().fetch(zipCode, address => {
* if (address === false) {
* alert('Invalid Zipcode')
* } else {
* // const { region_id, region, locality, street, extended } = address
* console.log(address)
* }
* })
*/
const CACHE = []
export default class YubinBango {
static DATA_URL = 'https://yubinbango.github.io/yubinbango-data/data'
static ZIPCODE_LENGTH = 7
static JSONP_CALLBACK = '$yubin'
static REGION = [
null, '北海道', '青森県', '岩手県', '宮城県',
'秋田県', '山形県', '福島県', '茨城県', '栃木県',
'群馬県', '埼玉県', '千葉県', '東京都', '神奈川県',
'新潟県', '富山県', '石川県', '福井県', '山梨県',
'長野県', '岐阜県', '静岡県', '愛知県', '三重県',
'滋賀県', '京都府', '大阪府', '兵庫県', '奈良県',
'和歌山県', '鳥取県', '島根県', '岡山県', '広島県',
'山口県', '徳島県', '香川県', '愛媛県', '高知県',
'福岡県', '佐賀県', '長崎県', '熊本県', '大分県',
'宮崎県', '鹿児島県', '沖縄県'
]
fetch (value, callback) {
if (value) {
const zipCode = value
.replace(/[0-9]/g, str => String.fromCharCode(str.charCodeAt(0) - 65248))
.match(/\d/g)
.join('')
if (this.validate(zipCode)) {
this.getAddress(zipCode, callback)
} else {
callback(false)
}
}
}
validate (zipCode) {
return zipCode.length === YubinBango.ZIPCODE_LENGTH
}
jsonp (url, callback) {
window[YubinBango.JSONP_CALLBACK] = data => callback(data)
const scriptTag = document.createElement('script')
scriptTag.setAttribute('type', 'text/javascript')
scriptTag.setAttribute('charset', 'UTF-8')
scriptTag.setAttribute('src', url)
document.body.appendChild(scriptTag)
}
getAddress (zipCode, callback) {
const zip01 = zipCode.substr(0, 3)
if (this.cacheCheck(zip01)) {
callback(this.selectAddress(zipCode, CACHE[zip01][zipCode]))
} else {
this.jsonp(`${YubinBango.DATA_URL}/${zip01}.js`, data => {
if (data && Object.keys(data).length > 0) {
CACHE[zip01] = data
callback(this.selectAddress(zipCode, data[zipCode]))
} else {
callback(false)
}
})
}
}
selectAddress (zipCode, address) {
let result = {
region_id: '',
region: '',
locality: '',
street: '',
extended: ''
}
if (address) {
result = Object.assign(
{},
result,
{
region_id: address[0],
region: YubinBango.REGION[address[0]],
locality: address[1],
street: address[2],
extended: address[3] || ''
}
)
return result
}
return false
}
cacheCheck (zip01) {
if (CACHE[zip01]) {
return true
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment