Skip to content

Commit

Permalink
feat: array access & object access
Browse files Browse the repository at this point in the history
  • Loading branch information
arlac77 committed Jan 4, 2017
1 parent 77807b6 commit 9bd5c9e
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
31 changes: 29 additions & 2 deletions src/grammar.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,32 @@ import {
}
from './functions';

function Error(error) {
return createValue(Promise.reject(error));
}

class AST {
get value() {
return undefined;
}
}

function Error(error) {
return createValue(Promise.reject(error));
class ArrayAccess extends AST {
constructor(array, index) {
super();
Object.defineProperty(this, 'value', {
get: () => array.value[index.value]
});
}
}

class ObjectAccess extends AST {
constructor(object, attribute) {
super();
Object.defineProperty(this, 'value', {
get: () => object.value[attribute.value]
});
}
}

class BinOP extends AST {
Expand Down Expand Up @@ -118,6 +136,15 @@ export const grammar = create({
}
},
infix: {
'.': {
precedence: 1,
combine: (left, right) => new ObjectAccess(left, right)
},
'[': {
precedence: 1,
combine: (left, right) => new ArrayAccess(left, right)
},
']': {},
',': {},
')': {},
'+': {
Expand Down
28 changes: 28 additions & 0 deletions tests/simple_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,32 @@ describe('expander', () => {
it('include missing', () => expand("${include('fixtures/missing.json')}").catch(e => assert.equal(e.message,
'ENOENT: no such file or directory, open \'/fixtures/missing.json\'')));
});

describe('arrays', () => {
it('access', () => expand("${myArray[2-1]}", {
constants: {
myArray: ['a', 'b', 'c'],
}
}).then(r => assert.equal(r, 'b')));
});

describe('object paths', () => {
it('access one level', () => expand("${myObject.att1}", {
constants: {
myObject: {
att1: 'val1'
},
}
}).then(r => assert.equal(r, 'val1')));

it('access several levels', () => expand("${myObject.level1.level2}", {
constants: {
myObject: {
level1: {
level2: 'val1'
}
},
}
}).then(r => assert.equal(r, 'val1')));
});
});

0 comments on commit 9bd5c9e

Please sign in to comment.