Algo| Codes| getBySelector| form
2024-10-27 本文已影响0人
玫瑰的lover
getBySelector
export const obj = {
selector: { to: { toutiao: "FE coder" } },
target: [1, 2, { name: "byted" }],
};
const getBySelector = (...args) => {
const source = args[0];
const selectors = args.slice(1);
const res: any[] = [];
selectors.forEach((s) => {
const arr = s.split(/\.|\[|\]/g);
const notEmptyArr = arr.filter((v) => v);
const v = notEmptyArr.reduce((prev, item) => {
return prev?.[item];
}, source);
res.push(v);
});
return res;
};
getBySelector(obj, "selector.to.toutiao", "target[0]", "target[2].name");
formatWithComma
const test: string = "1234567890";
const formatWithComma = (s: string) => {
if (s.length < 4) {
return s;
}
let res = "";
const seperator_char = ",";
const seperator_space = 3;
let count = 0;
for (let i = s.length - 1; i >= 0; i--) {
count++;
res = s[i] + res;
if (count === seperator_space) {
res = seperator_char + res;
count = 0;
}
}
return res;
};
console.log(formatWithComma(test), "Test utils is running");
mergeSortedArray
export const mergeSortedArr = (a: Array<number>, b: Array<number>) => {
if (a.length < 1) {
return b;
}
if (b.length < 1) {
return a;
}
try {
const merged = [];
let i = 0;
let j = 0;
while (a[i] && b[j]) {
if (a[i] <= b[j]) {
merged.push(a[i]);
i++;
} else {
merged.push(b[i]);
j++;
}
}
while (i < a.length) {
merged.push(a[i]);
i++;
}
while (j < b.length) {
merged.push(b[j]);
j++;
}
return merged;
} catch (e) {
console.log(`===${e}===`);
}
};