Last active
March 7, 2018 01:48
-
-
Save coolreader18/9d372c8604fb918a19e7d9647c863cb1 to your computer and use it in GitHub Desktop.
A function to replace characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "replace-character", | |
"version": "1.0.0", | |
"author": "coolreader18", | |
"main": "Replace-character.js", | |
"repo": "gist:9d372c8604fb918a19e7d9647c863cb1", | |
"license": "MIT" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @legume | |
* @name replace-character | |
* @version 1.0.0 | |
*/ | |
(function (root, factory) { | |
if (typeof define === 'function' && define.amd) { | |
define('replace-character', [], factory); | |
} else if (typeof module === 'object' && module.exports) { | |
module.exports = factory(); | |
} else { | |
root.replaceCharacter = factory(); | |
} | |
}(typeof self !== 'undefined' ? self : this, function () { | |
/** | |
* Replaces specified characters with others. | |
* @param {string} input - The input string. | |
* @param {Object} replacements - The keys are the letter to replace and the values are the letters getting replaced. | |
* @param {boolean} [filter=false] - Whether or not to filter out all characters that aren't one of replacements's keys. | |
*/ | |
return function replaceCharacter(input, replacements, filter = false) { | |
var ret = Array.from(input); | |
var counts = Object.keys(replacements) | |
.reduce((obj, cur) => (obj[cur] = -1, obj), {}); | |
if (filter) | |
ret = ret.filter(cur => Object.keys(replacements).includes(cur)); | |
return ret.map((cur, i) => { | |
var replace = replacements[cur]; | |
counts[cur]++; | |
return ({ | |
string: () => replace, | |
"function": () => replace(counts[cur], i), | |
undefined: () => cur | |
})[typeof replace](); | |
}).join(""); | |
}; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment