fp-ts icon indicating copy to clipboard operation
fp-ts copied to clipboard

Why does `string.split` return non-empty array when given an empty string?

Open OliverJAsh opened this issue 3 years ago • 6 comments

🐛 Bug report

Current Behavior

String.prototype.split:

''.split('') // => []

fp-ts:

pipe('', string.split('')) // => ['']

Expected behavior

I would expect [] from string.split, so it matches String.prototype.split but also because I think that behaviour makes more sense.

It seems like this was done intentionally: https://github.com/gcanti/fp-ts/commit/7d1887de8b704b6dc86a29964c33f6ca8decb41a#diff-bbade37cef19cf470364082a01329d9fbf208a96862818d50ea97602767d7a48R130

What was the reasoning for this change?

Reproducible example

See above.

Suggested solution(s)

Additional context

Your environment

Which versions of fp-ts are affected by this issue? Did this work in previous versions of fp-ts?

Software Version(s)
fp-ts
TypeScript

OliverJAsh avatar Nov 29 '21 11:11 OliverJAsh

Why do you think it makes more sense to return an empty array?

enricopolanski avatar Nov 29 '21 18:11 enricopolanski

  1. Because that's the behaviour of String.prototype.split.
  2. pipe('ab', string.split('')) returns ['a', 'b'], which suggests that a '' separator will split each character, but if '' is the input, there are no characters to split

OliverJAsh avatar Nov 29 '21 19:11 OliverJAsh

Checked out with test case by split from purescript-strings:

  assertEqual
    { actual: S.split (Pattern "") ""
    , expected: []
    }

imcotton avatar Dec 01 '21 06:12 imcotton

  1. Because that's the behaviour of String.prototype.split.
  2. pipe('ab', string.split('')) returns ['a', 'b'], which suggests that a '' separator will split each character, but if '' is the input, there are no characters to split

I don't see why is that relevant what the native api does. 🤷

I think we're reframing the classical question of "does the empty set contains itself". I think both of the choices are okay and it's more of a design question than a bug.

enricopolanski avatar Dec 01 '21 09:12 enricopolanski

When playing around with this case it becomes even more crazy. When we generalize the problem to input = separator we should actually return ['', ''] 😉

'a'.split('a') === ['', '']
''.split('') === [] // why?

It seems to be an edge case, but if when there is no higher intent for [''] we should go for [].

mlegenhausen avatar Dec 01 '21 10:12 mlegenhausen

:trollface: https://github.com/denysdovhan/wtfjs#split-a-string-by-a-space

imcotton avatar Dec 01 '21 14:12 imcotton