Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Last active January 25, 2018 09:05
Show Gist options
  • Save xiaoyunyang/86f3750aa0e0847c1b68eb5795a57e89 to your computer and use it in GitHub Desktop.
Save xiaoyunyang/86f3750aa0e0847c1b68eb5795a57e89 to your computer and use it in GitHub Desktop.
Closure Example Actual
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