Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

93
Views
How to return a default parameter while calling object?

I am using routes variable to return routes to various urls.

export const routes = {
    root: {  path: '/' },
    login: { path: '/login' },
    users: { path: '/users'}
}

Now, I have to use it like routes.login.path now. But is there any way that if nothing is passed after the parameter, it takes 'path' by default. Something like this: routes.login should automatically return '/login'

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

You want routes.login to return the string "/login", and you want to access .path through that string. I would recommend you to rethink the the way you are approaching this problem.

Nevertheless, there are two ways to achieve this:

One is to assign a path property onto each string like so:

export const routes = {
    root: Object.assign('/', {  get path() {return String(this)} }),
    login: Object.assign('/login', {  get path() {return String(this)} }),,
    users: Object.assign('/users', {  get path() {return String(this)} }),
}

The other is to override the toString method of the object:

export const routes = {
    root: {  path: '/', toString() {return this.path} },
    login: { path: '/login', toString() {return this.path} },
    users: { path: '/users', toString() {return this.path} }
}

Of course, you can clean this up with a separate class:

// First Method
class Route extends String {
  get path() { return String(this) }
}

export const routes = {
    root: new Route('/'),
    login: new Route('/login'),
    users: new Route('/users')
}

// Second Method
class Route {
  constructor(data) {
    Object.assign(this, data);
  }
  toString() {
    return this.path;
  }
}

export const routes = {
    root: new Route({  path: '/' }),
    login: new Route({ path: '/login' }),
    users: new Route({ path: '/users' })
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs