/*! * gana-compile * * Copyright (c) 2016 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk) * Released under the MIT license. */ 'use strict' var isObject = require('isobject') /** * > Compiles a `template` to a function, which * accepts `locals` object to populate the template. * * **Example** * * ```js * var ganaCompile = require('gana-compile') * * var template = 'Welcome here, ${ucfirst(name)}! And have fun!' * var locals = { * name: 'charlike', * ucfirst: function ucfirst (val) { * return val.charAt(0).toUpperCase() + val.slice(1) * } * } * * var fn = ganaCompile(template) * var str = fn(locals) * * console.log(str) * // => 'Welcome here, Charlike! And have fun!' * ``` * * @param {String} `template` string to compile to a function * @return {Function} like `compileFn(locals)`, where `locals` must be `object` * @throws {TypeError} if `template` not a string * @throws {TypeError} if `locals` not an object * @throws {ReferenceError} if key not exists in `locals` object * @api public */ module.exports = function ganaCompile (template) { if (typeof template !== 'string') { throw new TypeError('ganaCompile: expect `template` to be a string') } return function compileFn (locals) { if (!isObject(locals)) { throw new TypeError('ganaCompile: expect `locals` to be an object') } var keys = [] var vals = [] for (var key in locals) { keys.push(key) vals.push(locals[key]) } /* eslint-disable no-new-func */ var fn = new Function(keys, 'return `' + template + '`') return fn.apply(locals, vals) } }