Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
 - test case for regular access of a list and object using 'at'
 - implementation of flow which detects our of bound error
   when using 'at' to access a lists element by its index
  • Loading branch information
Dastin.Sandura committed Oct 24, 2020
1 parent 31545c4 commit a267080
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
28 changes: 24 additions & 4 deletions src/askvm/resources/core/__tests__/at.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,15 @@ function ask(code: string) {
}

describe(`at`, function () {
it(`should throw when trying to access undefined property`, async function () {
it(`Should retrieve a defined property from an object.`, async function () {
await expect(
ask(
`ask(const('cocoObject',object('title','Coco')),call(get('at'),get('cocoObject'),'title'))`
)
).resolves.toStrictEqual(`Coco`);
});

it(`Should throw when trying to access an undefined property of an object.`, async function () {
await expect(
ask(
`ask(const('myobject',object('title','Coco')),call(get('at'),get('myobject'),'description'))`
Expand All @@ -26,9 +34,21 @@ describe(`at`, function () {
);
});

it(`should throw when accessing index which is out of lists bounds.`, async function () {
it(`Should retrieve an element from a list.`, async function () {
await expect(
ask(
`ask(const('yummyList',list('Coco','Papaya','Mango')),call(get('at'),get('yummyList'),0))`
)
).resolves.toStrictEqual(`Coco`);
});

it(`Should throw when accessing index which is out of lists bounds.`, async function () {
await expect(
ask(`ask(const('myarray',array(1,2,3)),call(get('at'),get('myarray'),3))`)
).rejects.toThrow(`Index out of bounds mate.`);
ask(
`ask(const('yummyList',list('coco','papaya','mango')),call(get('at'),get('yummyList'),3))`
)
).rejects.toThrow(
`Sorry, but index 3 is out of bounds for a list with 3 elements.`
);
});
});
16 changes: 12 additions & 4 deletions src/askvm/resources/core/at.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ import { any, resource, typed } from '../../lib';
export const at = resource({
type: any,
async resolver(listOrObject: any, key: any): Promise<any> {
// TODO what is list comes as listOrObject
// if the requested index is out of bounds, then 'out of bounds' error should be thrown
if (
Array.isArray(listOrObject) &&
Number.isInteger(key) &&
listOrObject.length <= key
)
throw Error(
'Sorry, but index ' +
key +
' is out of bounds for a list with ' +
listOrObject.length +
' elements.'
);

if (Array.isArray(listOrObject) && listOrObject.length < 0 + key)
throw Error('Index out of bounds.');
if (
listOrObject !== null &&
typeof listOrObject === 'object' &&
Expand Down

0 comments on commit a267080

Please sign in to comment.