Skip to content

Instantly share code, notes, and snippets.

@bfitch
Last active April 12, 2016 16:12
Show Gist options
  • Save bfitch/7e29c6af29353b8855a47d547be73175 to your computer and use it in GitHub Desktop.
Save bfitch/7e29c6af29353b8855a47d547be73175 to your computer and use it in GitHub Desktop.
var baobab = new Baobab({
todos: [{id: 1, title: 'boo'}, {id: 2, title: 'boo'}],
currentUser: { first_name: 'boo'}
});
// unsetting (deleting) by query
setWhere('todos', {title: 'boo'}); // unsets any object with title 'boo'
setWhere('currentUser', {first_name: 'boo'}); // if the object's first name is 'boo' sets currentUser to null
//setting by query
setWhere('todos', {title: 'boo'}, {completed: true}); // sets completed: true on any object with title 'boo'
setWhere('currentUser', {first_name: 'boo'}, {isAdmin: true}); // if currentUser's first name is 'boo', sets isAdmin to true
baobab.get() // output:
{
"todos": [
{
"id": 1,
"title": "boo",
"completed": true
},
{
"id": 2,
"title": "boo",
"completed": true
}
],
"currentUser": {
"first_name": "boo",
"isAdmin": true
}
}
// setters
function setWhere(path, attrs, newAttrs = null) {
const key = Object.keys(attrs).pop();
const value = attrs[key]
const cursor = baobab.select(path);
if (Array.isArray(cursor.get())) {
setCollection(cursor, key, value, newAttrs);
} else {
setObject(cursor, key, value, newAttrs);
}
}
function setObject(cursor, key, value, newAttrs) {
if (cursor.get()[key]) {
!newAttrs ? cursor.set(null) : cursor.deepMerge(newAttrs);
}
}
function setCollection(collection, key, value, newAttrs) {
const items = collection.get().filter(item => item[key] === value);
const indices = items.map(item => collection.get().indexOf(item));
indices.forEach(i => {
if (!newAttrs) {
items.map(item => collection.unset(collection.get().indexOf(item)));
} else {
collection.splice([i, 1, Object.assign({}, items[i], newAttrs)]);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment