Skip to content

Instantly share code, notes, and snippets.

@jordaaash
Created March 8, 2016 21:23
Show Gist options
  • Save jordaaash/2d62644556c4e49da116 to your computer and use it in GitHub Desktop.
Save jordaaash/2d62644556c4e49da116 to your computer and use it in GitHub Desktop.
Deterministic filename-based CDN sharding
'use strict';
var publicPath = require('./static_path')(process.env.PUBLIC_PATH); // e.g. PUBLIC_PATH=https://static%d.domain.com/
module.exports = publicPath;
'use strict';
var staticPath = function (root, rootPattern, pathPattern) {
if (rootPattern == null) {
rootPattern = /%d/g;
}
if (pathPattern == null) {
pathPattern = /^https?:\/\/.*?\/(.*)$/;
}
if (rootPattern.test(root)) {
return function (path) {
var match, hash, i, length, digit;
if (path == null) {
return root.replace(rootPattern, '');
}
else {
match = path.match(pathPattern);
if (match != null) {
path = match[1];
}
hash = 0;
for (i = 0, length = path.length; i < length; i++) {
hash = (((hash << 5) - hash) + path.charCodeAt(i)) & 0xFFFFFFFF;
}
digit = Math.abs(hash % 10);
return root.replace(rootPattern, digit) + path;
}
};
}
else {
return function (path) {
return (path == null) ? root : root + path;
};
}
};
module.exports = staticPath;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment