realm-js/lib/lists.js

70 lines
1.6 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');
2015-10-06 19:36:56 +00:00
let idKey = Symbol();
let realmKey = Symbol();
2015-10-08 00:08:19 +00:00
let prototype = util.createListPrototype(getterForLength, getterForIndex, setterForIndex);
exports.create = create;
[
'pop',
'shift',
'push',
'unshift',
'splice',
].forEach(function(name, i) {
2015-10-06 19:36:56 +00:00
let growthMethod = (i >= 2);
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));
// Since this method might have grown the list, ensure index properties are defined.
if (growthMethod) {
2015-10-08 00:08:19 +00:00
prototype[util.growListPrototypeKey](this.length);
}
return result;
}
});
});
function create(realmId, info) {
let list = Object.create(prototype);
let size = info.size;
list[realmKey] = realmId;
list[idKey] = info.id;
2015-10-08 00:08:19 +00:00
list[util.growListPrototypeKey](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() {
let realmId = this[realmKey];
return rpc.getListItem(realmId, this[idKey], index);
};
}
function setterForIndex(index) {
return function(value) {
rpc.setListItem(this[realmKey], this[idKey], index, value);
};
}