Skip to content

Commit eddaec8

Browse files
Add 'Array.join' implementation.
1 parent 05a8677 commit eddaec8

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

TinyJS_Functions.cpp

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -299,20 +299,28 @@ Ref<JSValue> scArrayRemove(FunctionScope* pScope) {
299299
v = v->nextSibling;
300300
}
301301
}
302+
*/
302303

303-
Ref<JSValue>scArrayJoin(FunctionScope* pScope) {
304-
string sep = pScope->getParam("separator")->toString();
305-
CScriptVar *arr = pScope->getThis();
304+
Ref<JSValue>scArrayJoin(FunctionScope* pScope)
305+
{
306+
Ref<JSArray> arr = pScope->getThis().staticCast<JSArray>();
307+
auto sep = pScope->getParam("separator");
308+
string sepStr = ",";
306309

307-
ostringstream sstr;
308-
int l = arr->getArrayLength();
309-
for (int i=0;i<l;i++) {
310-
if (i>0) sstr << sep;
311-
sstr << arr->getArrayIndex(i)->toString();
312-
}
310+
if (!sep->isNull())
311+
sepStr = sep->toString();
313312

314-
return jsString(sstr.str());
315-
}*/
313+
ostringstream output;
314+
const size_t n = arr->length();
315+
for (size_t i = 0; i < n; i++)
316+
{
317+
if (i > 0)
318+
output << sepStr;
319+
output << arr->getAt(i)->toString();
320+
}
321+
322+
return jsString(output.str());
323+
}
316324

317325
// ----------------------------------------------- Register Functions
318326

@@ -377,7 +385,7 @@ void registerFunctions(Ref<IScope> scope)
377385
// JSON.parse is left out as you can (unsafely!) use eval instead
378386
// addNative("function Array.contains(obj)", scArrayContains, scope);
379387
// addNative("function Array.remove(obj)", scArrayRemove, scope);
380-
// addNative("function Array.join(separator)", scArrayJoin, scope);
388+
addNative("function Array.prototype.join(separator)", scArrayJoin, scope);
381389
addNative("function Array.prototype.push(x)", scArrayPush, scope);
382390
addNative("function Array.prototype.indexOf(searchElement, fromIndex)", scArrayIndexOf, scope);
383391
}

tests/test030.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// test for array join
22
var a = [1,2,4,5,7];
33

4-
result = a.join(",")=="1,2,4,5,7";
4+
var r = a.join("->");
5+
assert (r =="1->2->4->5->7", "r = " + r);
6+
result = a.join()=="1,2,4,5,7";

0 commit comments

Comments
 (0)