Jyoti Mishra
Jyoti Mishra

Reputation: 21

Checking if an array of package.json dependency is sorted in alphanumeric order in typeScript

I want to check if an array of package.json dependencies and devDependencies are sorted in alphanumeric order in typeScript. If it is not sorted then it should return the dep name which is falling out of place.

I want to build a bazel rule checking in typesScript to check

{
  dependencies: {
    "dep2": "0.0.1",
    "dep1": "0.0.2"
  },
  devDependencies: {
    "devdep1": "0.0.1",
    "devde": "0.0.1"
  }
}

to return false saying dep2, devdep1 are violating.

Upvotes: 0

Views: 217

Answers (1)

Vaibhav
Vaibhav

Reputation: 1473

You can compare strings using <, >, <=,>=

In a loop, if each left side value is less, it is ascending order. So,

  1. Import you package.json file,
  2. parse it using JSON.parse(),
  3. access object, loop through to compare values like below

function check(data) {
  for (let i = 0; i < data.length - 1; i++) {
    if (data[i] > data[i + 1]) {
      console.log(false)
      return false;
    }
  }
  console.log(true)
  return true;
}

const data = ['a', 'a-b', 'b', 'c', 'd', 'e'];
check(data)

const data1 = ['a', 'c', 'b', 'c', 'd'];
check(data1)

Upvotes: 1

Related Questions