realm-js/lib/lists.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

'use strict';
2015-10-06 19:36:56 +00:00
let rpc = require('./rpc');
2015-10-08 00:08:19 +00:00
let util = require('./util');
let idKey = util.idKey;
let realmKey = util.realmKey;
let resizeListKey = util.resizeListKey;
let prototype = {};
exports.create = create;
[
'pop',
'shift',
'push',
'unshift',
'splice',
].forEach(function(name) {
Object.defineProperty(prototype, name, {
value: function() {
let listId = this[idKey];
let realmId = this[realmKey];
if (!listId || !realmId) {
throw new TypeError(name + ' method was not called on a List!');
}
let result = rpc.callListMethod(realmId, listId, name, Array.from(arguments));
this[resizeListKey]();
return result;
}
});
});
function create(realmId, info) {
let list = util.createList(prototype, getterForLength, getterForIndex, setterForIndex);
let size = info.size;
list[realmKey] = realmId;
list[idKey] = info.id;
list[resizeListKey](size);
2015-10-08 00:08:19 +00:00
return list;
}
2015-10-08 00:08:19 +00:00
function getterForLength() {
return rpc.getListSize(this[realmKey], this[idKey]);
}
function getterForIndex(index) {
return function() {
2015-10-08 22:32:14 +00:00
return rpc.getListItem(this[realmKey], this[idKey], index);
};
}
function setterForIndex(index) {
return function(value) {
rpc.setListItem(this[realmKey], this[idKey], index, value);
};
}