0.1.0 • Published 6 years ago
databranch v0.1.0
JavaScript - DataBranch
A cross-brwoser data mapping tool for JavaScript.
Install
npm
It's recommended to install it as dependency.
npm install --save databranch
browser
Download the databranch.min.js
file and include it in your HTML.
<script src="path/to/src/databranch.min.js"></script>
Usage
CommonJS
var DataBranch = require('databranch');
var data = new DataBranch();
Browser
<!--<script src="path/to/src/databranch.min.js"></script>-->
<script>
var data = new DataBranch();
</script>
API
The examples below will use the functions and variables defined below:
var data = new DataBranch();
var arrInst = new Array(1, 2, 3);
var aNull = null;
.set(key, val)
Sets a new key-value pair.
key
can be anything except undefined
. val
can be anything.
data.set(document, document.body);
data.set('hello', 'world');
data.set(0, 1);
data.set(arrInst, ['a', 'b', 'c']);
data.set(aNull, null);
/* OR */
// Methods can be chained
data.set(document, document.body).set('hello', 'world').set(...);
.has(key)
DataBranch compares key
using .indexOf
under the hood. In other words, key
must return true
using ===
in order to match.
data.has(document); // true
data.has('hello'); // true
data.has('0'); // false, 0 !== '0'
data.has(arrInst); // true
data.has([1, 2, 3]); // false, arrInst !== [1, 2, 3]
data.has(null); // true, aNull === null
.get(key)
data.get(document); // => <body>...</body>
data.get('hello'); // => 'world'
data.get('0'); // => null
data.get(arrInst); // => ['a', 'b', 'c']
data.get([1, 2, 3]); // => null
data.get(null); // => null
.branch(id)
Creates a branch with id
identifier.
data.branch(true);
/* Equals to */
data.set(true, new DataBranch());
It returns the newly created branch. Therefore, you can chain methods to it.
data.branch(true).set(false, '!1');
data.get(true).get(false);
// => '!1'
.of(branch)
To retrieve branch.
data.of(true).get(false);
// => '!1'
The difference between .of
and .get
is that .of
only gets a branch for you and throw if the branch is not found.
data.of(document);
// => Uncaught TypeError: Value of this ID is not a DataBranch branch.
data.of('nonExistentKey');
// => Uncaught ReferenceError: Branch of this ID does not exist.
.size
data.size
// => 6
.delete(key)
data.get(true);
// => DataBranch {...}
data.delete(true);
data.get(true);
// => null
data.size
// => 5
Note: Deleting key/branch will remove all its children data.
.clear()
data.clear();
data.size;
// => 0
0.1.0
6 years ago