ff-worker-dist/lib/lodash.mixin.js

112 lines
3.0 KiB
JavaScript
Executable File

const convertFns = {
null2json: (data) => Object.create(),
null2array: (data) => [],
null2number: (data) => 0,
null2bool: (data) => false,
null2string: (data) => '',
null2integer: (data) => 0,
null2float: (data) => 0,
string2json: (data) => data ? JSON.parse(data) : '{}',
string2array: (data) => data.substr(0, 1) === '[' && data.substr(-1) === ']' ? JSON.parse(data) : data.split(','),
string2number: (data) => data == '' ? 0 : +data,
string2integer: (data) => data == '' ? 0 : +data,
string2float: (data) => data == '' ? 0 : +data,
string2bool: (data) => {
switch (`${data}`.toLowerCase()) {
case '0':
case 'false':
case '[]':
case '{}':
return false
}
return !!data
},
string2string: (data) => data,
json2json: (data) => data,
json2array: (data) => data ? Object.values(data) : [],
json2number: (data) => Object.keys(data).length,
json2integer: (data) => Object.keys(data).length,
json2float: (data) => Object.keys(data).length,
json2bool: (data) => Object.keys(data).length > 0,
json2string: (data) => data ? JSON.stringify(data) : '',
array2json: (data) => ({ ...data }),
array2array: (data) => data,
array2number: (data) => data.length,
array2integer: (data) => data.length,
array2float: (data) => data.length,
array2bool: (data) => data.length > 0,
array2string: (data) => JSON.stringify(data),
number2json: (data) => ({}),
number2array: (data) => [data],
number2number: (data) => data,
number2integer: (data) => data,
number2float: (data) => data,
number2bool: (data) => !!data,
number2string: (data) => data.toString(),
boolean2json: (data) => ({}),
boolean2array: (data) => [],
boolean2number: (data) => +data,
boolean2integer: (data) => +data,
boolean2float: (data) => +data,
boolean2bool: (data) => data,
boolean2string: (data) => data ? 'true' : 'false',
}
const toPrimitive = (data, type) => {
let sourceType = 'string'
if (Array.isArray(data)) {
sourceType = 'array'
} else {
sourceType = typeof data
}
if (_.isObject(data)) {
sourceType = 'json'
}
const fn = `${sourceType}2${type}`
return Reflect.has(convertFns, fn) ? convertFns[fn](data) : data
}
const toPairsDeep = (obj, i) => _.flatMap(
_.toPairs(obj), ([k, v]) =>
_.isObjectLike(v) ? toPairsDeep(v, k) : [[`${_.isUndefined(i) ? '' : i + '.'}${k}`, v]]
)
const deepSome = (items, func = () => false) => _.some(items, (item) => {
if (_.some(item, func)) {
return true
}
if (!_.isEmpty(item) && (_.isPlainObject(item) || _.isArray(item))) {
return deepSome(item, func)
}
})
const replaceKeys = (obj, keyMap) => {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(item => replaceKeys(item, keyMap));
}
return Object.keys(obj).reduce((acc, key) => {
if (keyMap[key]) {
acc[keyMap[key]] = replaceKeys(obj[key], keyMap);
} else {
acc[key] = replaceKeys(obj[key], keyMap);
}
return acc;
}, {});
}
_.mixin({ toPrimitive, toPairsDeep, deepSome, replaceKeys })