Skip to content

Commit 8229f78

Browse files
committed
[js] Optimize boolification.
1 parent 0062c15 commit 8229f78

File tree

3 files changed

+19
-22
lines changed

3 files changed

+19
-22
lines changed

src/vm/js/Compiler.nqp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,11 +536,13 @@ class QAST::CompilerJS does DWIMYNameMangling does SerializeOnce {
536536
}
537537

538538
if $got == $T_OBJ {
539+
if $desired == $T_BOOL {
540+
return Chunk.new($desired, "{$chunk.expr}.\$\$decont($*CTX).\$\$toBool($*CTX)", [$chunk]);
541+
}
539542
my %convert;
540543
%convert{$T_STR} := 'toStr';
541544
%convert{$T_NUM} := 'toNum';
542545
%convert{$T_INT} := 'toInt';
543-
%convert{$T_BOOL} := 'toBool';
544546
return Chunk.new($desired, 'nqp.' ~ %convert{$desired} ~ '(' ~ $chunk.expr ~ ", {$*CTX})", [$chunk]);
545547
}
546548

src/vm/js/nqp-runtime/null.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,8 @@ class Null {
33
$$decont(ctx) {
44
return this;
55
}
6+
$$toBool(ctx) {
7+
return 0;
8+
}
69
};
710
module.exports = new Null();

src/vm/js/nqp-runtime/runtime.js

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -195,27 +195,6 @@ exports.toInt = function(arg, ctx) {
195195
}
196196
};
197197

198-
exports.toBool = function(maybeContainer, ctx) {
199-
if (maybeContainer == Null) {
200-
return 0;
201-
}
202-
var value = maybeContainer.$$decont ? maybeContainer.$$decont(ctx) : maybeContainer;
203-
if (typeof value == 'number') {
204-
return value ? 1 : 0;
205-
} else if (typeof value == 'string') {
206-
return value == '' ? 0 : 1;
207-
} else if (value == Null) {
208-
return 0;
209-
} else if (value.$$toBool) {
210-
return value.$$toBool(ctx);
211-
} else if (typeof value == 'function') {
212-
// needed for continuations
213-
return 1;
214-
} else {
215-
throw "Can't decide if value is true";
216-
}
217-
};
218-
219198
exports.intToObj = function(hllName, i) {
220199
var currentHLL = hll.hllConfigs[hllName];
221200
var type;
@@ -391,10 +370,23 @@ Number.prototype.$$decont = function(ctx) {
391370
return this;
392371
};
393372

373+
Number.prototype.$$toBool = function(ctx) {
374+
return this === 0 ? 0 : 1;
375+
};
376+
394377
String.prototype.$$decont = function(ctx) {
395378
return this;
396379
};
397380

381+
String.prototype.$$toBool = function(ctx) {
382+
return this === '' ? 0 : 1;
383+
};
384+
385+
// needed for continuations
386+
Function.prototype.$$toBool = function(ctx) {
387+
return 1;
388+
};
389+
398390

399391
exports.null_s = null_s;
400392
exports.Null = Null;

0 commit comments

Comments
 (0)