String
's are sort of a collection of Char
's, but immutable. So, why not make it more functional and iterative?
Right now, to treat string as an array we have to .split('')
and then .join('')
back, but what if this would happen more seamlessly?
You can sort of achieve it with this hacky hack:
String.prototype.map = Array.prototype.map
And then if you call
"hello".map((e,i,self) => self[self.length-1-i])
Which will return ['o', 'l', 'l', 'e', 'h']
.
This kinda works with methods that don't mutate the string (previously array). But still yeilds some weird behavior.
for(a in str){ console.log(a) } // 0, 1, 2, 3, 4, 5, map, filter
And will not with things that do
String.prototype.reverse = Array.prototype.reverse
"hello".reverse()
Will yield and error saying that "we can assign value to readonly property".
Just imagine how amazing, clean and simple would JS be. Heck, we are going functional way, which is great, why not go all the way.
someString.split('').sort().join('')
will become
someString.sort()
and
someString.split('').reverse().join('')
will become
someString.reverse()
Is this even necessary? Are there any better ideas how to go about this?