Skip to content

Commit 71cdcf2

Browse files
bugfixes
1 parent c798dfe commit 71cdcf2

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

src/Data/String/CodePoints.js

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,23 +17,32 @@ function fromCodePoint(cp) {
1717
return cu1 + cu2;
1818
}
1919

20+
var codePointAt0 = hasCodePointAt
21+
? function (str) { return str.codePointAt(0); }
22+
: function (str) {
23+
if (str.length === 1) {
24+
return str.charCodeAt(0);
25+
}
26+
return ((str.charCodeAt(0) - 0xD800) * 0x400 + (str.charCodeAt(1) - 0xDC00) + 0x10000);
27+
};
28+
2029
exports._codePointAt = function (fallback) {
2130
return function (Just) {
2231
return function (Nothing) {
2332
return function (index) {
2433
return function (str) {
2534
var length = str.length;
2635
if (index < 0 || index >= length) return Nothing;
27-
if (hasArrayFrom && hasCodePointAt) {
36+
if (hasArrayFrom) {
2837
var cps = Array.from(str);
2938
if (index >= cps.length) return Nothing;
30-
return Just(cps[index].codePointAt(0));
39+
return Just(codePointAt0(cps[index]));
3140
} else if (hasStringIterator) {
3241
var iter = str[Symbol.iterator]();
3342
for (var i = index;; --i) {
3443
var o = iter.next();
3544
if (o.done) return Nothing;
36-
if (i === 0) return Just(o.value);
45+
if (i === 0) return Just(codePointAt0(o.value));
3746
}
3847
}
3948
return fallback(index)(str);
@@ -70,6 +79,7 @@ exports._count = function (isLead) {
7079
};
7180

7281
exports.fromCodePointArray = hasFromCodePoint
82+
// TODO: using F.p.apply here will fail for very large strings; use alternative implementation for very large strings
7383
? function (cps) { return String.fromCodePoint.apply(String, cps); }
7484
: function (cps) { return cps.map(fromCodePoint).join(""); };
7585

@@ -93,23 +103,23 @@ exports._take = function (fallback) {
93103
return accum;
94104
};
95105
}
96-
return fallback;
106+
return fallback(n);
97107
};
98108
};
99109

100110
exports._toCodePointArray = function (fallback) {
101-
if (hasArrayFrom && hasCodePointAt) {
111+
if (hasArrayFrom) {
102112
return function (str) {
103-
return Array.from(str, function (x) { return x.codePointAt(0); });
113+
return Array.from(str, codePointAt0);
104114
};
105-
} else if (hasStringIterator && hasCodePointAt) {
115+
} else if (hasStringIterator) {
106116
return function (str) {
107117
var accum = [];
108118
var iter = str[Symbol.iterator]();
109119
for (;;) {
110120
var o = iter.next();
111121
if (o.done) return accum;
112-
accum.push(o.value.codePointAt(0));
122+
accum.push(codePointAt0(o.value));
113123
}
114124
};
115125
}

0 commit comments

Comments
 (0)