This is the first day of my participation in Gwen Challenge
Without further ado, let’s get right to the code
Field verification Mandatory
/** * Field verification is mandatory@param {object} Obj JSON data *@param {array} RequiredFields Field to be determined. The format is as follows: [{name: a, MSG: 'This field does not exist '}] *@param {array} ForceValidate specifies whether the Number type is 0 and Object can be {} *@return {object} Error object */
export function objValidateRequired (
obj,
requiredFields,
{forceValidateNum = 0, forceValidateObject = 0, forceValidateArray = 0}
) {
let isEmpty = false;
let msg = ' ';
for (let [key, value] of iterEntries(obj)) {
let requiredField = requiredFields.find((m) = > m.name == key);
if (requiredField) {
if (
!value ||
(_.isNumber(value) && forceValidateNum && value == 0) ||
(_.isObject(value) &&
forceValidateObject &&
Object.keys(value).length == 0) ||
(_.isArray(value) && forceValidateArray && value.length == 0)
) {
msg = requiredField.msg;
isEmpty = true; }}else {
msg = `${value.name}Field does not exist '; }}return {isEmpty, msg};
}
/** * Deploys the Iterator interface on any object, such as object using the for of loop, or object.entries () **@param {object} Obj requires the object * of the Iterator interface@return {object} Return object * * let myObj = {foo: 3, bar: 7}; * for (let [key, value] of iterEntries(myObj)) { * console.log(key, value); *} * /
export function* iterEntries (obj) {
let keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
yield[key, obj[key]]; }}let params = {
a: {}};let requiredFields = [{name: 'a'.msg: 'a required 2'}];
console.log(objValidateRequired(params, requiredFields, {forceValidateObject: 1}));
Copy the code
duplicate removal
/ * * * to * *@param {array} Arr needs to de-duplicate the array *@return {array} Return the duplicate array */
export function unique (arr) {
return [...new Set(arr)];
}
Copy the code
Remove leading and trailing Spaces
/** ** removes the leading and trailing Spaces **@param {string} Determine where to remove Spaces *@return {string} Returns the time string */
export function trim (str, position) {
switch (position) {
case 'left':
return str.replace(/(^\s*)/g.' ');
case 'right':
return str.replace(/(\s*$)/g.' ');
default:
return str.replace(/(^\s*)|(\s*$)/g.' '); }}Copy the code
Numbers together
/** ** add the numbers **@param {array} Args An array of added numbers *@return {number} The sum is */
export function accAdd(arg1, arg2) {
if (isNaN(arg1)) {
arg1 = 0;
}
if (isNaN(arg2)) {
arg2 = 0;
}
arg1 = Number(arg1);
arg2 = Number(arg2);
var r1, r2, m, c;
try {
r1 = arg1.toString().split('. ') [1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split('. ') [1].length;
} catch (e) {
r2 = 0;
}
c = Math.abs(r1 - r2);
m = Math.pow(10.Math.max(r1, r2));
if (c > 0) {
var cm = Math.pow(10, c);
if (r1 > r2) {
arg1 = Number(arg1.toString().replace('. '.' '));
arg2 = Number(arg2.toString().replace('. '.' ')) * cm;
} else {
arg1 = Number(arg1.toString().replace('. '.' ')) * cm;
arg2 = Number(arg2.toString().replace('. '.' ')); }}else {
arg1 = Number(arg1.toString().replace('. '.' '));
arg2 = Number(arg2.toString().replace('. '.' '));
}
return (arg1 + arg2) / m;
}
Copy the code
Digital subtraction
/** ** subtract ** from **@param {array} Args An array of added numbers *@return {number} The sum is */
export function accSub(arg1, arg2) {
if (isNaN(arg1)) {
arg1 = 0;
}
if (isNaN(arg2)) {
arg2 = 0;
}
arg1 = Number(arg1);
arg2 = Number(arg2);
var r1, r2, m, n;
try {
r1 = arg1.toString().split('. ') [1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = arg2.toString().split('. ') [1].length;
} catch (e) {
r2 = 0;
}
m = Math.pow(10.Math.max(r1, r2)); //last modify by deeka //
n = (r1 >= r2) ? r1 : r2;
return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
Copy the code
Object mapping, field conversion
/** * Object mapping, which assigns the value of an object to a new object with the same structure but different fields ** Usage scenario: the data processed by the front-end is inconsistent with the data fields required by the back-end **@param {object} Obj1 The JSON object to process *@param {object} Obj2Fileds Objects composed of obj1 fields corresponding to new fields *@param {object} Obj2Fileds Optional. If a field value is an object, recursively rename the fields of obj1 *@return {object} Returns the new object that has been mapped to */
export function O2O (obj1, obj2Fileds, obj3Fileds) {
let newO = {};
for (let [key, value] of iterEntries(obj2Fileds)) {
if (Reflect.has(obj1, key)) {
if (_.isObject(obj1[key])) {
try {
if (Reflect.has(obj3Fileds, key)) {
newO[obj3Fileds[key]] = O2O(obj1[key], value, obj3Fileds);
} else{ newO[key] = O2O(obj1[key], value); }}catch (e) {
console.error(e); }}else{ newO[value] = obj1[key]; }}}return newO;
}
Copy the code
Merge cell logic
/** * merge cell logic, which is used with antD's table component *@param {array} arr
* @param {num} Col Specifies a field to be calculated, for example, the number of rows occupied by the ID field *@return The corresponding fields in the array are all attributes */
export function getColSpanNum(arr, col) {
let rowSpan = {};
arr.forEach((item, index) = > {
if(! rowSpan[item[col]]) { rowSpan[item[col]] = {count: 1.firstIndex: index,
lastIndex: index,
};
} else{ rowSpan[item[col]].count++; rowSpan[item[col]].lastIndex = index; }});return rowSpan;
}
Copy the code
Download the pictures
/** * Download images, sometimes img's download attribute does not work **@param {string} Imgsrc Image link */
export function downImg(imgsrc) {
let image = new Image();
// Resolve cross-domain Canvas pollution
image.setAttribute('crossOrigin'.'anonymous');
image.onload = function() {
let canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext('2d');
context.drawImage(image, 0.0, image.width, image.height);
let url = canvas.toDataURL('image/png'); // Get the base64 encoded data of the image
let a = document.createElement('a'); // Generate an A element
let event = new MouseEvent('click'); // Create a click event
a.download = name || 'photo'; // Set the image name
a.href = url; // Set the generated URL to the A.ref property
a.dispatchEvent(event); // Triggers the click event of A
};
image.src = imgsrc;
}
Copy the code
Finding an ID based on its parent ID is not necessarily the best approach
/** * Tree traversal (children); /** tree traversal (pid); /** tree traversal (children)@param {array} tree
* @param {num} id
* @return Tree ids * /
export function getTreeIds(tree, id) {
let pids = [id];
let c = tree;
function findTreesIds(tree, id) {
for (let i = 0; i < tree.length; i++) {
if(tree[i].id ! = pids[0]) {
if(! tree[i].children) {continue;
}
findTreesIds(tree[i].children, id);
} else{ tree[i].pid ! =0 && pids.unshift(tree[i].pid);
if(tree[i].pid ! =0) {
findTreesIds(c, tree[i].pid);
} else {
return;
}
}
}
}
findTreesIds(tree, id);
return pids;
}
Copy the code
Converts a value to a type
/** * converts a value to a type **@param {number, string} The value value *@param {string} Type Indicates the type to be converted *@param {number} FixedNum preserves several decimals *@return {number, string, float}* /
export function value2Type(value, type, fixedNum = 2) {
if(! type)return value;
switch (type) {
case 'int':
return isNaN(parseInt(value)) ? 0 : parseInt(value);
case 'float':
let n = parseFloat(parseFloat(value).toFixed(fixedNum));
return isNaN(n) ? 0 : Math.abs(n); }}Copy the code
Cartesian product, returns an array
/** * Cartesian product returns an array. **@param {array} Pass in a multidimensional array *@return {array}* /
export function cartesion([...arys]) {
if (arys.length == 0) return [];
if (arys.length == 1) {
let newArr = [];
arys[0].forEach((item) = > {
newArr.push([item]);
});
return newArr;
}
return arys.reduce((prev, item) = > {
let temp = [];
for (let i = 0; i < prev.length; i++) {
for (let j = 0; j < item.length; j++) {
temp.push(
Array.isArray(prev[i]) ? [...prev[i], item[j]] : [prev[i], item[j]] ); }}return temp;
});
}
Copy the code