Advertisement
Guest User

Untitled

a guest
Feb 16th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Path {
  2.   constructor(private readonly sys: Sys) {}
  3.  
  4.   private intoStack(pathLike: string): string[] {
  5.     return pathLike.split('/').filter(n => n.length !== 0)
  6.   }
  7.  
  8.   /** returns true if the path is absolute. */
  9.   public isAbsolute(pathLike: string): boolean {
  10.     return (pathLike.indexOf('/') === 0)
  11.   }
  12.   /** returns the `dirname` path for this path. */
  13.   public dirname(pathLike: string): string {
  14.     const stack = this.intoStack(pathLike)
  15.     stack.pop()
  16.     return stack.length > 0 ? stack.join('/') : '/'
  17.   }
  18.  
  19.   /** Returns the `basename` for the given path. */
  20.   public basename(pathLike: string): string {
  21.     return this.intoStack(pathLike).pop() || ''
  22.   }
  23.  
  24.   /** Returns the `extname` for the given path. */
  25.   public extname(pathLike: string): string {
  26.     const stack = this.intoStack(pathLike)
  27.     const last  = stack[stack.length - 1]
  28.     const parts = last.split('.')
  29.     return (!(parts.length === 1 || parts[0].length === 0))
  30.       ? '.' + parts[parts.length - 1]
  31.       : ''
  32.   }
  33.  
  34.   public join(...pathLikes: string[]): string {
  35.     return ''
  36.   }
  37.   public resolve(pathLike: string): string {
  38.     return ''
  39.   }
  40.  
  41.   public relative(from: string, to: string): string {
  42.     return ''
  43.   }
  44.  
  45.   public normalize(pathLike: string): string {
  46.     const absolute = this.isAbsolute(pathLike)
  47.     const normal = this.intoStack(pathLike).reduce((acc, current) => {
  48.       if(current === '..') {
  49.         if(absolute) {
  50.           if(acc.length === 0) {
  51.             return ['']
  52.           } else if (acc[acc.length - 1] !== '..') {
  53.             acc.pop()
  54.             return acc
  55.           } else {
  56.             return [...acc, current]
  57.           }
  58.         } else {
  59.           if(acc.length === 0) {
  60.             return ['..']
  61.           } else if (acc[acc.length - 1] !== '..') {
  62.             acc.pop()
  63.             return acc
  64.           } else {
  65.             return [...acc, current]
  66.           }
  67.         }
  68.       }
  69.       return (current !== '.')
  70.         ? [...acc, current]
  71.         : [...acc]
  72.     }, [] as string[]).join('/')
  73.     return (absolute && normal.indexOf('/') !== 0)
  74.       ? ('/' + normal)
  75.       : normal
  76.   }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement