All files / path / _common / basename.ts

100.00% Branches 15/15
100.00% Lines 40/40
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
 
 
x51
 
x51
x122
x225
x225
 
x228
 
x122
x201
x204
x204
x201
 
x156
x122
 
x51
x51
x51
x51
 
x506
x506
 
x506
x3229
x3690
x4067
x4067
x4067
x3229
x5921
x5921
x5921
x3229
 
x506
x506
 
x51
x508
x508
x508
x509
x509
 
x509
x508



















































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

import { assertPath } from "./assert_path.ts";

export function stripSuffix(name: string, suffix: string): string {
  if (suffix.length >= name.length) {
    return name;
  }

  const lenDiff = name.length - suffix.length;

  for (let i = suffix.length - 1; i >= 0; --i) {
    if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) {
      return name;
    }
  }

  return name.slice(0, -suffix.length);
}

export function lastPathSegment(
  path: string,
  isSep: (char: number) => boolean,
  start = 0,
): string {
  let matchedNonSeparator = false;
  let end = path.length;

  for (let i = path.length - 1; i >= start; --i) {
    if (isSep(path.charCodeAt(i))) {
      if (matchedNonSeparator) {
        start = i + 1;
        break;
      }
    } else if (!matchedNonSeparator) {
      matchedNonSeparator = true;
      end = i + 1;
    }
  }

  return path.slice(start, end);
}

export function assertArgs(path: string, suffix: string) {
  assertPath(path);
  if (path.length === 0) return path;
  if (typeof suffix !== "string") {
    throw new TypeError(
      `Suffix must be a string, received "${JSON.stringify(suffix)}"`,
    );
  }
}