Last active
June 16, 2020 17:54
-
-
Save cherifGsoul/a32de0fe3f5777395bbb5397dc7ac698 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const setNumber = function setNumber(number) { | |
if (typeof number !== 'string') { | |
throw new Error('Mobile phone number must be of string value'); | |
} | |
const normalized = number.replace(/\s|-/g, ''); | |
if (/^(00213|\+213|0)(5|6|7)[0-9]{8}/.test(normalized) === false) { | |
throw new Error('Invalid phone number'); | |
} | |
this.number = normalized; | |
} | |
class AlgerianMobilePhoneNumber { | |
constructor(number) { | |
setNumber.call(this,number); | |
} | |
asString() { | |
return this.number; | |
} | |
toString() { | |
return this.asString(); | |
} | |
valueOf() { | |
return this.asString(); | |
} | |
withNumber(number) { | |
return algerianMobilePhoneNumberFromString(number); | |
} | |
equals(other) { | |
const thisType = Object.prototype.toString.call(this); | |
const otherType = Object.prototype.toString.call(other); | |
if (thisType === otherType) { | |
return this.number === other.number; | |
} | |
return false; | |
} | |
get [Symbol.toStringTag]() { | |
return 'AlgerianMobilePhoneNumber'; | |
} | |
} | |
module.exports = algerianMobilePhoneNumberFromString = (number) => { | |
const instance = new AlgerianMobilePhoneNumber(number); | |
return new Proxy(instance, { | |
get(target, prop, receiver) { | |
if (typeof prop === 'function') { | |
return instance[prop].bind(target); | |
} | |
return Reflect.get(target, prop); | |
}, | |
set() { | |
throw new Error('Can not set properties on immutable object'); | |
}, | |
defineProperty() { | |
throw new Error('Can not define new properties on immutable object'); | |
}, | |
deleteProperty() { | |
throw new Error('Can not delete property on immutable object'); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment