Skip to content

Commit

Permalink
TwigJS: new filter 'parseDirection'
Browse files Browse the repository at this point in the history
  • Loading branch information
plepe committed Nov 3, 2024
1 parent 77f0bee commit a718631
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions doc/TwigJS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Extra filters:
* filter `ksort`: Sort an associative array by key (alphabetic)
* filter `unique`: Remove duplicate elements from an array.
* filter `md5`: calculate md5 hash of a string.
* filter `parseDirection`: parses the value of a direction (e.g. 'east' => 90, 'SE' => 135). If the value is a string, but not a cardinal direction return the value as number (e.g. '90' => 90). Other values are returned as is.
* filter `enumerate`: enumerate the given list, e.g. "foo, bar, and bla". Input either an array (`[ "foo", "bar", "bla" ]|enumerate`) or a string with `;` as separator (`"foo;bar;bla"|enumerate`).
* filter `debug`: print the value (and further arguments) to the javascript console (via `console.log()`)
* filter `wikipediaAbstract`: shows the abstract of a Wikipedia article in the selected data language (or, if not available, the language which was used in input, resp. 'en' for Wikidata input). Input is either 'language:article' (e.g. 'en:Douglas Adams') or a wikidata id (e.g. 'Q42').
Expand Down
39 changes: 39 additions & 0 deletions src/twigFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,33 @@ const yaml = require('js-yaml')

var md5cache = {}

const cardinalDirections = {
'NORTH': 0,
'N': 0,
'NNE': 22.5,
'NE': 45,
'NORTHEAST': 45,
'ENE': 67.5,
'EAST': 90,
'E': 90,
'ESE': 112.5,
'SE': 135,
'SOUTHEAST': 45,
'SSE': 157.5,
'SOUTH': 180,
'S': 180,
'SSW': 202.5,
'SW': 225,
'SOUTHWEST': 225,
'WSW': 247.5,
'WEST': 270,
'W': 270,
'WNW': 292.5,
'NW': 315,
'NORTHWEST': 315,
'NNW': 337.5
}

OverpassLayer.twig.extendFunction('tagsPrefix', function (tags, prefix) {
var ret = {}
var count = 0
Expand Down Expand Up @@ -59,6 +86,18 @@ OverpassLayer.twig.extendFilter('matches', function (value, param) {
OverpassLayer.twig.extendFilter('natsort', function (values, options) {
return values.sort(natsort(options))
})
OverpassLayer.twig.extendFilter('parseDirection', function (value, options) {
if (typeof value === 'string') {
const valueUpper = value.trim().toUpperCase()
if (valueUpper in cardinalDirections) {
return cardinalDirections[valueUpper]
}

return parseFloat(value)
}

return value
})
OverpassLayer.twig.extendFilter('unique', function (values, options) {
// source: https://stackoverflow.com/a/14438954
function onlyUnique (value, index, self) {
Expand Down

0 comments on commit a718631

Please sign in to comment.