Add ol.geom.flat.segments.forEach

This commit is contained in:
Éric Lemoine
2014-07-08 16:18:16 +02:00
parent 24321f6feb
commit 3ce6229d34
2 changed files with 90 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
goog.provide('ol.geom.flat.segments');
/**
* This function calls `callback` for each segment of the flat coordinates
* array. If the callback returns a truthy value the function returns that
* value immediately. Otherwise the function returns `false`.
* @param {Array.<number>} flatCoordinates Flat coordinates.
* @param {number} offset Offset.
* @param {number} end End.
* @param {number} stride Stride.
* @param {function(ol.Coordinate, ol.Coordinate): T} callback Function
* called for each segment.
* @return {T|boolean} Value.
* @template T
*/
ol.geom.flat.segments.forEach =
function(flatCoordinates, offset, end, stride, callback) {
var point1 = [flatCoordinates[offset], flatCoordinates[offset + 1]];
var point2 = [];
var ret;
for (; (offset + stride) < end; offset += stride) {
point2[0] = flatCoordinates[offset + stride];
point2[1] = flatCoordinates[offset + stride + 1];
ret = callback(point1, point2);
if (ret) {
return ret;
}
point1[0] = point2[0];
point1[1] = point2[1];
}
return false;
};

View File

@@ -0,0 +1,57 @@
goog.provide('ol.test.geom.flat.segments');
describe('ol.geom.flat.segments', function() {
describe('ol.geom.flat.segments.forEach', function() {
var flatCoordinates, offset, end, stride;
beforeEach(function() {
flatCoordinates = [0, 0, 1, 1, 2, 2, 3, 3];
offset = 0;
end = 8;
stride = 2;
});
describe('callback returns undefined', function() {
it('executes the callback for each segment', function() {
var args = [];
var spy = sinon.spy(function(point1, point2) {
args.push([point1[0], point1[1], point2[0], point2[1]]);
});
var ret = ol.geom.flat.segments.forEach(
flatCoordinates, offset, end, stride, spy);
expect(spy.callCount).to.be(3);
expect(args[0][0]).to.be(0);
expect(args[0][1]).to.be(0);
expect(args[0][2]).to.be(1);
expect(args[0][3]).to.be(1);
expect(args[1][0]).to.be(1);
expect(args[1][1]).to.be(1);
expect(args[1][2]).to.be(2);
expect(args[1][3]).to.be(2);
expect(args[2][0]).to.be(2);
expect(args[2][1]).to.be(2);
expect(args[2][2]).to.be(3);
expect(args[2][3]).to.be(3);
expect(ret).to.be(false);
});
});
describe('callback returns true', function() {
it('executes the callback for the first segment', function() {
var args = [];
var spy = sinon.spy(function(point1, point2) {
args.push([point1[0], point1[1], point2[0], point2[1]]);
return true;
});
var ret = ol.geom.flat.segments.forEach(
flatCoordinates, offset, end, stride, spy);
expect(spy.callCount).to.be(1);
expect(args[0][0]).to.be(0);
expect(args[0][1]).to.be(0);
expect(args[0][2]).to.be(1);
expect(args[0][3]).to.be(1);
expect(ret).to.be(true);
});
});
});
});
goog.require('ol.geom.flat.segments');