Friday, 22 November 2019

The most efficient way to trim a file name in JavaScript

I was wondering how to trim a file name in JS to show "..." or any appendix for that matter after a certain number of characters, the most efficient way to handle all possible test cases.

Rules

  1. Show the actual file extension and not the last character after splitting the string name with "."
  2. The function should take the input file name (string), the number of characters to trim (integer) and appendix (string) as the parameter.
  3. By efficient, I mean I expect to write fewer lines of code and handle all possible edge cases.

Sample Inputs

  1. myAwesomeFile.min.css
  2. my Awesome File.tar.gz
  3. file.png

Expected output (say I want to trim after 5 characters)

  1. myAwe....min.css
  2. my Aw....tar.gz
  3. file.png

Editing the question to show my attempt

function trimFileName(str, noOfChars, appendix) {
  let nameArray = str.split(".");
  let fileType = `.${nameArray.pop()}`;
  let fileName = nameArray.join(" ");

  if (fileName.length >= noOfChars) {
    fileName = fileName.substr(0, noOfChars) + appendix;
  };

  return (fileName + fileType);
}

console.log(trimFileName("myAwesomeFile.min.css", 5, "..."));
console.log(trimFileName("my Awesome File.tar.gz", 5, "..."));
console.log(trimFileName("file.png", 5, "..."));

Edit #2: Feel free to go ahead and edit the question if you think it's not the standard expectation and add more edge cases to the sample inputs and expected outputs.

Edit #3: Added a few more details to the question after the new comments. I know my attempt doesn't fulfill my expected outputs (and I am unsure whether the output I have listed above is a standard expectation or not).

Edit #4 (Final): Removed the rule of not breaking a word in the middle after a continuous backlash in the comments and changed the rules to cater to more realistic and practical use cases.



from The most efficient way to trim a file name in JavaScript

No comments:

Post a Comment