Skip to content

Commit

Permalink
feat: support index in array.map
Browse files Browse the repository at this point in the history
  • Loading branch information
meixg committed Oct 23, 2019
1 parent af7dcf2 commit f93d0ba
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
27 changes: 24 additions & 3 deletions src/features/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,18 @@ import {
EmitHint,
isPropertyAccessExpression,
isCallExpression,
isIdentifier
isIdentifier,
CallExpression,
PropertyAccessExpression,
createNodeArray,
ListFormat,
FunctionLike,
createCall,
createIdentifier
} from 'typescript';

import method from '../utilities/method';
import method, {formatMethodName} from '../utilities/method';


const map = {
push: method('array_push', true, 1),
Expand All @@ -20,7 +28,20 @@ const map = {
concat: method('array_merge', true),
reverse: method('array_reverse', true),
splice: method('array_splice', true),
map: method('array_map', false, 1, true),
map(node: CallExpression, {emitExpressionList, writePunctuation}, {helperNamespace}) {
let expNode = node.expression as PropertyAccessExpression;
let postList = [expNode.expression];
writePunctuation(formatMethodName('array_map', helperNamespace));
if ((node.arguments[0] as FunctionLike).parameters.length > 1) {
postList.push(createCall(
createIdentifier('array_keys'),
undefined,
[expNode.expression]
));
}
const args = createNodeArray([node.arguments[0], ...postList]);
emitExpressionList(node, args, ListFormat.CallExpressionArguments);
},
forEach: method('array_walk', true, 1),
every: method('%helper::array_every', true, 1),
some: method('%helper::array_some', true, 1),
Expand Down
8 changes: 7 additions & 1 deletion test/features/ArrayApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@
$c = count($b);
array_push($b, $c);
$d = \Ts2Php_Helper::array_pos(1, $b);
$f = array_map(function ($value, $index) {
$f = array_map(function ($value) {
return $value;
}, $b);
$h = array_map(function ($value, $index) {
return array(
"value" => $value,
"index" => $index
);
}, $b, array_keys($b));
$e = array_walk($b, function ($value, $index) {
$a = $value;
});
Expand Down
8 changes: 7 additions & 1 deletion test/features/ArrayApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ const b = [1, 'a'];
const c = b.length;
b.push(c);
const d = b.indexOf(1);
const f = b.map(function (value, index) {
const f = b.map(function (value) {
return value;
});
const h = b.map(function (value, index) {
return {
value,
index
};
});
const e = b.forEach(function (value, index) {
let a = value;
});
Expand Down

0 comments on commit f93d0ba

Please sign in to comment.