Search code examples
javascriptobjectclojurescript

Implementation of String.prototype.startsWith in ClojureScript


I need to convert this Javascript code into ClojureScript. I'm having some trouble with the this keyword.

Here's my JS:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

I'm getting a Object doesn't support property or method 'startsWith' error with the Google Closure compiler in advanced mode so I need to add this code. (IE 11)


Solution

  • Try this ClojureScript code:

    (when (not (.. js/String -prototype -startsWith))
      (set!
        (.. js/String -prototype -startsWith)
        (fn [searchString position]
          (set! position (or position 0))
          (= (this-as this (.indexOf this) searchString position) position))))