gkz / prelude-ls

prelude.ls is a functionally oriented utility library - powerful and flexible, almost all of functions are curried. It is written in, and is the recommended base library for, http://livescript.net
http://preludels.com/
MIT License
424 stars 59 forks source link

Request: check if a string contains another one with "in" or "contains" #110

Open vindarel opened 7 years ago

vindarel commented 7 years ago

Hi all, Currently when I want to check if a string contains a substring, I need to use javascript's indexOf, or other tricks.

Of course, I always write first "foo" in "foobar", but that doesn't work. That would be the best solution to me. Would it be possible to see that in LiveScript ?

Then I look at prelude and I don't find something like Str:contains. That would also be nice.

Any chance to see that coming ?

Thanks !

tcrowe commented 6 years ago

What solution did you end up with @vindarel ?

I was thinking about a similar thing. in operator gives a TypeError on this in JS.

if 'five' in 'i am five years old'
  console.log 'its in'

That transpiled to:

if (in$('five', 'i am five years old')) {
  console.log('its in');
}
function in$(x, xs){
  var i = -1, l = xs.length >>> 0;
  while (++i < l) if (x === xs[i]) return true;
  return false;
}

I'm not sure what that is doing but if you have ES6 or polyfills includes would be in there. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

Another way might be something like:

# includes :: String -> String -> Boolean
includes = (check, str) --> str.indexOf(check) > -1

checkForFive = includes 'five'

console.log checkForFive 'i am five years old'
# true

console.log checkForFive 'i am six years old'
# false
vindarel commented 6 years ago

I indeed falled back on the usual .indexOf plain JS solution :/