'use strict'

const hifo =      require('hifo')
const mergeWith = require('lodash.mergewith')

const tokenize =  require('vbb-util').locations.stations.tokenize

const stations =  require('./data/stations.json')
const tokens =    require('./data/tokens.json')

// naming:
// - a fragment is a part of a search query
// - a token is a part of a stations' name
// - a result is a triple of station, relevance & weight





const findTokensForFragment = function (fragment) {
	let results = []
	for (let token in allTokens) {

		if (token === fragment) // exact match
			results.push({
				name:      fragment,
				relevance: Math.sqrt(fragment.length)
			})

		// match beginning with `fragment`
		else if (fragment === token.slice(0, fragment.length))
			results.push({
				name:      token,
				relevance: fragment.length / token.length
			})
	}
	return results
}

const findStationsForToken = (token) => allTokens[token.name]



const enrichTokenWithStations = (token) => Object.assign(
	token,
	{stations: findStationsForToken(token)}
)

const enrichFragmentWithTokens = (fragment) => ({
	name:   fragment,
	tokens: findTokensForFragment(fragment)
		.map(enrichTokenWithStations)
})









const autocomplete = function (query, limit) {
	let results = hifo(hifo.highest('relevance'), limit || 6)

	let fragments = tokenize(query).split(' ')
		.map(enrichFragmentWithTokens)


				}
			}
		}
	}


	return results.data
}



module.exports = Object.assign(autocomplete, {
	diffFragments,
	findTokensByFragment
})

@@ -1181,18 +1181,669 @@
 )%0A%7D)%0A%0A%0A%0A
-%0A%0A
+const stationsOfToken = (acc, token) =%3E acc.concat(token.stations)%0Aconst stationsOfFragment = (fragment) =%3E fragment.tokens%0A%09.reduce(stationsOfToken, %5B%5D)%0A%0Aconst stationMatchesAllFragments = (stationsOfFragments) =%3E%0A%09(station) =%3E stationsOfFragments%0A%09%09.every((stationsOfFragment) =%3E stationsOfFragment.indexOf(station) %3E= 0)%0A%0Aconst filterStationsOfFragmentsByAnd = function (fragments) %7B%0A%09let p = stationMatchesAllFragments(fragments.map(stationsOfFragment))%0A%0A%09for (let fragment of fragments) %7B%0A%09%09fragment.tokens = fragment.tokens%0A%09%09%09.filter(function (token) %7B%0A%09%09%09%09token.stations = token.stations.filter(p)%0A%09%09%09%09return token.stations.length %3E 0%0A%09%09%09%7D)%0A%09%7D%0A%7D
 %0A%0A%0A%0Acons
@@ -2022,16 +2022,59 @@
 Tokens)%0A
+%09filterStationsOfFragmentsByAnd(fragments)%0A
 %0A%0A%09%09%09%09%7D%0A

rewrite in functional style, part 2