From c69e82ada7f07744432a315658a927209497ed87 Mon Sep 17 00:00:00 2001 From: Corin Chaplin Date: Wed, 11 Jul 2018 13:11:20 +0100 Subject: [PATCH] Change farmhash to an optional dependency and add fall back to string-hash (#91) --- package.json | 5 ++++- src/sql.js | 11 +++++++++-- test/to-esri.js | 14 +++++++++++++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 9523762..306fbf9 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,6 @@ "@turf/centroid": "^6.0.0", "alasql": "^0.4.0", "classybrew": "0.0.3", - "farmhash": "^2.0.5", "flora-sql-parser": "^0.7.5", "highland": "^3.0.0-beta.3", "lodash": "^4.17.4", @@ -44,6 +43,7 @@ "proj4": "^2.3.17", "simple-statistics": "^6.0.0", "srs": "^1.2.0", + "string-hash": "^1.1.3", "terraformer": "^1.0.7" }, "devDependencies": { @@ -52,5 +52,8 @@ "standard": "^11.0.0", "tap-spec": "^5.0.0", "tape": "^4.6.3" + }, + "optionalDependencies": { + "farmhash": "^2.1.0" } } diff --git a/src/sql.js b/src/sql.js index cb0be56..4fff3df 100644 --- a/src/sql.js +++ b/src/sql.js @@ -1,5 +1,4 @@ const Terraformer = require('terraformer') -const farmhash = require('farmhash') const transformArray = require('./geometry/transform-array') const convertToEsri = require('./geometry/convert-to-esri') const convertFromEsri = require('./geometry/convert-from-esri') @@ -10,6 +9,14 @@ const _ = require('lodash') const projectCoordinates = require('./geometry/project-coordinates') const reducePrecision = require('./geometry/reduce-precision') +// Try to require farmhash, as it is an optional depenecy we can fall back to JavaScript only hashing library +let hashFunction +try { + hashFunction = require('farmhash').hash32 +} catch (e) { + hashFunction = require('string-hash') +} + sql.MAXSQLCACHESIZE = 0 sql.fn.ST_Within = function (feature = {}, filterGeom = {}) { @@ -151,7 +158,7 @@ function esriFy (properties, geometry, dateFields, requiresObjectId, idField) { */ function createIntHash (inputStr) { // Hash to 32 bit unsigned integer - const hash = farmhash.hash32(inputStr) + const hash = hashFunction(inputStr) // Normalize to range of postive values of signed integer return Math.round((hash / 4294967295) * (2147483647)) } diff --git a/test/to-esri.js b/test/to-esri.js index 55ccc3c..07735e0 100644 --- a/test/to-esri.js +++ b/test/to-esri.js @@ -97,7 +97,19 @@ test('adding an object id', t => { } const fixture = _.cloneDeep(geojson) const result = Winnow.query(fixture, options) - t.equal(result.features[0].attributes.OBJECTID, 239375164) + + // A different hash can be returned depending on the library used + let hash + try { + // If requiring farmhash is successful we use that hash + require('farmhash') + hash = 239375164 + } catch (e) { + // Else use the string-hash number + hash = 1729830217 + } + + t.equal(result.features[0].attributes.OBJECTID, hash) t.end() })