Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Iterating over hashes.
Implement nqp::iterval, nqp::iterkey_s.
.key and .value missing.
  • Loading branch information
pmurias committed Sep 16, 2014
1 parent 1c41a1e commit e6ef35a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/vm/js/QAST/Compiler.nqp
Expand Up @@ -438,7 +438,10 @@ class QAST::OperationsJS {
add_sideffect_op('pop', $T_OBJ, [$T_OBJ], sub ($array) {"$array.pop()"});
add_sideffect_op('push', $T_OBJ, [$T_OBJ, $T_OBJ], sub ($array, $elem) {"$array.push($elem)"});

add_simple_op('iterator', $T_OBJ, [$T_OBJ], sub ($array) {"nqp.op.iterator($array)"});
add_sideffect_op('iterator', $T_OBJ, [$T_OBJ], sub ($array) {"nqp.op.iterator($array)"});

add_simple_op('iterval', $T_OBJ, [$T_OBJ], sub ($iter) {"$iter.iterval()"});
add_simple_op('iterkey_s', $T_STR, [$T_OBJ], sub ($iter) {"$iter.iterkey_s()"});

add_simple_op('existskey', $T_BOOL, [$T_OBJ, $T_STR], sub ($hash, $key) {"$hash.hasOwnProperty($key)"});

Expand Down
38 changes: 35 additions & 3 deletions src/vm/js/nqp-runtime/runtime.js
Expand Up @@ -79,8 +79,39 @@ Iter.prototype.shift = function() {
return this.array[this.idx++];
};

op.iterator = function(array) {
return new Iter(array);
function HashIter(hash) {
this.hash = hash;
this.keys = Object.keys(hash);
this.target = this.keys.length;
this.idx = 0;
}

HashIter.prototype.shift = function() {
return new IterPair(this.hash,this.keys[this.idx++]);
};

function IterPair(hash, key) {
this.key = key;
this.hash = hash;
}

IterPair.prototype.iterval = function() {
return this.hash[this.key];
};
IterPair.prototype.iterkey_s = function() {
return this.key;
};


op.iterator = function(obj) {
if (obj instanceof Array) {
return new Iter(obj);
} else if (obj instanceof Hash) {
console.log(obj);
return new HashIter(obj);
} else {
throw "unsupported thing to iterate over";
}
};

exports.to_str = function(arg) {
Expand All @@ -103,6 +134,7 @@ exports.to_num = function(arg) {
} else if (arg instanceof Array) {
return arg.length;
} else {
console.log(arg);
throw "Can't convert to num";
}
};
Expand All @@ -122,7 +154,7 @@ exports.to_bool = function(arg) {
return arg == '' || arg == '0' ? 0 : 1;
} else if (arg instanceof Array) {
return arg.length == 0 ? 0 : 1;
} else if (arg instanceof Iter) {
} else if (arg instanceof Iter || arg instanceof HashIter) {
return arg.idx < arg.target;
} else if (arg === undefined) {
return 0;
Expand Down

0 comments on commit e6ef35a

Please sign in to comment.