code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function collapseTopology(topology, numPieces) {
var geometries = topology.objects.triangles.geometries,
bisect$$1 = bisector(function (d) { return d.area; }).left;
while (geometries.length > numPieces) {
mergeSmallestFeature();
}
if (numPieces > geometries.length) {
throw new RangeError(
"Can't collapse topology into " + numPieces + " pieces."
);
}
return feature(topology, topology.objects.triangles).features.map(function (f) {
f.geometry.coordinates[0].pop();
return f.geometry.coordinates[0];
});
function mergeSmallestFeature() {
var smallest = geometries[0],
neighborIndex = neighbors(geometries)[0][0],
neighbor = geometries[neighborIndex],
merged = mergeArcs(topology, [smallest, neighbor]);
// MultiPolygon -> Polygon
merged.area = smallest.area + neighbor.area;
merged.type = "Polygon";
merged.arcs = merged.arcs[0];
// Delete smallest and its chosen neighbor
geometries.splice(neighborIndex, 1);
geometries.shift();
// Add new merged shape in sorted order
geometries.splice(bisect$$1(geometries, merged.area), 0, merged);
}
}
|
Compute the curve derivative (hodograph) at t.
|
collapseTopology
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function mergeSmallestFeature() {
var smallest = geometries[0],
neighborIndex = neighbors(geometries)[0][0],
neighbor = geometries[neighborIndex],
merged = mergeArcs(topology, [smallest, neighbor]);
// MultiPolygon -> Polygon
merged.area = smallest.area + neighbor.area;
merged.type = "Polygon";
merged.arcs = merged.arcs[0];
// Delete smallest and its chosen neighbor
geometries.splice(neighborIndex, 1);
geometries.shift();
// Add new merged shape in sorted order
geometries.splice(bisect$$1(geometries, merged.area), 0, merged);
}
|
Compute the curve derivative (hodograph) at t.
|
mergeSmallestFeature
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
triangulate = function(ring, numPieces) {
return collapseTopology(createTopology(cut(ring), ring), numPieces);
}
|
Compute the curve derivative (hodograph) at t.
|
triangulate
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function cut(ring) {
var cuts = earcut_1(
ring.reduce(function (arr, point) { return arr.concat( [point[0]], [point[1]]); }, [])
),
triangles = [];
for (var i = 0, l = cuts.length; i < l; i += 3) {
// Save each triangle as segments [a, b], [b, c], [c, a]
triangles.push([
[cuts[i], cuts[i + 1]],
[cuts[i + 1], cuts[i + 2]],
[cuts[i + 2], cuts[i]]
]);
}
return triangles;
}
|
Compute the curve derivative (hodograph) at t.
|
cut
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
pieceOrder = function(start, end) {
if (start.length > 8) {
return start.map(function (d, i) { return i; });
}
var distances = start.map(function (p1) { return end.map(function (p2) { return squaredDistance(p1, p2); }); });
return bestOrder(start, end, distances);
}
|
Compute the curve derivative (hodograph) at t.
|
pieceOrder
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function bestOrder(start, end, distances) {
var min = Infinity,
best = start.map(function (d, i) { return i; });
function permute(arr, order, sum) {
if ( order === void 0 ) order = [];
if ( sum === void 0 ) sum = 0;
for (var i = 0; i < arr.length; i++) {
var cur = arr.splice(i, 1),
dist = distances[cur[0]][order.length];
if (sum + dist < min) {
if (arr.length) {
permute(arr.slice(), order.concat(cur), sum + dist);
} else {
min = sum + dist;
best = order.concat(cur);
}
}
if (arr.length) {
arr.splice(i, 0, cur[0]);
}
}
}
permute(best);
return best;
}
|
Compute the curve derivative (hodograph) at t.
|
bestOrder
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function permute(arr, order, sum) {
if ( order === void 0 ) order = [];
if ( sum === void 0 ) sum = 0;
for (var i = 0; i < arr.length; i++) {
var cur = arr.splice(i, 1),
dist = distances[cur[0]][order.length];
if (sum + dist < min) {
if (arr.length) {
permute(arr.slice(), order.concat(cur), sum + dist);
} else {
min = sum + dist;
best = order.concat(cur);
}
}
if (arr.length) {
arr.splice(i, 0, cur[0]);
}
}
}
|
Compute the curve derivative (hodograph) at t.
|
permute
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function squaredDistance(p1, p2) {
var d = distance(polygonCentroid$$1(p1), polygonCentroid$$1(p2));
return d * d;
}
|
Compute the curve derivative (hodograph) at t.
|
squaredDistance
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function separate(
fromShape,
toShapes,
ref
) {
if ( ref === void 0 ) ref = {};
var maxSegmentLength = ref.maxSegmentLength; if ( maxSegmentLength === void 0 ) maxSegmentLength = 10;
var string = ref.string; if ( string === void 0 ) string = true;
var single = ref.single; if ( single === void 0 ) single = false;
var fromRing = normalizeRing(fromShape, maxSegmentLength);
if (fromRing.length < toShapes.length + 2) {
addPoints(fromRing, toShapes.length + 2 - fromRing.length);
}
var fromRings = triangulate(fromRing, toShapes.length),
toRings = toShapes.map(function (d) { return normalizeRing(d, maxSegmentLength); }),
t0 = typeof fromShape === "string" && fromShape,
t1;
if (!single || toShapes.every(function (s) { return typeof s === "string"; })) {
t1 = toShapes.slice(0);
}
return interpolateSets(fromRings, toRings, {
match: true,
string: string,
single: single,
t0: t0,
t1: t1
});
}
|
Compute the curve derivative (hodograph) at t.
|
separate
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function combine$1(
fromShapes,
toShape,
ref
) {
if ( ref === void 0 ) ref = {};
var maxSegmentLength = ref.maxSegmentLength; if ( maxSegmentLength === void 0 ) maxSegmentLength = 10;
var string = ref.string; if ( string === void 0 ) string = true;
var single = ref.single; if ( single === void 0 ) single = false;
var interpolators = separate(toShape, fromShapes, {
maxSegmentLength: maxSegmentLength,
string: string,
single: single
});
return single
? function (t) { return interpolators(1 - t); }
: interpolators.map(function (fn) { return function (t) { return fn(1 - t); }; });
}
|
Compute the curve derivative (hodograph) at t.
|
combine$1
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function interpolateAll(
fromShapes,
toShapes,
ref
) {
if ( ref === void 0 ) ref = {};
var maxSegmentLength = ref.maxSegmentLength; if ( maxSegmentLength === void 0 ) maxSegmentLength = 10;
var string = ref.string; if ( string === void 0 ) string = true;
var single = ref.single; if ( single === void 0 ) single = false;
if (
!Array.isArray(fromShapes) ||
!Array.isArray(toShapes) ||
fromShapes.length !== toShapes.length ||
!fromShapes.length
) {
throw new TypeError(INVALID_INPUT_ALL);
}
var normalize = function (s) { return normalizeRing(s, maxSegmentLength); },
fromRings = fromShapes.map(normalize),
toRings = toShapes.map(normalize),
t0,
t1;
if (single) {
if (fromShapes.every(function (s) { return typeof s === "string"; })) {
t0 = fromShapes.slice(0);
}
if (toShapes.every(function (s) { return typeof s === "string"; })) {
t1 = toShapes.slice(0);
}
} else {
t0 = fromShapes.slice(0);
t1 = toShapes.slice(0);
}
return interpolateSets(fromRings, toRings, {
string: string,
single: single,
t0: t0,
t1: t1,
match: false
});
}
|
Compute the curve derivative (hodograph) at t.
|
interpolateAll
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function interpolateSets(
fromRings,
toRings,
ref
) {
if ( ref === void 0 ) ref = {};
var string = ref.string;
var single = ref.single;
var t0 = ref.t0;
var t1 = ref.t1;
var match = ref.match;
var order = match
? pieceOrder(fromRings, toRings)
: fromRings.map(function (d, i) { return i; }),
interpolators = order.map(function (d, i) { return interpolateRing(fromRings[d], toRings[i], string); }
);
if (match && Array.isArray(t0)) {
t0 = order.map(function (d) { return t0[d]; });
}
if (single && string) {
if (Array.isArray(t0)) {
t0 = t0.join(" ");
}
if (Array.isArray(t1)) {
t1 = t1.join(" ");
}
}
if (single) {
var multiInterpolator = string
? function (t) { return interpolators.map(function (fn) { return fn(t); }).join(" "); }
: function (t) { return interpolators.map(function (fn) { return fn(t); }); };
if (string && (t0 || t1)) {
return function (t) { return (t < 1e-4 && t0) || (1 - t < 1e-4 && t1) || multiInterpolator(t); };
}
return multiInterpolator;
} else if (string) {
t0 = Array.isArray(t0) ? t0.map(function (d) { return typeof d === "string" && d; }) : [];
t1 = Array.isArray(t1) ? t1.map(function (d) { return typeof d === "string" && d; }) : [];
return interpolators.map(function (fn, i) {
if (t0[i] || t1[i]) {
return function (t) { return (t < 1e-4 && t0[i]) || (1 - t < 1e-4 && t1[i]) || fn(t); };
}
return fn;
});
}
return interpolators;
}
|
Compute the curve derivative (hodograph) at t.
|
interpolateSets
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function fromCircle(x, y, radius, toShape, options) {
return fromShape(
circlePoints(x, y, radius),
toShape,
circlePath(x, y, radius),
2 * Math.PI * radius,
options
);
}
|
Compute the curve derivative (hodograph) at t.
|
fromCircle
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function toCircle(fromShape, x, y, radius, options) {
var interpolator = fromCircle(x, y, radius, fromShape, options);
return function (t) { return interpolator(1 - t); };
}
|
Compute the curve derivative (hodograph) at t.
|
toCircle
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function fromRect(x, y, width, height, toShape, options) {
return fromShape(
rectPoints(x, y, width, height),
toShape,
rectPath(x, y, width, height),
2 * width + 2 * height,
options
);
}
|
Compute the curve derivative (hodograph) at t.
|
fromRect
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function toRect(fromShape, x, y, width, height, options) {
var interpolator = fromRect(x, y, width, height, fromShape, options);
return function (t) { return interpolator(1 - t); };
}
|
Compute the curve derivative (hodograph) at t.
|
toRect
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function fromShape(
fromFn,
toShape,
original,
perimeter,
ref
) {
if ( ref === void 0 ) ref = {};
var maxSegmentLength = ref.maxSegmentLength; if ( maxSegmentLength === void 0 ) maxSegmentLength = 10;
var string = ref.string; if ( string === void 0 ) string = true;
var toRing = normalizeRing(toShape, maxSegmentLength),
fromRing,
interpolator;
// Enforce maxSegmentLength on circle/rect perimeter too
if (
isFiniteNumber(perimeter) &&
toRing.length < perimeter / maxSegmentLength
) {
addPoints(toRing, Math.ceil(perimeter / maxSegmentLength - toRing.length));
}
fromRing = fromFn(toRing);
interpolator = interpolatePoints(fromRing, toRing, string);
if (string) {
return function (t) { return (t < 1e-4 ? original : interpolator(t)); };
}
return interpolator;
}
|
Compute the curve derivative (hodograph) at t.
|
fromShape
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function circlePoints(x, y, radius) {
return function(ring) {
var centroid = polygonCentroid$$1(ring),
perimeter = polygonLength(ring.concat( [ring[0]])),
startingAngle = Math.atan2(
ring[0][1] - centroid[1],
ring[0][0] - centroid[0]
),
along = 0;
return ring.map(function (point, i) {
var angle;
if (i) {
along += distance(point, ring[i - 1]);
}
angle =
startingAngle +
2 * Math.PI * (perimeter ? along / perimeter : i / ring.length);
return [Math.cos(angle) * radius + x, Math.sin(angle) * radius + y];
});
};
}
|
Compute the curve derivative (hodograph) at t.
|
circlePoints
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function rectPoints(x, y, width, height) {
return function(ring) {
var centroid = polygonCentroid$$1(ring),
perimeter = polygonLength(ring.concat( [ring[0]])),
startingAngle = Math.atan2(
ring[0][1] - centroid[1],
ring[0][0] - centroid[0]
),
along = 0;
if (startingAngle < 0) {
startingAngle = 2 * Math.PI + startingAngle;
}
var startingProgress = startingAngle / (2 * Math.PI);
return ring.map(function (point, i) {
if (i) {
along += distance(point, ring[i - 1]);
}
var relative = rectPoint(
(startingProgress + (perimeter ? along / perimeter : i / ring.length)) %
1
);
return [x + relative[0] * width, y + relative[1] * height];
});
};
}
|
Compute the curve derivative (hodograph) at t.
|
rectPoints
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function rectPoint(progress) {
if (progress <= 1 / 8) {
return [1, 0.5 + progress * 4];
}
if (progress <= 3 / 8) {
return [1.5 - 4 * progress, 1];
}
if (progress <= 5 / 8) {
return [0, 2.5 - 4 * progress];
}
if (progress <= 7 / 8) {
return [4 * progress - 2.5, 0];
}
return [1, 4 * progress - 3.5];
}
|
Compute the curve derivative (hodograph) at t.
|
rectPoint
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function circlePath(x, y, radius) {
var l = x - radius + "," + y,
r = x + radius + "," + y,
pre = "A" + radius + "," + radius + ",0,1,1,";
return "M" + l + pre + r + pre + l + "Z";
}
|
Compute the curve derivative (hodograph) at t.
|
circlePath
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function rectPath(x, y, width, height) {
var r = x + width,
b = y + height;
return (
"M" +
x +
"," +
y +
"L" +
r +
"," +
y +
"L" +
r +
"," +
b +
"L" +
x +
"," +
b +
"Z"
);
}
|
Compute the curve derivative (hodograph) at t.
|
rectPath
|
javascript
|
veltman/flubber
|
build/flubber.js
|
https://github.com/veltman/flubber/blob/master/build/flubber.js
|
MIT
|
function bounceAnimation(direction) {
slider.className = 'bounce-from-' + direction;
setTimeout(function() {
slider.className = '';
}, 400);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
bounceAnimation
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function updateOffset() {
var offset = -currentIndex * 100 + '%';
if (options.animation === 'fadeIn') {
slider.style.opacity = 0;
setTimeout(function() {
supports.transforms ?
slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)'
: slider.style.left = offset;
slider.style.opacity = 1;
}, 400);
} else {
supports.transforms ?
slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)'
: slider.style.left = offset;
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
updateOffset
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function testTransformsSupport() {
var div = create('div');
return typeof div.style.perspective !== 'undefined' || typeof div.style.webkitPerspective !== 'undefined';
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testTransformsSupport
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function testSvgSupport() {
var div = create('div');
div.innerHTML = '<svg/>';
return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testSvgSupport
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function testPassiveEventsSupport() {
var passiveEvents = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
passiveEvents = true;
}
});
window.addEventListener('test', null, opts);
} catch (e) { /* Silence the error and continue */ }
return passiveEvents;
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testPassiveEventsSupport
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function preloadNext(index) {
if (index - currentIndex >= options.preload) {
return;
}
loadImage(index + 1, function() {
preloadNext(index + 1);
});
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
preloadNext
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function preloadPrev(index) {
if (currentIndex - index >= options.preload) {
return;
}
loadImage(index - 1, function() {
preloadPrev(index - 1);
});
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
preloadPrev
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function bind(element, event, callback, options) {
if (element.addEventListener) {
element.addEventListener(event, callback, options);
} else {
// IE8 fallback
element.attachEvent('on' + event, function(event) {
// `event` and `event.target` are not provided in IE8
event = event || window.event;
event.target = event.target || event.srcElement;
callback(event);
});
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
bind
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function unbind(element, event, callback, options) {
if (element.removeEventListener) {
element.removeEventListener(event, callback, options);
} else {
// IE8 fallback
element.detachEvent('on' + event, callback);
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
unbind
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function getByID(id) {
return document.getElementById(id);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
getByID
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function create(element) {
return document.createElement(element);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
create
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function destroyPlugin() {
unbindEvents();
clearCachedData();
unbind(document, 'keydown', keyDownHandler);
document.getElementsByTagName('body')[0].removeChild(document.getElementById('baguetteBox-overlay'));
data = {};
currentGallery = [];
currentIndex = 0;
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
destroyPlugin
|
javascript
|
feimosi/baguetteBox.js
|
dist/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/dist/baguetteBox.js
|
MIT
|
function bounceAnimation(direction) {
slider.className = 'bounce-from-' + direction;
setTimeout(function() {
slider.className = '';
}, 400);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
bounceAnimation
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function updateOffset() {
var isRtl = document.querySelectorAll('html')[0].getAttribute('dir') === 'rtl';
var percentage = isRtl ? -100 : 100;
var offset = -currentIndex * percentage + '%';
if (options.animation === 'fadeIn') {
slider.style.opacity = 0;
setTimeout(function() {
supports.transforms ?
slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)'
: slider.style.left = offset;
slider.style.opacity = 1;
}, 400);
} else {
supports.transforms ?
slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)'
: slider.style.left = offset;
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
updateOffset
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function testTransformsSupport() {
var div = create('div');
return typeof div.style.perspective !== 'undefined' || typeof div.style.webkitPerspective !== 'undefined';
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testTransformsSupport
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function testSvgSupport() {
var div = create('div');
div.innerHTML = '<svg/>';
return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg';
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testSvgSupport
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function testPassiveEventsSupport() {
var passiveEvents = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
passiveEvents = true;
}
});
window.addEventListener('test', null, opts);
} catch (e) { /* Silence the error and continue */ }
return passiveEvents;
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
testPassiveEventsSupport
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function preloadNext(index) {
if (index - currentIndex >= options.preload) {
return;
}
loadImage(index + 1, function() {
preloadNext(index + 1);
});
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
preloadNext
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function preloadPrev(index) {
if (currentIndex - index >= options.preload) {
return;
}
loadImage(index - 1, function() {
preloadPrev(index - 1);
});
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
preloadPrev
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function bind(element, event, callback, options) {
if (element.addEventListener) {
element.addEventListener(event, callback, options);
} else {
// IE8 fallback
element.attachEvent('on' + event, function(event) {
// `event` and `event.target` are not provided in IE8
event = event || window.event;
event.target = event.target || event.srcElement;
callback(event);
});
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
bind
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function unbind(element, event, callback, options) {
if (element.removeEventListener) {
element.removeEventListener(event, callback, options);
} else {
// IE8 fallback
element.detachEvent('on' + event, callback);
}
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
unbind
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function getByID(id) {
return document.getElementById(id);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
getByID
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function create(element) {
return document.createElement(element);
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
create
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function destroyPlugin() {
unbindEvents();
clearCachedData();
unbind(document, 'keydown', keyDownHandler);
document.getElementsByTagName('body')[0].removeChild(document.getElementById('baguetteBox-overlay'));
data = {};
currentGallery = [];
currentIndex = 0;
}
|
Triggers the bounce animation
@param {('left'|'right')} direction - Direction of the movement
|
destroyPlugin
|
javascript
|
feimosi/baguetteBox.js
|
src/baguetteBox.js
|
https://github.com/feimosi/baguetteBox.js/blob/master/src/baguetteBox.js
|
MIT
|
function getRandomArray (n) {
var res = []
, i, j, temp
;
for (i = 0; i < n; i += 1) { res[i] = i; }
for (i = n - 1; i >= 1; i -= 1) {
j = Math.floor((i + 1) * Math.random());
temp = res[i];
res[i] = res[j];
res[j] = temp;
}
return res;
}
|
Return an array with the numbers from 0 to n-1, in a random order
Uses Fisher Yates algorithm
Useful to get fair tests
|
getRandomArray
|
javascript
|
louischatriot/nedb
|
benchmarks/commonUtilities.js
|
https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
|
MIT
|
function runFrom(i) {
if (i === n) { // Finished
var opsPerSecond = Math.floor(1000* n / profiler.elapsedSinceLastStep());
console.log("===== RESULT (insert) ===== " + opsPerSecond + " ops/s");
profiler.step('Finished inserting ' + n + ' docs');
profiler.insertOpsPerSecond = opsPerSecond;
return cb();
}
d.insert({ docNumber: order[i] }, function (err) {
executeAsap(function () {
runFrom(i + 1);
});
});
}
|
Insert a certain number of documents for testing
|
runFrom
|
javascript
|
louischatriot/nedb
|
benchmarks/commonUtilities.js
|
https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
|
MIT
|
function runFrom(i) {
if (i === n) { // Finished
console.log("===== RESULT (find with in selector) ===== " + Math.floor(1000* n / profiler.elapsedSinceLastStep()) + " ops/s");
profiler.step('Finished finding ' + n + ' docs');
return cb();
}
d.find({ docNumber: { $in: ins[i] } }, function (err, docs) {
if (docs.length !== arraySize) { return cb('One find didnt work'); }
executeAsap(function () {
runFrom(i + 1);
});
});
}
|
Find documents with find and the $in operator
|
runFrom
|
javascript
|
louischatriot/nedb
|
benchmarks/commonUtilities.js
|
https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
|
MIT
|
function runFrom(i) {
if (i === n) { // Finished
console.log("===== RESULT (update) ===== " + Math.floor(1000* n / profiler.elapsedSinceLastStep()) + " ops/s");
profiler.step('Finished updating ' + n + ' docs');
return cb();
}
// Will not actually modify the document but will take the same time
d.update({ docNumber: order[i] }, { docNumber: order[i] }, options, function (err, nr) {
if (err) { return cb(err); }
if (nr !== 1) { return cb('One update didnt work'); }
executeAsap(function () {
runFrom(i + 1);
});
});
}
|
Update documents
options is the same as the options object for update
|
runFrom
|
javascript
|
louischatriot/nedb
|
benchmarks/commonUtilities.js
|
https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
|
MIT
|
function runFrom(i) {
if (i === n) { // Finished
// opsPerSecond corresponds to 1 insert + 1 remove, needed to keep collection size at 10,000
// We need to subtract the time taken by one insert to get the time actually taken by one remove
var opsPerSecond = Math.floor(1000 * n / profiler.elapsedSinceLastStep());
var removeOpsPerSecond = Math.floor(1 / ((1 / opsPerSecond) - (1 / profiler.insertOpsPerSecond)))
console.log("===== RESULT (remove) ===== " + removeOpsPerSecond + " ops/s");
profiler.step('Finished removing ' + n + ' docs');
return cb();
}
d.remove({ docNumber: order[i] }, options, function (err, nr) {
if (err) { return cb(err); }
if (nr !== 1) { return cb('One remove didnt work'); }
d.insert({ docNumber: order[i] }, function (err) { // We need to reinsert the doc so that we keep the collection's size at n
// So actually we're calculating the average time taken by one insert + one remove
executeAsap(function () {
runFrom(i + 1);
});
});
});
}
|
Remove documents
options is the same as the options object for update
|
runFrom
|
javascript
|
louischatriot/nedb
|
benchmarks/commonUtilities.js
|
https://github.com/louischatriot/nedb/blob/master/benchmarks/commonUtilities.js
|
MIT
|
function ensureDirExists (name) {
try {
fs.mkdirSync(path.join(__dirname, name));
} catch (e) {
if (e.code !== 'EEXIST') {
console.log("Error ensuring that node_modules exists");
process.exit(1);
}
}
}
|
Build the browser version of nedb
|
ensureDirExists
|
javascript
|
louischatriot/nedb
|
browser-version/build.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/build.js
|
MIT
|
function randomBytes (size) {
var bytes = new Array(size);
var r;
for (var i = 0, r; i < size; i++) {
if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return bytes;
}
|
Taken from the crypto-browserify module
https://github.com/dominictarr/crypto-browserify
NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it
|
randomBytes
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/customUtils.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/customUtils.js
|
MIT
|
function uid (len) {
return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+\/]/g, '').slice(0, len);
}
|
Return a random alphanumerical string of length len
There is a very small probability (less than 1/1,000,000) for the length to be less than len
(il the base64 conversion yields too many pluses and slashes) but
that's not an issue here
The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
See http://en.wikipedia.org/wiki/Birthday_problem
|
uid
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/customUtils.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/customUtils.js
|
MIT
|
function exists (filename, callback) {
localforage.getItem(filename, function (err, value) {
if (value !== null) { // Even if value is undefined, localforage returns null
return callback(true);
} else {
return callback(false);
}
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
exists
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function rename (filename, newFilename, callback) {
localforage.getItem(filename, function (err, value) {
if (value === null) {
localforage.removeItem(newFilename, function () { return callback(); });
} else {
localforage.setItem(newFilename, value, function () {
localforage.removeItem(filename, function () { return callback(); });
});
}
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
rename
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function writeFile (filename, contents, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.setItem(filename, contents, function () { return callback(); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
writeFile
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function appendFile (filename, toAppend, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.getItem(filename, function (err, contents) {
contents = contents || '';
contents += toAppend;
localforage.setItem(filename, contents, function () { return callback(); });
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
appendFile
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function readFile (filename, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.getItem(filename, function (err, contents) { return callback(null, contents || ''); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
readFile
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function unlink (filename, callback) {
localforage.removeItem(filename, function () { return callback(); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
unlink
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function mkdirp (dir, callback) {
return callback();
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
mkdirp
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function ensureDatafileIntegrity (filename, callback) {
return callback(null);
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
ensureDatafileIntegrity
|
javascript
|
louischatriot/nedb
|
browser-version/browser-specific/lib/storage.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/browser-specific/lib/storage.js
|
MIT
|
function Cursor (db, query, execFn) {
this.db = db;
this.query = query || {};
if (execFn) { this.execFn = execFn; }
}
|
Create a new cursor for this collection
@param {Datastore} db - The datastore this cursor is bound to
@param {Query} query - The query this cursor will operate on
@param {Function} execFn - Handler to be executed after cursor has found the results and before the callback passed to find/findOne/update/remove
|
Cursor
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function callback (error, res) {
if (self.execFn) {
return self.execFn(error, res, _callback);
} else {
return _callback(error, res);
}
}
|
Get all matching elements
Will return pointers to matched elements (shallow copies), returning full copies is the role of find or findOne
This is an internal function, use exec which uses the executor
@param {Function} callback - Signature: err, results
|
callback
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function randomBytes (size) {
var bytes = new Array(size);
var r;
for (var i = 0, r; i < size; i++) {
if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return bytes;
}
|
Taken from the crypto-browserify module
https://github.com/dominictarr/crypto-browserify
NOTE: Math.random() does not guarantee "cryptographic quality" but we actually don't need it
|
randomBytes
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function uid (len) {
return byteArrayToBase64(randomBytes(Math.ceil(Math.max(8, len * 2)))).replace(/[+\/]/g, '').slice(0, len);
}
|
Return a random alphanumerical string of length len
There is a very small probability (less than 1/1,000,000) for the length to be less than len
(il the base64 conversion yields too many pluses and slashes) but
that's not an issue here
The probability of a collision is extremely small (need 3*10^12 documents to have one chance in a million of a collision)
See http://en.wikipedia.org/wiki/Birthday_problem
|
uid
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function Executor () {
this.buffer = [];
this.ready = false;
// This queue will execute all commands, one-by-one in order
this.queue = async.queue(function (task, cb) {
var newArguments = [];
// task.arguments is an array-like object on which adding a new field doesn't work, so we transform it into a real array
for (var i = 0; i < task.arguments.length; i += 1) { newArguments.push(task.arguments[i]); }
var lastArg = task.arguments[task.arguments.length - 1];
// Always tell the queue task is complete. Execute callback if any was given.
if (typeof lastArg === 'function') {
// Callback was supplied
newArguments[newArguments.length - 1] = function () {
if (typeof setImmediate === 'function') {
setImmediate(cb);
} else {
process.nextTick(cb);
}
lastArg.apply(null, arguments);
};
} else if (!lastArg && task.arguments.length !== 0) {
// false/undefined/null supplied as callbback
newArguments[newArguments.length - 1] = function () { cb(); };
} else {
// Nothing supplied as callback
newArguments.push(function () { cb(); });
}
task.fn.apply(task.this, newArguments);
}, 1);
}
|
Responsible for sequentially executing actions on the database
|
Executor
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function checkValueEquality (a, b) {
return a === b;
}
|
Two indexed pointers are equal iif they point to the same place
|
checkValueEquality
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function Index (options) {
this.fieldName = options.fieldName;
this.unique = options.unique || false;
this.sparse = options.sparse || false;
this.treeOptions = { unique: this.unique, compareKeys: model.compareThings, checkValueEquality: checkValueEquality };
this.reset(); // No data in the beginning
}
|
Create a new index
All methods on an index guarantee that either the whole operation was successful and the index changed
or the operation was unsuccessful and an error is thrown while the index is unchanged
@param {String} options.fieldName On which field should the index apply (can use dot notation to index on sub fields)
@param {Boolean} options.unique Optional, enforce a unique constraint (default: false)
@param {Boolean} options.sparse Optional, allow a sparse index (we can have documents for which fieldName is undefined) (default: false)
|
Index
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function checkKey (k, v) {
if (typeof k === 'number') {
k = k.toString();
}
if (k[0] === '$' && !(k === '$$date' && typeof v === 'number') && !(k === '$$deleted' && v === true) && !(k === '$$indexCreated') && !(k === '$$indexRemoved')) {
throw new Error('Field names cannot begin with the $ character');
}
if (k.indexOf('.') !== -1) {
throw new Error('Field names cannot contain a .');
}
}
|
Check a key, throw an error if the key is non valid
@param {String} k key
@param {Model} v value, needed to treat the Date edge case
Non-treatable edge cases here: if part of the object if of the form { $$date: number } or { $$deleted: true }
Its serialized-then-deserialized version it will transformed into a Date object
But you really need to want it to trigger such behaviour, even when warned not to use '$' at the beginning of the field names...
|
checkKey
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function checkObject (obj) {
if (util.isArray(obj)) {
obj.forEach(function (o) {
checkObject(o);
});
}
if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(function (k) {
checkKey(k, obj[k]);
checkObject(obj[k]);
});
}
}
|
Check a DB object and throw an error if it's not valid
Works by applying the above checkKey function to all fields recursively
|
checkObject
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function deserialize (rawData) {
return JSON.parse(rawData, function (k, v) {
if (k === '$$date') { return new Date(v); }
if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null) { return v; }
if (v && v.$$date) { return v.$$date; }
return v;
});
}
|
From a one-line representation of an object generate by the serialize function
Return the object itself
|
deserialize
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function deepCopy (obj, strictKeys) {
var res;
if ( typeof obj === 'boolean' ||
typeof obj === 'number' ||
typeof obj === 'string' ||
obj === null ||
(util.isDate(obj)) ) {
return obj;
}
if (util.isArray(obj)) {
res = [];
obj.forEach(function (o) { res.push(deepCopy(o, strictKeys)); });
return res;
}
if (typeof obj === 'object') {
res = {};
Object.keys(obj).forEach(function (k) {
if (!strictKeys || (k[0] !== '$' && k.indexOf('.') === -1)) {
res[k] = deepCopy(obj[k], strictKeys);
}
});
return res;
}
return undefined; // For now everything else is undefined. We should probably throw an error instead
}
|
Deep copy a DB object
The optional strictKeys flag (defaulting to false) indicates whether to copy everything or only fields
where the keys are valid, i.e. don't begin with $ and don't contain a .
|
deepCopy
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function compareNSB (a, b) {
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
}
|
Utility functions for comparing things
Assumes type checking was already done (a and b already have the same type)
compareNSB works for numbers, strings and booleans
|
compareNSB
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function compareArrays (a, b) {
var i, comp;
for (i = 0; i < Math.min(a.length, b.length); i += 1) {
comp = compareThings(a[i], b[i]);
if (comp !== 0) { return comp; }
}
// Common section was identical, longest one wins
return compareNSB(a.length, b.length);
}
|
Utility functions for comparing things
Assumes type checking was already done (a and b already have the same type)
compareNSB works for numbers, strings and booleans
|
compareArrays
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function compareThings (a, b, _compareStrings) {
var aKeys, bKeys, comp, i
, compareStrings = _compareStrings || compareNSB;
// undefined
if (a === undefined) { return b === undefined ? 0 : -1; }
if (b === undefined) { return a === undefined ? 0 : 1; }
// null
if (a === null) { return b === null ? 0 : -1; }
if (b === null) { return a === null ? 0 : 1; }
// Numbers
if (typeof a === 'number') { return typeof b === 'number' ? compareNSB(a, b) : -1; }
if (typeof b === 'number') { return typeof a === 'number' ? compareNSB(a, b) : 1; }
// Strings
if (typeof a === 'string') { return typeof b === 'string' ? compareStrings(a, b) : -1; }
if (typeof b === 'string') { return typeof a === 'string' ? compareStrings(a, b) : 1; }
// Booleans
if (typeof a === 'boolean') { return typeof b === 'boolean' ? compareNSB(a, b) : -1; }
if (typeof b === 'boolean') { return typeof a === 'boolean' ? compareNSB(a, b) : 1; }
// Dates
if (util.isDate(a)) { return util.isDate(b) ? compareNSB(a.getTime(), b.getTime()) : -1; }
if (util.isDate(b)) { return util.isDate(a) ? compareNSB(a.getTime(), b.getTime()) : 1; }
// Arrays (first element is most significant and so on)
if (util.isArray(a)) { return util.isArray(b) ? compareArrays(a, b) : -1; }
if (util.isArray(b)) { return util.isArray(a) ? compareArrays(a, b) : 1; }
// Objects
aKeys = Object.keys(a).sort();
bKeys = Object.keys(b).sort();
for (i = 0; i < Math.min(aKeys.length, bKeys.length); i += 1) {
comp = compareThings(a[aKeys[i]], b[bKeys[i]]);
if (comp !== 0) { return comp; }
}
return compareNSB(aKeys.length, bKeys.length);
}
|
Compare { things U undefined }
Things are defined as any native types (string, number, boolean, null, date) and objects
We need to compare with undefined as it will be used in indexes
In the case of objects and arrays, we deep-compare
If two objects dont have the same type, the (arbitrary) type hierarchy is: undefined, null, number, strings, boolean, dates, arrays, objects
Return -1 if a < b, 1 if a > b and 0 if a = b (note that equality here is NOT the same as defined in areThingsEqual!)
@param {Function} _compareStrings String comparing function, returning -1, 0 or 1, overriding default string comparison (useful for languages with accented letters)
|
compareThings
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function createModifierFunction (modifier) {
return function (obj, field, value) {
var fieldParts = typeof field === 'string' ? field.split('.') : field;
if (fieldParts.length === 1) {
lastStepModifierFunctions[modifier](obj, field, value);
} else {
if (obj[fieldParts[0]] === undefined) {
if (modifier === '$unset') { return; } // Bad looking specific fix, needs to be generalized modifiers that behave like $unset are implemented
obj[fieldParts[0]] = {};
}
modifierFunctions[modifier](obj[fieldParts[0]], fieldParts.slice(1), value);
}
};
}
|
Updates the value of the field, only if specified field is smaller than the current value of the field
|
createModifierFunction
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function modify (obj, updateQuery) {
var keys = Object.keys(updateQuery)
, firstChars = _.map(keys, function (item) { return item[0]; })
, dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; })
, newDoc, modifiers
;
if (keys.indexOf('_id') !== -1 && updateQuery._id !== obj._id) { throw new Error("You cannot change a document's _id"); }
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
throw new Error("You cannot mix modifiers and normal fields");
}
if (dollarFirstChars.length === 0) {
// Simply replace the object with the update query contents
newDoc = deepCopy(updateQuery);
newDoc._id = obj._id;
} else {
// Apply modifiers
modifiers = _.uniq(keys);
newDoc = deepCopy(obj);
modifiers.forEach(function (m) {
var keys;
if (!modifierFunctions[m]) { throw new Error("Unknown modifier " + m); }
// Can't rely on Object.keys throwing on non objects since ES6
// Not 100% satisfying as non objects can be interpreted as objects but no false negatives so we can live with it
if (typeof updateQuery[m] !== 'object') {
throw new Error("Modifier " + m + "'s argument must be an object");
}
keys = Object.keys(updateQuery[m]);
keys.forEach(function (k) {
modifierFunctions[m](newDoc, k, updateQuery[m][k]);
});
});
}
// Check result is valid and return it
checkObject(newDoc);
if (obj._id !== newDoc._id) { throw new Error("You can't change a document's _id"); }
return newDoc;
}
|
Modify a DB object according to an update query
|
modify
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function getDotValue (obj, field) {
var fieldParts = typeof field === 'string' ? field.split('.') : field
, i, objs;
if (!obj) { return undefined; } // field cannot be empty so that means we should return undefined so that nothing can match
if (fieldParts.length === 0) { return obj; }
if (fieldParts.length === 1) { return obj[fieldParts[0]]; }
if (util.isArray(obj[fieldParts[0]])) {
// If the next field is an integer, return only this item of the array
i = parseInt(fieldParts[1], 10);
if (typeof i === 'number' && !isNaN(i)) {
return getDotValue(obj[fieldParts[0]][i], fieldParts.slice(2))
}
// Return the array of values
objs = new Array();
for (i = 0; i < obj[fieldParts[0]].length; i += 1) {
objs.push(getDotValue(obj[fieldParts[0]][i], fieldParts.slice(1)));
}
return objs;
} else {
return getDotValue(obj[fieldParts[0]], fieldParts.slice(1));
}
}
|
Get a value from object with dot notation
@param {Object} obj
@param {String} field
|
getDotValue
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function areThingsEqual (a, b) {
var aKeys , bKeys , i;
// Strings, booleans, numbers, null
if (a === null || typeof a === 'string' || typeof a === 'boolean' || typeof a === 'number' ||
b === null || typeof b === 'string' || typeof b === 'boolean' || typeof b === 'number') { return a === b; }
// Dates
if (util.isDate(a) || util.isDate(b)) { return util.isDate(a) && util.isDate(b) && a.getTime() === b.getTime(); }
// Arrays (no match since arrays are used as a $in)
// undefined (no match since they mean field doesn't exist and can't be serialized)
if ((!(util.isArray(a) && util.isArray(b)) && (util.isArray(a) || util.isArray(b))) || a === undefined || b === undefined) { return false; }
// General objects (check for deep equality)
// a and b should be objects at this point
try {
aKeys = Object.keys(a);
bKeys = Object.keys(b);
} catch (e) {
return false;
}
if (aKeys.length !== bKeys.length) { return false; }
for (i = 0; i < aKeys.length; i += 1) {
if (bKeys.indexOf(aKeys[i]) === -1) { return false; }
if (!areThingsEqual(a[aKeys[i]], b[aKeys[i]])) { return false; }
}
return true;
}
|
Check whether 'things' are equal
Things are defined as any native types (string, number, boolean, null, date) and objects
In the case of object, we check deep equality
Returns true if they are, false otherwise
|
areThingsEqual
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function areComparable (a, b) {
if (typeof a !== 'string' && typeof a !== 'number' && !util.isDate(a) &&
typeof b !== 'string' && typeof b !== 'number' && !util.isDate(b)) {
return false;
}
if (typeof a !== typeof b) { return false; }
return true;
}
|
Check that two values are comparable
|
areComparable
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function match (obj, query) {
var queryKeys, queryKey, queryValue, i;
// Primitive query against a primitive type
// This is a bit of a hack since we construct an object with an arbitrary key only to dereference it later
// But I don't have time for a cleaner implementation now
if (isPrimitiveType(obj) || isPrimitiveType(query)) {
return matchQueryPart({ needAKey: obj }, 'needAKey', query);
}
// Normal query
queryKeys = Object.keys(query);
for (i = 0; i < queryKeys.length; i += 1) {
queryKey = queryKeys[i];
queryValue = query[queryKey];
if (queryKey[0] === '$') {
if (!logicalOperators[queryKey]) { throw new Error("Unknown logical operator " + queryKey); }
if (!logicalOperators[queryKey](obj, queryValue)) { return false; }
} else {
if (!matchQueryPart(obj, queryKey, queryValue)) { return false; }
}
}
return true;
}
|
Tell if a given document matches a query
@param {Object} obj Document to check
@param {Object} query
|
match
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function matchQueryPart (obj, queryKey, queryValue, treatObjAsValue) {
var objValue = getDotValue(obj, queryKey)
, i, keys, firstChars, dollarFirstChars;
// Check if the value is an array if we don't force a treatment as value
if (util.isArray(objValue) && !treatObjAsValue) {
// If the queryValue is an array, try to perform an exact match
if (util.isArray(queryValue)) {
return matchQueryPart(obj, queryKey, queryValue, true);
}
// Check if we are using an array-specific comparison function
if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue)) {
keys = Object.keys(queryValue);
for (i = 0; i < keys.length; i += 1) {
if (arrayComparisonFunctions[keys[i]]) { return matchQueryPart(obj, queryKey, queryValue, true); }
}
}
// If not, treat it as an array of { obj, query } where there needs to be at least one match
for (i = 0; i < objValue.length; i += 1) {
if (matchQueryPart({ k: objValue[i] }, 'k', queryValue)) { return true; } // k here could be any string
}
return false;
}
// queryValue is an actual object. Determine whether it contains comparison operators
// or only normal fields. Mixed objects are not allowed
if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue) && !util.isArray(queryValue)) {
keys = Object.keys(queryValue);
firstChars = _.map(keys, function (item) { return item[0]; });
dollarFirstChars = _.filter(firstChars, function (c) { return c === '$'; });
if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
throw new Error("You cannot mix operators and normal fields");
}
// queryValue is an object of this form: { $comparisonOperator1: value1, ... }
if (dollarFirstChars.length > 0) {
for (i = 0; i < keys.length; i += 1) {
if (!comparisonFunctions[keys[i]]) { throw new Error("Unknown comparison function " + keys[i]); }
if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) { return false; }
}
return true;
}
}
// Using regular expressions with basic querying
if (util.isRegExp(queryValue)) { return comparisonFunctions.$regex(objValue, queryValue); }
// queryValue is either a native value or a normal object
// Basic matching is possible
if (!areThingsEqual(objValue, queryValue)) { return false; }
return true;
}
|
Match an object against a specific { key: value } part of a query
if the treatObjAsValue flag is set, don't try to match every part separately, but the array as a whole
|
matchQueryPart
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function Persistence (options) {
var i, j, randomString;
this.db = options.db;
this.inMemoryOnly = this.db.inMemoryOnly;
this.filename = this.db.filename;
this.corruptAlertThreshold = options.corruptAlertThreshold !== undefined ? options.corruptAlertThreshold : 0.1;
if (!this.inMemoryOnly && this.filename && this.filename.charAt(this.filename.length - 1) === '~') {
throw new Error("The datafile name can't end with a ~, which is reserved for crash safe backup files");
}
// After serialization and before deserialization hooks with some basic sanity checks
if (options.afterSerialization && !options.beforeDeserialization) {
throw new Error("Serialization hook defined but deserialization hook undefined, cautiously refusing to start NeDB to prevent dataloss");
}
if (!options.afterSerialization && options.beforeDeserialization) {
throw new Error("Serialization hook undefined but deserialization hook defined, cautiously refusing to start NeDB to prevent dataloss");
}
this.afterSerialization = options.afterSerialization || function (s) { return s; };
this.beforeDeserialization = options.beforeDeserialization || function (s) { return s; };
for (i = 1; i < 30; i += 1) {
for (j = 0; j < 10; j += 1) {
randomString = customUtils.uid(i);
if (this.beforeDeserialization(this.afterSerialization(randomString)) !== randomString) {
throw new Error("beforeDeserialization is not the reverse of afterSerialization, cautiously refusing to start NeDB to prevent dataloss");
}
}
}
// For NW apps, store data in the same directory where NW stores application data
if (this.filename && options.nodeWebkitAppName) {
console.log("==================================================================");
console.log("WARNING: The nodeWebkitAppName option is deprecated");
console.log("To get the path to the directory where Node Webkit stores the data");
console.log("for your app, use the internal nw.gui module like this");
console.log("require('nw.gui').App.dataPath");
console.log("See https://github.com/rogerwang/node-webkit/issues/500");
console.log("==================================================================");
this.filename = Persistence.getNWAppFilename(options.nodeWebkitAppName, this.filename);
}
}
|
Create a new Persistence object for database options.db
@param {Datastore} options.db
@param {Boolean} options.nodeWebkitAppName Optional, specify the name of your NW app if you want options.filename to be relative to the directory where
Node Webkit stores application data such as cookies and local storage (the best place to store data in my opinion)
|
Persistence
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function exists (filename, callback) {
localforage.getItem(filename, function (err, value) {
if (value !== null) { // Even if value is undefined, localforage returns null
return callback(true);
} else {
return callback(false);
}
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
exists
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function rename (filename, newFilename, callback) {
localforage.getItem(filename, function (err, value) {
if (value === null) {
localforage.removeItem(newFilename, function () { return callback(); });
} else {
localforage.setItem(newFilename, value, function () {
localforage.removeItem(filename, function () { return callback(); });
});
}
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
rename
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function writeFile (filename, contents, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.setItem(filename, contents, function () { return callback(); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
writeFile
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function appendFile (filename, toAppend, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.getItem(filename, function (err, contents) {
contents = contents || '';
contents += toAppend;
localforage.setItem(filename, contents, function () { return callback(); });
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
appendFile
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function readFile (filename, options, callback) {
// Options do not matter in browser setup
if (typeof options === 'function') { callback = options; }
localforage.getItem(filename, function (err, contents) { return callback(null, contents || ''); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
readFile
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function unlink (filename, callback) {
localforage.removeItem(filename, function () { return callback(); });
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
unlink
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function mkdirp (dir, callback) {
return callback();
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
mkdirp
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function ensureDatafileIntegrity (filename, callback) {
return callback(null);
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
ensureDatafileIntegrity
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
function only_once(fn) {
var called = false;
return function() {
if (called) throw new Error("Callback was already called.");
called = true;
fn.apply(root, arguments);
}
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
only_once
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
_each = function (arr, iterator) {
if (arr.forEach) {
return arr.forEach(iterator);
}
for (var i = 0; i < arr.length; i += 1) {
iterator(arr[i], i, arr);
}
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
_each
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
_map = function (arr, iterator) {
if (arr.map) {
return arr.map(iterator);
}
var results = [];
_each(arr, function (x, i, a) {
results.push(iterator(x, i, a));
});
return results;
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
_map
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
_reduce = function (arr, iterator, memo) {
if (arr.reduce) {
return arr.reduce(iterator, memo);
}
_each(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
_reduce
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
_keys = function (obj) {
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
_keys
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
iterate = function () {
iterator(arr[completed], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
if (completed >= arr.length) {
callback(null);
}
else {
iterate();
}
}
});
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
iterate
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
_eachLimit = function (limit) {
return function (arr, iterator, callback) {
callback = callback || function () {};
if (!arr.length || limit <= 0) {
return callback();
}
var completed = 0;
var started = 0;
var running = 0;
(function replenish () {
if (completed >= arr.length) {
return callback();
}
while (running < limit && started < arr.length) {
started += 1;
running += 1;
iterator(arr[started - 1], function (err) {
if (err) {
callback(err);
callback = function () {};
}
else {
completed += 1;
running -= 1;
if (completed >= arr.length) {
callback();
}
else {
replenish();
}
}
});
}
})();
};
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
_eachLimit
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
doParallel = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [async.each].concat(args));
};
}
|
Way data is stored for this database
For a Node.js/Node Webkit database it's the file system
For a browser-side database it's localforage, which uses the best backend available (IndexedDB then WebSQL then localStorage)
This version is the browser version
|
doParallel
|
javascript
|
louischatriot/nedb
|
browser-version/out/nedb.js
|
https://github.com/louischatriot/nedb/blob/master/browser-version/out/nedb.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.