base64-format
Version:
Re-format base64 data
77 lines (60 loc) • 1.82 kB
JavaScript
/*
base64-format
*/
;
var R = require("ramda"),
escapeRegex = require("escape-string-regexp"),
segment = require("string-segment"),
base64Clean = require("base64-clean"),
variants = require("base64-variants"),
defaults = R.mixin({
from: "base64",
to: "base64",
clean: true
}),
// Make a function-returning-function act like it's curried.
defer = function (func, value) {
return (value === undefined) ? func : func(value);
},
// Delete non-encoding chars, if appropriate
clean = function (options) {
if (!options.clean) {
return R.identity;
}
return base64Clean({ variant: options.from });
},
// Reflow lines
reflow = function (options) {
var line = variants[options.to].line;
return R.compose(
R.join(line.newline), // Join lines together with newline char
segment(line.width) // Split data into an array of lines
);
},
// Replace `from.keyspace` chars with `to.keyspace` chars
format = R.curry(function (options, data) {
var from = variants[options.from].keyspace,
to = variants[options.to].keyspace;
R.forEach(function (index) {
data = R.replace(
new RegExp(escapeRegex(from[index]), "g"),
to[index],
data
);
}, R.keys(from));
return data;
}),
main = function (options, data) {
options = Object.freeze(defaults(options));
return defer(
R.compose(
reflow(options),
format(options),
clean(options)
),
data
);
};
if (module !== undefined) {
module.exports = main;
}