Last active
January 22, 2019 11:45
-
-
Save genadyp/a175b9fa56f1391df1439fb4c0ff5b98 to your computer and use it in GitHub Desktop.
javascripts (js) utils
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
| const { | |
| map, mapKeys, mapValues, isObject, isEmpty, isArray, negate, cond, | |
| stubTrue, curry, includes, flow, identity | |
| } = require('lodash/fp'); | |
| function hookStream(stream, callback, disableOriginal = false) { | |
| const originalWrite = stream.write | |
| stream.write = (function (write) { | |
| return function (string, encoding, fd) { | |
| if (!disableOriginal) { | |
| write.apply(stream, arguments) | |
| } | |
| callback(string, encoding, fd) | |
| } | |
| })(stream.write) | |
| return function () { | |
| stream.write = originalWrite | |
| } | |
| } | |
| function mkdirp(targetDir, { isRelativeToScript = false } = {}) { | |
| const sep = path.sep; | |
| const initDir = path.isAbsolute(targetDir) ? sep : ''; | |
| const baseDir = isRelativeToScript ? __dirname : '.'; | |
| targetDir.split(sep).reduce((parentDir, childDir) => { | |
| const curDir = path.resolve(baseDir, parentDir, childDir); | |
| try { | |
| fs.mkdirSync(curDir); | |
| } catch (err) { | |
| if (err.code !== 'EEXIST') { | |
| throw err; | |
| } | |
| } | |
| return curDir; | |
| }, initDir); | |
| } | |
| /******************** | |
| * lodash/fp complementary functions | |
| ********************/ | |
| const mapKeysDeep1 = curry( | |
| (cb, obj) => { | |
| if (Array.isArray(obj)) { | |
| return map(mapKeysDeep(cb), obj); | |
| } else if (isObject(obj)) { | |
| return mapValues(mapKeysDeep(cb), mapKeys(cb, obj)) | |
| } else { | |
| return obj; | |
| } | |
| } | |
| ) | |
| const mapKeysDeep2 = curry( | |
| (cb, obj) => cond([ | |
| [isArray, map(mapKeysDeep(cb))], | |
| [isObject, flow([mapKeys(cb), mapValues(mapKeysDeep(cb))])], | |
| [stubTrue, identity] | |
| ])(obj) | |
| ) | |
| const ifElse = curry( | |
| (conditionCb, onTrueCb, onFalseCb) => cond([ | |
| [conditionCb, onTrueCb], | |
| [stubTrue, onFalseCb] | |
| ]) | |
| ) | |
| mapWithKey: map.convert({ cap: false }), | |
| isNotEmpty: negate(isEmpty), | |
| included: curry((collection, value) => includes(value, collection)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment