Skip to content

Commit

Permalink
feat: seclude formatParts util
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Oct 1, 2018
1 parent 53a03a2 commit 3b40e25
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 11 deletions.
20 changes: 20 additions & 0 deletions format-parts.js
@@ -0,0 +1,20 @@
// For given resolver returns

"use strict";

var ensureArray = require("es5-ext/array/valid-array")
, isValue = require("es5-ext/object/is-value")
, ensureObject = require("es5-ext/object/valid-object")
, ensureString = require("es5-ext/object/validate-stringifiable-value");

module.exports = function (parts) {
var literals = ensureArray(ensureObject(parts).literals);
var substitutions = ensureArray(parts.substitutions);
var resolvedString = literals.length
? literals.reduce(function (resolved, literal, index) {
return resolved + substitutions[index - 1] + literal;
})
: "";
if (isValue(parts.rest)) resolvedString += ensureString(parts.rest);
return resolvedString;
};
14 changes: 3 additions & 11 deletions index.js
@@ -1,20 +1,12 @@
"use strict";

var getPartsResolver = require("./get-parts-resolver");
var getPartsResolver = require("./get-parts-resolver")
, formatParts = require("./format-parts");

module.exports = function (modifiers) {
var resolveParts = getPartsResolver(modifiers);

return function (formatIgnored/*, ...params*/) {
var data = resolveParts.apply(null, arguments);
var literals = data.literals;
var substitutions = data.substitutions;
var resolvedString = literals.length
? literals.reduce(function (resolved, literal, index) {
return resolved + substitutions[index - 1] + literal;
})
: "";
if (data.rest) resolvedString += data.rest;
return resolvedString;
return formatParts(resolveParts.apply(null, arguments));
};
};
37 changes: 37 additions & 0 deletions test/format-parts.js
@@ -0,0 +1,37 @@
"use strict";

var test = require("tape")
, formatParts = require("../format-parts");

test("getResolver", function (t) {
t.test("Should resolve", function (t) {
t.equal(formatParts({ literals: ["foo raz"], substitutions: [], rest: null }), "foo raz");
t.equal(
formatParts({ literals: ["foo ", ""], substitutions: ["marko"], rest: null }),
"foo marko", "Single placeholder"
);
t.equal(
formatParts({
literals: ["foo ", " ", ""],
substitutions: ["marko", "12"],
rest: null
}),
"foo marko 12", "Two placeholders"
);
t.equal(
formatParts({ literals: [], substitutions: [], rest: null }), "",
"Non-string first argument without rest"
);

t.equal(
formatParts({ literals: ["foo ", ""], substitutions: ["marko"], rest: " 12-elo" }),
"foo marko 12-elo", "with rest handling"
);
t.equal(
formatParts({ literals: [], substitutions: [], rest: "12-13" }), "12-13",
"Non-string first argument with rest"
);
t.end();
});
t.end();
});

0 comments on commit 3b40e25

Please sign in to comment.