DEV Community

Mitchell
Mitchell

Posted on • Edited on

String prototype - JavaScript Challenges

You can find all the code in this post in the repo Github.


String prototype related challenges


String.prototype.repeat()

The key here is to handle different edge cases.

/**
 * @param {number} count
 * @return {string}
 */

// Time: O(1) | Space: O(1)
String.prototype.myRepeat = function (count) {
  if (count < 0) {
    throw new RangeError("count must be non-negative");
  }

  if (count === 0) {
    return "";
  }

  return Array.from({ length: Math.round(count) + 1 }).join(this);
};

// Usage example
console.log("abc".myRepeat(0)); // => ""
console.log("abc".myRepeat(1)); // => "abc"
console.log("abc".myRepeat(2)); // => "abcabc"
console.log("abc".myRepeat(-1)); // => RangeError
Enter fullscreen mode Exit fullscreen mode

String.prototype.trim()

Use regular expressions to make your day easier:

  • // for regular expression
  • ^ matches the beginning
  • $ matches the ending
  • g matches all the patterns
  • | acts like logic OR operator
  • + means one or more characters
  • \s matches all whitespace(spaces, tabs, line breaks)
/**
 * @param {strint} str
 * @return {string}
 */

// Time: O(1) | Space: O(1)
String.prototype.myTrim = function () {
  return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
  // or
  // return this.replace(/^[\s]+|[\s]+$/g, "");
};

// Usage example
const str = "  Hello, World!  ";
console.log(str.myTrim()); // => "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Reference

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more