Skip to content

Instantly share code, notes, and snippets.

@jonathanlurie
Last active March 1, 2019 17:41
Show Gist options
  • Save jonathanlurie/82f1d2ca26bd23c61ebe1757e05e97c9 to your computer and use it in GitHub Desktop.
Save jonathanlurie/82f1d2ca26bd23c61ebe1757e05e97c9 to your computer and use it in GitHub Desktop.
Some handy functions I use quite a lot but that does not deserve a proper repo
/**
* Because sometime we want to use the constructor of a typed array
* from a string such as 'uint8' or 'float32'
*/
const TYPED_ARRAY_LUT = {
int8: Int8Array,
int16: Int16Array,
int32: Int32Array,
uint8: Uint8Array,
uint16: Uint16Array,
uint32: Uint32Array,
float32: Float32Array,
float64: Float64Array
}
/**
* Deal with option object we pass in argument of function.
* Allows the return of a default value if the `optionName` is not available in
* the `optionObj`
* @example
* let myVal = getOption(options, 'someOptionName', 10)
* @param {Object} optionObj - the object that contain the options
* @param {String} optionName - the name of the option desired, attribute of `optionObj`
* @param {any} optionDefaultValue - default values to be returned in case `optionName` is not an attribute of `optionObj`
*/
function getOption(optionObj, optionName, optionDefaultValue) {
return (optionObj && optionName in optionObj) ? optionObj[optionName] : optionDefaultValue
}
/**
* Use a custom template with custom values to create a custom string
* @example
* let result = sprintf('hello, my name is ${firstname} ${lastname}.', {firstname: 'Johnny', lastname: 'Bravo'})
* @param {string} template - the string template
* @param {Object} data - key value pairs
* @return {string} the formated string
*/
function sprintf(template, data){
let keys = Object.keys(data)
let values = keys.map(k => data[k])
return new Function(...keys, `return \`${template}\`;`)(...values)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment