Skip to content

Commit

Permalink
Merge pull request #124 from mdrewt/issue_123
Browse files Browse the repository at this point in the history
Added support for remove in ArrayList and Map
  • Loading branch information
shepherdwind committed Aug 27, 2019
2 parents 9a9319f + c214d01 commit 9ddb4d7
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/compile/references.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,30 @@ module.exports = function(Velocity, utils) {
return baseRef[this.getLiteral(property.args[0])] = this.getLiteral(property.args[1]);
} else if (id === 'add' && !baseRef[id] && typeof baseRef.push === 'function') {
return baseRef.push(this.getLiteral(property.args[0]));
} else if (id === 'remove') {

if (utils.isArray(baseRef)) {

if (typeof index === 'number') {
var index = this.getLiteral(property.args[0]);
} else {
var index = baseRef.indexOf(this.getLiteral(property.args[0]));
}

ret = baseRef[index];
baseRef.splice(index, 1);
return ret;

} else if (utils.isObject(baseRef)) {

ret = baseRef[this.getLiteral(property.args[0])];
delete baseRef[this.getLiteral(property.args[0])];
return ret;

}

return undefined;

} else if (id === 'subList' && !baseRef[id]) {
return baseRef.slice(this.getLiteral(property.args[0]), this.getLiteral(property.args[1]));
} else {
Expand Down
42 changes: 42 additions & 0 deletions tests/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,48 @@ describe('Compile', function() {
});
});

describe('deletion via .remove', function () {
it('should remove a key from an object', function() {
var vm = `
#set($test = {'foo': 'bar'})
#set($baz = $test.remove('foo'))
$test
`;
var expected = '{}';
assert.equal(render(vm).trim(), expected);
});

it('should return the value of the removed key', function () {
var vm = `
#set($test = {'foo': 'bar'})
#set($baz = $test.remove('foo'))
$baz
`;
var expected = 'bar';
assert.equal(render(vm).trim(), expected);
});

it('should remove a value from an array', function () {
var vm = `
#set($test = ['foo', 'bar'])
#set($baz = $test.remove('bar'))
$test
`;
var expected = '[foo]';
assert.equal(render(vm).trim(), expected);
});

it('should return the removed value', function () {
var vm = `
#set($test = ['foo', 'bar'])
#set($baz = $test.remove('bar'))
$baz
`;
var expected = 'bar';
assert.equal(render(vm).trim(), expected);
});
});

describe('Add into empty array', function () {
it('should add item to array', function() {
var vm = `
Expand Down

0 comments on commit 9ddb4d7

Please sign in to comment.