Skip to content

Commit

Permalink
feat(sdk): adding set() method to mutarray (#3838)
Browse files Browse the repository at this point in the history
Adding a mutarray set method to change array values. Now setting values can be done with;
```ts
let x = MutArray<num>[2, 3];
x.set(1, 4); // changes x to [2, 4]
```

closes #3832

## Checklist

- [x] Title matches [Winglang's style guide](https://www.winglang.io/contributing/start-here/pull_requests#how-are-pull-request-titles-formatted)
- [x] Description explains motivation and solution
- [x] Tests added (always)
- [x] Docs updated (only required for features)
- [ ] Added `pr/e2e-full` label if this feature requires end-to-end testing

*By submitting this pull request, I confirm that my contribution is made under the terms of the [Wing Cloud Contribution License](https://github.com/winglang/wing/blob/main/CONTRIBUTION_LICENSE.md)*.
  • Loading branch information
WeepingClown13 authored Aug 17, 2023
1 parent 34f3175 commit d980a25
Show file tree
Hide file tree
Showing 5 changed files with 207 additions and 2 deletions.
25 changes: 25 additions & 0 deletions docs/docs/04-standard-library/02-std/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,7 @@ Mutable Array.
| <code><a href="#@winglang/sdk.std.MutArray.lastIndexOf">lastIndexOf</a></code> | Returns the index of the last occurrence of searchElement found. |
| <code><a href="#@winglang/sdk.std.MutArray.pop">pop</a></code> | Remove value from end of array. |
| <code><a href="#@winglang/sdk.std.MutArray.push">push</a></code> | Add value to end of array. |
| <code><a href="#@winglang/sdk.std.MutArray.set">set</a></code> | Sets a new value at the given index of an array. |

---

Expand Down Expand Up @@ -1233,6 +1234,30 @@ value to add.

---

##### `set` <a name="set" id="@winglang/sdk.std.MutArray.set"></a>

```wing
set(index: num, value: <T>): void
```

Sets a new value at the given index of an array.

###### `index`<sup>Required</sup> <a name="index" id="@winglang/sdk.std.MutArray.set.parameter.index"></a>

- *Type:* num

the index to set the value at.

---

###### `value`<sup>Required</sup> <a name="value" id="@winglang/sdk.std.MutArray.set.parameter.value"></a>

- *Type:* <a href="#@winglang/sdk.std.T1">&lt;T&gt;</a>

the value to set at the given index.

---


#### Properties <a name="Properties" id="Properties"></a>

Expand Down
30 changes: 30 additions & 0 deletions examples/tests/sdk_tests/std/array.w
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,33 @@ test "lastIndexOf()" {

assert(s.lastIndexOf("something") == -1);
}

//-----------------------------------------------------------------------------
// set()

test "set()" {
let assertThrows = (expected: str, block: (): void) => {
let var error = false;
try {
block();
} catch actual {
assert(actual == expected);
error = true;
}
assert(error);
};

let INDEX_OUT_OF_BOUNDS_ERROR = "Index out of bounds";
let mutArr = MutArray<num>[1, 3, 5, 7, 9];

assert(mutArr.at(0) == 1);
mutArr.set(0, 2);
assert(mutArr.at(0) == 2);

assertThrows(INDEX_OUT_OF_BOUNDS_ERROR, () => {
mutArr.set(-1, 1);
});
assertThrows(INDEX_OUT_OF_BOUNDS_ERROR, () => {
mutArr.set(5, 11);
});
}
15 changes: 15 additions & 0 deletions libs/wingsdk/src/std/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,4 +249,19 @@ export class MutArray {
public pop(): T1 {
throw new Error("Abstract");
}

/**
* Sets a new value at the given index of an array
*
* @macro ((obj, args) => { if (args[0] < 0 || args[0] >= $self$.length) throw new Error("Index out of bounds"); obj[args[0]] = args[1]; })($self$, [$args$])
*
* @param index the index to set the value at
* @param value the value to set at the given index
* @throws index out of bounds error if the given index does not exist for the array
*/
public set(index: number, value: T1): void {
index;
value;
throw new Error("Macro");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,49 @@ module.exports = function({ }) {

```

## inflight.$Closure14-1.js
```js
module.exports = function({ }) {
class $Closure14 {
constructor({ }) {
const $obj = (...args) => this.handle(...args);
Object.setPrototypeOf($obj, this);
return $obj;
}
async handle() {
const assertThrows = async (expected, block) => {
let error = false;
try {
(await block());
}
catch ($error_actual) {
const actual = $error_actual.message;
{((cond) => {if (!cond) throw new Error("assertion failed: actual == expected")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(actual,expected)))};
error = true;
}
{((cond) => {if (!cond) throw new Error("assertion failed: error")})(error)};
}
;
const INDEX_OUT_OF_BOUNDS_ERROR = "Index out of bounds";
const mutArr = [1, 3, 5, 7, 9];
{((cond) => {if (!cond) throw new Error("assertion failed: mutArr.at(0) == 1")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })((await mutArr.at(0)),1)))};
((obj, args) => { if (args[0] < 0 || args[0] >= mutArr.length) throw new Error("Index out of bounds"); obj[args[0]] = args[1]; })(mutArr, [0,2]);
{((cond) => {if (!cond) throw new Error("assertion failed: mutArr.at(0) == 2")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })((await mutArr.at(0)),2)))};
(await assertThrows(INDEX_OUT_OF_BOUNDS_ERROR,async () => {
((obj, args) => { if (args[0] < 0 || args[0] >= mutArr.length) throw new Error("Index out of bounds"); obj[args[0]] = args[1]; })(mutArr, [(-1),1]);
}
));
(await assertThrows(INDEX_OUT_OF_BOUNDS_ERROR,async () => {
((obj, args) => { if (args[0] < 0 || args[0] >= mutArr.length) throw new Error("Index out of bounds"); obj[args[0]] = args[1]; })(mutArr, [5,11]);
}
));
}
}
return $Closure14;
}

```

## inflight.$Closure2-1.js
```js
module.exports = function({ }) {
Expand Down Expand Up @@ -304,7 +347,7 @@ module.exports = function({ }) {
},
"output": {
"WING_TEST_RUNNER_FUNCTION_ARNS": {
"value": "[[\"root/Default/Default/test:length\",\"${aws_lambda_function.testlength_Handler_BFD8933F.arn}\"],[\"root/Default/Default/test:at()\",\"${aws_lambda_function.testat_Handler_E4F013BC.arn}\"],[\"root/Default/Default/test:pushAndPop()\",\"${aws_lambda_function.testpushAndPop_Handler_EAC0C8FF.arn}\"],[\"root/Default/Default/test:concatMutArray()\",\"${aws_lambda_function.testconcatMutArray_Handler_40D88E89.arn}\"],[\"root/Default/Default/test:concatArray()\",\"${aws_lambda_function.testconcatArray_Handler_F66848AE.arn}\"],[\"root/Default/Default/test:contains()\",\"${aws_lambda_function.testcontains_Handler_F60865D9.arn}\"],[\"root/Default/Default/test:indexOf()\",\"${aws_lambda_function.testindexOf_Handler_BD91EA6F.arn}\"],[\"root/Default/Default/test:indexOfArray()\",\"${aws_lambda_function.testindexOfArray_Handler_DB3A81F5.arn}\"],[\"root/Default/Default/test:join()\",\"${aws_lambda_function.testjoin_Handler_6AC62A8E.arn}\"],[\"root/Default/Default/test:joinWithDefaultSeparator()\",\"${aws_lambda_function.testjoinWithDefaultSeparator_Handler_7AE1258D.arn}\"],[\"root/Default/Default/test:copy()\",\"${aws_lambda_function.testcopy_Handler_27A14A0E.arn}\"],[\"root/Default/Default/test:copyMut()\",\"${aws_lambda_function.testcopyMut_Handler_851E24B4.arn}\"],[\"root/Default/Default/test:lastIndexOf()\",\"${aws_lambda_function.testlastIndexOf_Handler_FFB2061F.arn}\"]]"
"value": "[[\"root/Default/Default/test:length\",\"${aws_lambda_function.testlength_Handler_BFD8933F.arn}\"],[\"root/Default/Default/test:at()\",\"${aws_lambda_function.testat_Handler_E4F013BC.arn}\"],[\"root/Default/Default/test:pushAndPop()\",\"${aws_lambda_function.testpushAndPop_Handler_EAC0C8FF.arn}\"],[\"root/Default/Default/test:concatMutArray()\",\"${aws_lambda_function.testconcatMutArray_Handler_40D88E89.arn}\"],[\"root/Default/Default/test:concatArray()\",\"${aws_lambda_function.testconcatArray_Handler_F66848AE.arn}\"],[\"root/Default/Default/test:contains()\",\"${aws_lambda_function.testcontains_Handler_F60865D9.arn}\"],[\"root/Default/Default/test:indexOf()\",\"${aws_lambda_function.testindexOf_Handler_BD91EA6F.arn}\"],[\"root/Default/Default/test:indexOfArray()\",\"${aws_lambda_function.testindexOfArray_Handler_DB3A81F5.arn}\"],[\"root/Default/Default/test:join()\",\"${aws_lambda_function.testjoin_Handler_6AC62A8E.arn}\"],[\"root/Default/Default/test:joinWithDefaultSeparator()\",\"${aws_lambda_function.testjoinWithDefaultSeparator_Handler_7AE1258D.arn}\"],[\"root/Default/Default/test:copy()\",\"${aws_lambda_function.testcopy_Handler_27A14A0E.arn}\"],[\"root/Default/Default/test:copyMut()\",\"${aws_lambda_function.testcopyMut_Handler_851E24B4.arn}\"],[\"root/Default/Default/test:lastIndexOf()\",\"${aws_lambda_function.testlastIndexOf_Handler_FFB2061F.arn}\"],[\"root/Default/Default/test:set()\",\"${aws_lambda_function.testset_Handler_ADDF1A01.arn}\"]]"
}
},
"provider": {
Expand Down Expand Up @@ -430,6 +473,15 @@ module.exports = function({ }) {
}
},
"assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}"
},
"testset_Handler_IamRole_B9B79227": {
"//": {
"metadata": {
"path": "root/Default/Default/test:set()/Handler/IamRole",
"uniqueId": "testset_Handler_IamRole_B9B79227"
}
},
"assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},\"Effect\":\"Allow\"}]}"
}
},
"aws_iam_role_policy": {
Expand Down Expand Up @@ -562,6 +614,16 @@ module.exports = function({ }) {
},
"policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}",
"role": "${aws_iam_role.testpushAndPop_Handler_IamRole_5F6E6E00.name}"
},
"testset_Handler_IamRolePolicy_ADE48415": {
"//": {
"metadata": {
"path": "root/Default/Default/test:set()/Handler/IamRolePolicy",
"uniqueId": "testset_Handler_IamRolePolicy_ADE48415"
}
},
"policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"none:null\",\"Resource\":\"*\"}]}",
"role": "${aws_iam_role.testset_Handler_IamRole_B9B79227.name}"
}
},
"aws_iam_role_policy_attachment": {
Expand Down Expand Up @@ -694,6 +756,16 @@ module.exports = function({ }) {
},
"policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
"role": "${aws_iam_role.testpushAndPop_Handler_IamRole_5F6E6E00.name}"
},
"testset_Handler_IamRolePolicyAttachment_58805670": {
"//": {
"metadata": {
"path": "root/Default/Default/test:set()/Handler/IamRolePolicyAttachment",
"uniqueId": "testset_Handler_IamRolePolicyAttachment_58805670"
}
},
"policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
"role": "${aws_iam_role.testset_Handler_IamRole_B9B79227.name}"
}
},
"aws_lambda_function": {
Expand Down Expand Up @@ -1034,6 +1106,32 @@ module.exports = function({ }) {
"security_group_ids": [],
"subnet_ids": []
}
},
"testset_Handler_ADDF1A01": {
"//": {
"metadata": {
"path": "root/Default/Default/test:set()/Handler/Default",
"uniqueId": "testset_Handler_ADDF1A01"
}
},
"environment": {
"variables": {
"WING_FUNCTION_NAME": "Handler-c8240bc7",
"WING_TARGET": "tf-aws"
}
},
"function_name": "Handler-c8240bc7",
"handler": "index.handler",
"publish": true,
"role": "${aws_iam_role.testset_Handler_IamRole_B9B79227.arn}",
"runtime": "nodejs18.x",
"s3_bucket": "${aws_s3_bucket.Code.bucket}",
"s3_key": "${aws_s3_object.testset_Handler_S3Object_A8FBF518.key}",
"timeout": 30,
"vpc_config": {
"security_group_ids": [],
"subnet_ids": []
}
}
},
"aws_s3_bucket": {
Expand Down Expand Up @@ -1311,6 +1409,17 @@ module.exports = function({ }) {
"bucket": "${aws_s3_bucket.Code.bucket}",
"key": "<ASSET_KEY>",
"source": "<ASSET_SOURCE>"
},
"testset_Handler_S3Object_A8FBF518": {
"//": {
"metadata": {
"path": "root/Default/Default/test:set()/Handler/S3Object",
"uniqueId": "testset_Handler_S3Object_A8FBF518"
}
},
"bucket": "${aws_s3_bucket.Code.bucket}",
"key": "<ASSET_KEY>",
"source": "<ASSET_SOURCE>"
}
}
}
Expand Down Expand Up @@ -1639,6 +1748,30 @@ class $Root extends $stdlib.std.Resource {
`);
}
}
class $Closure14 extends $stdlib.std.Resource {
constructor(scope, id, ) {
super(scope, id);
this._addInflightOps("handle", "$inflight_init");
this.display.hidden = true;
}
static _toInflightType(context) {
return $stdlib.core.NodeJsCode.fromInline(`
require("./inflight.$Closure14-1.js")({
})
`);
}
_toInflight() {
return $stdlib.core.NodeJsCode.fromInline(`
(await (async () => {
const $Closure14Client = ${$Closure14._toInflightType(this).text};
const client = new $Closure14Client({
});
if (client.$inflight_init) { await client.$inflight_init(); }
return client;
})())
`);
}
}
const bucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"myBucket");
const buckets = [bucket];
const anotherBucket = this.node.root.newAbstract("@winglang/sdk.cloud.Bucket",this,"mySecondBucket");
Expand Down Expand Up @@ -1733,6 +1866,7 @@ class $Root extends $stdlib.std.Resource {
{((cond) => {if (!cond) throw new Error("assertion failed: multipleBuckets.lastIndexOf(bucket) == 1")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(multipleBuckets.lastIndexOf(bucket),1)))};
{((cond) => {if (!cond) throw new Error("assertion failed: multipleBuckets.lastIndexOf(dummyBucket) == -1")})((((a,b) => { try { return require('assert').deepStrictEqual(a,b) === undefined; } catch { return false; } })(multipleBuckets.lastIndexOf(dummyBucket),(-1))))};
this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:lastIndexOf()",new $Closure13(this,"$Closure13"));
this.node.root.new("@winglang/sdk.std.Test",std.Test,this,"test:set()",new $Closure14(this,"$Closure14"));
}
}
const $App = $stdlib.core.App.for(process.env.WING_TARGET);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pass ─ array.wsim » root/env1/test:at()
pass ─ array.wsim » root/env10/test:copy()
pass ─ array.wsim » root/env11/test:copyMut()
pass ─ array.wsim » root/env12/test:lastIndexOf()
pass ─ array.wsim » root/env13/test:set()
pass ─ array.wsim » root/env2/test:pushAndPop()
pass ─ array.wsim » root/env3/test:concatMutArray()
pass ─ array.wsim » root/env4/test:concatArray()
Expand All @@ -17,7 +18,7 @@ pass ─ array.wsim » root/env8/test:join()
pass ─ array.wsim » root/env9/test:joinWithDefaultSeparator()
Tests 13 passed (13)
Tests 14 passed (14)
Test Files 1 passed (1)
Duration <DURATION>
```
Expand Down

0 comments on commit d980a25

Please sign in to comment.