Skip to content

Instantly share code, notes, and snippets.

@ox
Last active December 19, 2015 23:29
Show Gist options
  • Save ox/6035073 to your computer and use it in GitHub Desktop.
Save ox/6035073 to your computer and use it in GitHub Desktop.
var buildKeySus = function (patternObj, data) {
var pattern = patternObj.pattern
var duration = patternObj.duration || DEFAULT_CACHE_AGE_MS
data = data || {}
var patternParts = pattern.split('/')
var key = ''
for (var i = 0; i < patternParts.length; i++) {
if (patternParts[i].charAt(0) === ':') {
var dataKey = patternParts[i].substr(1)
// if a pattern-matched portion of the key is missing, exit out
// of the key building with the currently built portion of the key.
// e.g. the key /collectionPosts/:collectionId/:postId with
// {collectionId: 123} would return /collectionPosts/123/
if (!data[dataKey]) return {
key: key,
duration: duration
}
key += data[dataKey] || 'null'
} else {
key += patternParts[i]
}
if (i < patternParts.length - 1) key += '/'
}
return {
key: key,
duration: duration
}
}
var buildKeyLegit = function (patternObj, data) {
return {
key: keyBuilder(patternObj.pattern)(data || {}),
duration: patternObj.duration || DEFAULT_CACHE_AGE_MS
}
}
function keyBuilder(key) {
for (var parts = key.split('/'), _=(parts[0] == "" && parts.shift()), l = parts.length, fA = '(function(data) {\n\treturn \"/', i = 0; i < l; i++) {
fA += (parts[i][0] == ':' ? "\"+(var s = data[\'" + parts[i].slice(1) + "\'] ? data[\'" + parts[i].slice(1) + "\'] + '/' : '')+\"" : parts[i] + '/')
}
return eval(fA + '\"\n})', {})
}
// console.log(keyBuilder('/collection/:controller/:action/:id'))
console.log(keyBuilder('/collection/:controller/:action/:id')({controller: 'foo', action: 'bar', id: '123'}))
console.log(keyBuilder('/collection/:controller/:action/:id')({controller: 'foo'}))
console.log('old', buildKeySus({pattern: '/b/:controller/:action/:id', duration: 60}, {controller: 'foo', action: 'bar', id: '123'}))
// old { key: '/b/foo/bar/123', duration: 60 }
console.log('new', buildKeyLegit({pattern: '/b/:controller/:action/:id', duration: 60}, {controller: 'foo', action: 'bar', id: '123'}))
// new { key: '/b/foo/bar/123', duration: 60 }
console.log('mod', buildKeyLegit({pattern: '/b/:controller/:action/:id', duration: 60}, {controller: 'foo', id: '123'}))
// mod { key: '/b/foo/123', duration: 60 }
console.log('mod', buildKeyLegit({pattern: '/b/:controller/:action/:id', duration: 60}, {}))
// mod { key: '/b', duration: 60 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment