form-cheatsheet/src/functions.js

89 lines
2.1 KiB
JavaScript

/**
* Helper functions
*/
import DlHighlight from './DlHighlight/highlight-xml-html';
/**
* Returns the final segment of a string split by the specified
* separator character(s)
*
* @param {string} str
* @param {string} separator
* @returns {string}
*/
export function basename(str, separator="/") {
return str.substr(str.lastIndexOf(separator) + 1);
}
/**
* Do multiple string replacements with a mapping array
*
* @param {string} str - The string to modify
* @param {string[][]} replacements - map [search, replacement]
* @return {string}
*/
export function replaceMultiple(str, replacements) {
let output = str;
replacements.forEach(pair => {
output = output.replace(pair[0], pair[1]);
});
return output;
}
/**
* Highlight HTML code
*
* @param {string} html
* @return {string}
*/
export function highlightHtml(html) {
return (new DlHighlight({lang: 'html'})).doItNow(html);
}
/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
* The level - OPTIONAL
* Returns : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
* Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
*/
export function dump(arr, level = 0) {
let dumped_text = "";
//The padding given at the beginning of the line.
let level_padding = "";
for(let j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(let item in arr) {
const value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
/**
* Default export map
*/
export default {
basename: basename,
dump: dump,
highlightHtml: highlightHtml,
replaceMultiple: replaceMultiple
};