Last active
January 25, 2018 09:05
-
-
Save xiaoyunyang/86f3750aa0e0847c1b68eb5795a57e89 to your computer and use it in GitHub Desktop.
Closure Example Actual
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 getInfoFromURL = path => { | |
const URL = require(“url”).URL; | |
const myUrl = new URL(path) | |
const pathname = myUrl.pathname | |
const getUsernameFromURL = pathname => { | |
const regex = new RegExp(‘/@’); | |
const username = pathname.split(regex).slice(1)[0] | |
if(!username) { | |
return “Error in parsing: URL needs to be in format://hostname:port/@username” | |
} | |
return username | |
} | |
const getPathnameFromURL = pathname => { | |
const regex = new RegExp(‘/’); | |
const name = pathname.split(regex).slice(1)[0] | |
if(!name) { | |
return “Error in parsing: URL needs to be in format://hostname:port/pathname” | |
} | |
return name | |
} | |
return (param) => { | |
if (param === “username”) return getUsernameFromURL(pathname) | |
else if (param === “pathname”) return getPathnameFromURL(pathname) | |
else return “error” | |
} | |
} | |
// You should get “xiaoyunyang” | |
getInfoFromURL(“https://medium.com/@xiaoyunyang")("username") | |
// You should get “@xiaoyunyang | |
getInfoFromURL(path)(“pathname”) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment