helpers.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. // eslint-disable-next-line es/no-object-hasown -- safe
  3. const has = Object.hasOwn || Function.call.bind({}.hasOwnProperty);
  4. const VERSION_PATTERN = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/;
  5. class SemVer {
  6. constructor(input) {
  7. const match = VERSION_PATTERN.exec(input);
  8. if (!match) throw new TypeError(`Invalid version: ${ input }`);
  9. const [, $major, $minor, $patch] = match;
  10. this.major = +$major;
  11. this.minor = $minor ? +$minor : 0;
  12. this.patch = $patch ? +$patch : 0;
  13. }
  14. toString() {
  15. return `${ this.major }.${ this.minor }.${ this.patch }`;
  16. }
  17. }
  18. function semver(input) {
  19. return input instanceof SemVer ? input : new SemVer(input);
  20. }
  21. function compare($a, operator, $b) {
  22. const a = semver($a);
  23. const b = semver($b);
  24. for (const component of ['major', 'minor', 'patch']) {
  25. if (a[component] < b[component]) return operator === '<' || operator === '<=' || operator === '!=';
  26. if (a[component] > b[component]) return operator === '>' || operator === '>=' || operator === '!=';
  27. } return operator === '==' || operator === '<=' || operator === '>=';
  28. }
  29. function filterOutStabilizedProposals(modules) {
  30. const modulesSet = new Set(modules);
  31. for (const $module of modulesSet) {
  32. if ($module.startsWith('esnext.') && modulesSet.has($module.replace(/^esnext\./, 'es.'))) {
  33. modulesSet.delete($module);
  34. }
  35. }
  36. return [...modulesSet];
  37. }
  38. function intersection(list, order) {
  39. const set = list instanceof Set ? list : new Set(list);
  40. return order.filter(name => set.has(name));
  41. }
  42. function sortObjectByKey(object, fn) {
  43. return Object.keys(object).sort(fn).reduce((memo, key) => {
  44. memo[key] = object[key];
  45. return memo;
  46. }, {});
  47. }
  48. module.exports = {
  49. compare,
  50. filterOutStabilizedProposals,
  51. has,
  52. intersection,
  53. semver,
  54. sortObjectByKey,
  55. };