I've been playing with JavaScript dynamic formatting today and I can't seem to get this to work and wondered if anyone out there has done the same.
This is my function I've created to pass in a set number of formatters in for, say, strings, numbers etc:
function Formatter(formatters) { this.format = function(value, type) { switch(type) { case "string": return value => formatters.string break; case "currency": return value => formatters.curency break; case "number": return value => formatters.number break; default: return value; break; } } } I'm sending to it in the initialisation this:
formatters: { 'string': input => input, 'number': input => input.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'), 'currency': input => input.toFixed(3), 'url': input => (`<a href="${input.url}">${input.title}</a>`) } Soo...
var formatter = new Formatter({ 'string': input => input, 'number': input => input.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'), 'currency': input => input.toFixed(3), 'url': input => (`<a href="${input.url}">${input.title}</a>`) }); // This should display "test" as the format is just itself. formatter.format("test", "string); What it actually displays is value => formatters.string.
Is there any way to achieve what I'm trying to do here?
formatters.value