Check Duplicated Paths with LoDash (and Angular 2)
2 min read

Check Duplicated Paths with LoDash (and Angular 2)

Check Duplicated Paths with LoDash (and Angular 2)

One of the things I'm looking at is to be able to create a list of paths I'd want to scan. The first iteration had blind addition to the list. However, this would make the user's responsibility to manage the duplicated paths, which is not really nice. Therefore, I think it's a good thing to add some sort of path duplication detection in the code. The pseudo-code would be something like:

for each item in the list:
    if item.indexOf(newPath) >- 1:
        return item
return null

In this case, if we have a non-null item, then we already have something in the list. Otherwise, we'll need to add it.

The lodash implementation is a bit more convoluted:

import { sep } from 'path'
import * as _ from 'lodash'

class PathListWiidget {
  @Input() pathsList: string[] = []
  /**
   * Check if a path is already present in the list.
   *
   * @param newPath
   */
  _checkNewPath(newPath: string) {
    const completePath = newPath + sep
    return _.find(this.pathsList, function(item: string) {
      const tmpPath = item + sep
      return completePath.indexOf(tmpPath) > -1
    })
  }

  // ...
}

I've had to add the sep because the code needs to tell that paths like /usr/local and /usr/locals are different paths, but /usr/local and /usr/local/bin are nested. Comparing newPath against item will detect the case when we already have /usr/local in our list and the user wants to add /usr/local/bin.

Now, the code can be called like:

onAdd(path: string) {
  if (this._checkNewPath(path)) {
    logger.warn(`PathListWidget: onAdd(): Path [${path}] already present in the list`)
  } else {
    this.pathsList.push(path)
  }
}

Notes

We can extend the logger.warn() branch to e.g. emit an event so we can notify the user.

The code above does only flag if the list has a path like /usr/local and the user wants to add /usr/local/bin. It does not detect the opposite. We could extend the logic to verify the other way around. The problem is the list can have something like /usr/local/bin and /usr/local/lib and the user would want to add /usr/local (which would include both original paths).

HTH,