# 加法
代码语言:javascript复制add = (v1, v2) => {
v1 = '';
v2 = '';
let r1, r2;
try {
r1 = v1.toString().split('.')[1].length;
} catch (e) {
r1 = 0;
}
try {
r2 = v2.toString().split('.')[1].length;
} catch (e) {
r2 = 0;
}
const m = 10 ** Math.max(r1, r2);
return (mul(v1, m) mul(v2, m)) / m;
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 减法
代码语言:javascript复制sub = (v1, v2) => {
return add(v1, -v2);
};
1 2 3
# 乘法
代码语言:javascript复制mul = (v1, v2) => {
v1 = '';
v2 = '';
let m = 0;
const s1 = v1.toString();
const s2 = v2.toString();
try {
m = s1.split('.')[1].length;
} catch (e) {
}
try {
m = s2.split('.')[1].length;
} catch (e) {
}
return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / 10 ** m;
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 除法
代码语言:javascript复制div = (v1, v2) => {
v1 = '';
v2 = '';
let t1 = 0,
t2 = 0;
try {
t1 = v1.toString().split('.')[1].length;
} catch (e) {
}
try {
t2 = v2.toString().split('.')[1].length;
} catch (e) {
}
const r1 = Number(v1.toString().replace('.', ''));
const r2 = Number(v2.toString().replace('.', ''));
return (r1 / r2) * 10 ** (t2 - t1);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 其它
# 正数向上取整
代码语言:javascript复制// 3453.1 → 4000
ceil = v1 => {
v1 = Math.ceil(v1);
if (v1 === 0) return v1;
let num = Math.pow(10, v1.toString().length - 1);
return mul(Math.ceil(div(v1, num)), num);
};
1 2 3 4 5 6 7
# 首字母大写
代码语言:javascript复制// github → Github
firstUpper = str => {
return str.charAt(0).toUpperCase() str.slice(1);
};
1 2 3 4
# 对象 Key Value 反转
代码语言:javascript复制obj_flip = obj => {
return Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key;
return acc;
}, {});
};
1 2 3 4 5 6