@poppinss/utils
Advanced tools
Comparing version 2.4.1 to 2.5.0
/** | ||
* A simple function interpolate values inside curly braces. The function assumes | ||
* it will be used in good faith and hence doesn't validate the inputs. | ||
* A simple function interpolate values inside curly braces. | ||
* | ||
* @example | ||
* `interpolate('hello {username}', { username: 'virk' })` | ||
* `interpolate('hello {{ username }}', { username: 'virk' })` | ||
*/ | ||
export declare function interpolate(input: string, data: any): string; |
@@ -12,18 +12,31 @@ "use strict"; | ||
exports.interpolate = void 0; | ||
function uncurryThis(fn) { | ||
return function (...args) { | ||
return Function.call.apply(fn, args); | ||
}; | ||
} | ||
const hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); | ||
/** | ||
* A simple function interpolate values inside curly braces. The function assumes | ||
* it will be used in good faith and hence doesn't validate the inputs. | ||
* Parses prop | ||
*/ | ||
function parseProp(data, key) { | ||
const tokens = key.split('.'); | ||
while (tokens.length) { | ||
if (data === null || typeof data !== 'object') { | ||
return; | ||
} | ||
const token = tokens.shift(); | ||
data = hasOwnProperty(data, token) ? data[token] : undefined; | ||
} | ||
return data; | ||
} | ||
/** | ||
* A simple function interpolate values inside curly braces. | ||
* | ||
* @example | ||
* `interpolate('hello {username}', { username: 'virk' })` | ||
* `interpolate('hello {{ username }}', { username: 'virk' })` | ||
*/ | ||
function interpolate(input, data) { | ||
return input.replace(/{(.*?)}/g, (_, key) => { | ||
let result = data; | ||
for (const prop of key.split('.')) { | ||
result = result && result[prop]; | ||
} | ||
return String(result); | ||
}); | ||
return input.replace(/{{(.*?)}}/g, (_, key) => parseProp(data, key.trim())); | ||
} | ||
exports.interpolate = interpolate; |
{ | ||
"name": "@poppinss/utils", | ||
"version": "2.4.1", | ||
"version": "2.5.0", | ||
"description": "Handy utilities for repetitive work", | ||
@@ -5,0 +5,0 @@ "main": "build/index.js", |
@@ -168,4 +168,4 @@ <div align="center"><img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1557762307/poppinss_iftxlt.jpg" width="600px"></div> | ||
interpolate('hello {username}', { username: 'virk' }) | ||
interpolate('hello {users.0.username}', { users: [{ username: 'virk' }] }) | ||
interpolate('hello {{ username }}', { username: 'virk' }) | ||
interpolate('hello {{ users.0.username }}', { users: [{ username: 'virk' }] }) | ||
``` | ||
@@ -172,0 +172,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
65702
931