@keepzen/strengthen-build-in.js
v1.2.0
Published
Javascript build-in lib reinforce
Downloads
25
Readme
start()
You can use it as whole:
const {start} = require('@keepzen/strengthen-build-in.js');
start();
Or you can just use a part, such as ExgExp, as fellow:
const {start} = require('@keepzen/strengthen-build-in.js/ExgExp');
start()
stop()
Stop use the reinforce, recover to the buildin status.
Recover the whole status to buildin:
const {stop} = require('@keepzen/strengthen-build-in.js');
stop();
Just recover RegExp to buildin.
const {stop} = require('@keepzen/strengthen-build-in.js/RegExp');
stop();
Array
Array.prototype.last
Get the last element in the array
, if array
is empty, return undefined
.
Examples
test("array.last", () => {
start();
let array = [1, 2, 3];
expect(array.last).toBe(3);
stop();
expect(array.last).toBe(undefined);
expect('last' in array).toBe(false);
});
Array.prototype.first
Get the first element in the array
, if array
is empty, return undefined
.
Examples
test('array.first', () => {
start();
let array = [1, 2, 3];
expect(array.first).toBe(1);
stop();
expect(array.first).toBe(undefined);
expect('first' in array).toBe(false);
})
Array.prototype.order(fun)
Sort the arry
with fun
get a new orderd array.
order(fun)
create a new array, but not change the origin array.
Parameters
fun
:=(a:any,b:any)=>int=
Returns Array
Examples
test('array.order(fn)', () => {
start();
let fn = (a, b) => a - b;
let a1 = [7, 3, 1, 4, 6];
let a2 = [...a1];
let a3 = [...a1];
a2.sort(fn);
expect(a1.order(fn)).toMatchObject(a2);
expect(a1).toMatchObject(a3);
stop();
});
Array.prototype.reject(fun)
Filter out the array
.
If fun
return true
, the ele
will not included in result, else included.
Parameters
fun
:(ele:any,index:int)=> boolean
Returns Array
.
Examples
test('array.reject(fn)', () => {
start();
let a1 = [7, 3, 1, 4, 6];
let fn1 = (a) => a % 2 == 0;
let fn2 = (a) => a % 2 == 1;
expect(a1.reject(fn1)).toMatchObject(a1.filter(fn2));
stop();
})
Array.prototype.zip(arrayLikelyObj)
Zip the array
with arrayLikelyObj
.
Parameters
arrayLikelyObj
: An array likly object
Examples
test('array.zip(arrayLike)', () => {
start();
let numbers = [1, 2, 3, 4];
let letters = ['a', 'b', 'c'];
let ret = numbers.zip(letters);
expect(ret.length).toBe(numbers.length);
expect(ret).toMatchObject([[1, "a"], [2, "b"], [3, "c"], [4, undefined]]);
stop();
})
Array.prototype.all(fun[,thisForFun])
Similary as Array.prototype.every
but is this array is empty return false
.
Parameters
fun
:(element[,index,array])=>boolean
thisForFun
: thethis
offun
binding.
Return boolean.
Examples
test('array.all(fun)', () => {
start();
let numbers = [1, 2, 3, 4];
expect(numbers.all(a => a > 0)).toBe(true);
expect(numbers.all(a => a < 4)).toBe(false);
expect([].all(a => a == 4)).toBe(false);
stop();
})
Array.prototype.groupBy(fun)
Return a array of array.
The inner array hava property name
.
fun
expect take one argument and return a value.
The returned value is used as the name
propery of the inner array.
Examples
test('array.groupBy(fn)', () => {
start();
let [a, b] = [1, 2, 3, 4].groupBy(n => n % 2 ? "odd" : "even");
const odds = [1, 3]; odds.name = 'odd';
const evens = [2, 4]; evens.name = 'even';
expect(a).toMatchObject(odds);
expect(b).toMatchObject(evens);
stop();
})
String
String.prototype.match(regexp[,index])
Match the string
from index
.
Parameters
pattern
:(String|ExgExp)
index
: int (optional, default0
)
Examples
test('str match', () => {
start();
const str = 'abc-abc-abc';
const regexp = /[a-z]{3}/y;
expect(str.match(regexp)).toHaveProperty('index', 0);
expect(regexp.lastIndex).toBe(3);
expect(str.match(regexp)).toBe(null);
expect(regexp.lastIndex).toBe(0);
expect(str.match(regexp, 4)).toHaveProperty('index', 4);
expect(regexp.lastIndex).toBe(0);
});
RegExp
RxgExp.prototype.exec(str[,index])
Parameters
str
: String. The string from which you want to exactor pattern.index
:int. Match from where to begin. (optional, default0
)
Examples
test('reg.exec(str,index)', () => {
start();
let reg = /abc/g;
let str = "eabc-abc-abc"
let ret = reg.exec(str)
expect(ret.index).toBe(1);
expect(reg.lastIndex).toBe(4);
expect(reg.exec(str).index).toBe(5);
expect(reg.lastIndex).toBe(8);
expect(reg.exec(str).index).toBe(9);
ret = reg.exec(str, 0);
expect(ret.index).toBe(1);
expect(reg.lastIndex).toBe(4);
expect(reg.exec(str).index).toBe(5);
expect(reg.lastIndex).toBe(8);
expect(reg.exec(str).index).toBe(9);
})
RxgExp.prototype.test(str[,index])
Parameters
str
:String. The string be tested.index
:int. From where to begin the test, default is zero. (optional, default0
)
Examples
test('reg.test(str,index)', () => {
start();
let reg = /abc/y;
let str = "eabc-abc-abc"
let ret = reg.test(str)
expect(ret).toBe(false);
expect(reg.lastIndex).toBe(0);
ret = reg.test(str, 1);
expect(ret).toBe(true);
expect(reg.lastIndex).toBe(4);
expect(reg.test(str)).toBe(false);
let reg2 = /abc/y;
reg2.lastIndex = 5;
expect(reg.test(str, 5)).toBe(reg2.test(str));
expect(reg.lastIndex).toBe(reg2.lastIndex);
})
Number
Number.prototype.toFixed(minIntegerLength[,maxFloatLength])
Parameters
minIntegerLength
:uint.maxFloatLength
:uint. IfmaxFloatLong
be ignored, methold will same as the origintoFixed
. (optional, defaultnull
)
Returns String.
Examples
require('./Number').start();
test('Number.toFixed(n)', () => {
expect((1).toFixed(2)).toBe('1.00');
expect((1).toFixed(0, 1)).toBe('1.0');
expect((1).toFixed(2, 2)).toBe('01.00');
expect((1).toFixed(2, 0)).toBe('01');
expect((-1).toFixed(2, 2)).toBe('-1.00');
expect((-1).toFixed(3, 2)).toBe('-01.00');
expect((-1).toFixed(4, 2)).toBe('-001.00');
})
Number.prototype.round({endAfterPoint[, roundInGreaterThan = 4]})
Parameters
- endAfterPoint: int, special after the point how many digits should to keep
- roundInGreaterThan: int ∈ [1,9], default is 4.
Examaple
test('number.round({afterPoint,roundInGreateThan=4})', () => {
expect((2.501).round({ endAfterPoint: 2 })).toBe(2.50)
expect((2.501).round({ endAfterPoint: 2 })).toBe((2.504).round({ endAfterPoint: 2 }))
expect((2.501).round({ endAfterPoint: 2 })).toBeLessThan((2.505).round({ endAfterPoint: 2 }))
expect((2.510).round({ endAfterPoint: 2 })).toBe((2.506).round({ endAfterPoint: 2 }))
expect((-2.501).round({ endAfterPoint: 2 })).toBe(-2.5)
expect((-2.504).round({ endAfterPoint: 2 })).toBe(-2.5)
expect((-2.505).round({ endAfterPoint: 2 })).toBe(-2.51)
})
Date
Date.prototype.format(fmt)
Like the Unix date
format. But just subset.
Parameters
fmt
: string
Returns String.
Examples
test('date.format(fmt)', () => {
require('./Date').start();
const { start, stop } = require('./Number')
start();
let d = new Date();
let str = d.format('%Y-%m-%d');
let m = (d.getMonth() + 1).toFixed(2, 0)
let day = d.getDate().toFixed(2, 0);
let shouldStr = `${d.getFullYear()}-${m}-${day}`;
stop();
expect(str).toBe(shouldStr);
})
Date.prototype.after({d,m,s})
Get the time after this date,with unit of d-ay, m-inute, or s-econd.
parameters
- {d}: d:uint. Unit with day, default is 0.
- {m}: m:unit. Unit with minute, default is 0.
- {s}: s:unit. Unit with second, dfault is 0.
Retun a Date after the special time.
Examples
test('date.after({})', () => {
let date = new Date();
let after10Days = date.after({ d: 10 });
expect(after10Days - date).toBe(10 * 24 * 3600 * 1000);
let after10Minus = date.after({ m: 10 });
expect(after10Minus - date).toBe(10 * 60 * 1000);
});
Date.prototype.plus({d,m,s})
Alias of Date.prototype.after()
Retun a Date after the special time.
Examples
test('date.plus({})', () => {
let date = new Date();
let after10Days = date.plus({ d: 10 });
expect(after10Days - date).toBe(10 * 24 * 3600 * 1000);
let after10Minus = date.plus({ m: 10 });
expect(after10Minus - date).toBe(10 * 60 * 1000);
let after10Seconds = date.plus({ s: 10 });
expect(after10Seconds - date).toBe(10 * 1000);
});
Date.prototype.before({d,m,s})
Get the time before this date, with unit d-ay, m-inute, or s-econd.
parameters
- {d}: d:uint. Unit with day, default is 0.
- {m}: m:unit. Unit with minute, default is 0.
- {s}: s:unit. Unit with second, dfault is 0.
Retun a Date after the special time.
Examples
test('data.before()', () => {
let date = new Date();
let before10Days = date.before({ d: 10 });
expect(before10Days - date).toBe(-10 * 24 * 3600 * 1000);
let before10Minus = date.before({ m: 10 });
expect(before10Minus - date).toBe(-10 * 60 * 1000);
})
Date.prototype.minus({d,m,s})
Alias of Date.prototype.before()
.
Date.prototype.timeZone : string
The time zone of current system.
- "+8" mean east 8 time zone.
- "-8" mean west 8 time zone.
Examples
test("date.timeZone", () => {
let date = new Date();
expect(date.timeZone).toBe('+8');
})
Date.prototype.toString([fmt]) : string
fmt
:string
default is ="%Y-%m-%d %H-%M-%S"=
Object
Object.prototype.not_instanceof(obj)
If you want to check whether object
is a instance of Type
,
it just like:
if(object instanceof Type){
console.log('a');
}else{
console.log('b');
}
So, the fellow lines are what I wrote, when I want to
check whether object
is not an instance of Type
:
if(! object instaceof Type ){
console.log('a');
}else{
console.log('b');
}
But it is WRONG.
Because ! object instaceof Type
is same as !(object) instaceof Type
,
but NOT same as !(object instaceof Type)
.
Now with help of not_instanceof(Type)
,
we can write code fellows our thought more smoothly:
if( object.not_instanceof(Type)){
console.log('a');
}else{
console.log('b');
}
Parameters
- aClass: Class
Returns boolean.
Examples
test('obj.not_instanceof(Type)', () => {
start();
let n = 1;
expect(n.not_instanceof(Number)).toBe(false);
expect(n.not_instanceof(Function)).toBe(true);
stop();
})
Object.is_primary_type(v)
Check if v
is primary type.
If a value is not a instance of Object
,
it is a primary type.
Parameters
v
: any
Returns boolean.
Examples
test('Object.primary_type(v)', () => {
start();
expect(Object.is_primary_type(1)).toBe(true);
expect(Object.is_primary_type("a")).toBe(true);
expect(Object.is_primary_type(null)).toBe(true);
expect(Object.is_primary_type(undefined)).toBe(true);
expect(Object.is_primary_type(Symbol())).toBe(true);
expect(Object.is_primary_type(Symbol)).toBe(false);
stop();
})
Object.freeze(v)
Freeze v
deeply or shallowly.
Parameters
v
: anyarg$1
: Object (optional, default{deep:true}
)
Examples
test('Object.freeze(obj)', () => {
start();
let obj = Object.freeze({ z: 1, objc: { a: 2 } });
obj.a = 'a';
expect(`a` in obj).toBe(false);
delete obj.z;
expect(obj.z).toBe(1);
expect(Object.isFrozen(obj.objc)).toBe(true);
stop();
obj = Object.freeze({ z: 1, objc: { a: 2 } });
expect(Object.isFrozen(obj)).toBe(true);
expect(Object.isFrozen(obj.objc)).toBe(false);
})
Set
Set.prototype.not_has(v)
Parameters
v
:any
Returns boolean
Examples
test('set.not_has(v)', () => {
let a = new Set();
expect(a.not_has(0)).toBe(!a.has(0));
})
Set.prototype.diff(iteratable)
Support A is {a,b}, B is {b,c,d}, then C = A - B = {a}.
In Math, that is
∀ e , if e ∈ A, and e ∉ B, then e ∈ C= A - B.
Parameters
- aSet:(Iteratable)
Returns Set.
Examples
test('set.diff(anotherSet)', () => {
let set = new Set([1, 2, 3]);
let setDiff = set.diff([3, 4]);
expect(setDiff.size).toBe(2);
expect(setDiff.not_has(3)).toBe(true);
})
Set.prototype.union(iteratable)
Support A= {a,b}, B = {b,c,d}, then C = A ∪ B = {a,b,c,d}.
In Math as
∀ e ∈ C = A∪B meaning e ∈ A or e ∈ B.
Parameters
- aSet: Iteratable
Returns Set.
Examples
test('set.union(anotherSet)', () => {
let set = new Set([1]);
let set2 = new Set([2]);
let u1 = set2.union(set);
let u2 = set.union(set2);
expect(u1.size).toBe(u2.size);
expect(u1.has(1)).toBe(true);
expect(u1.has(2)).toBe(true);
})
Set.prototype.intersection(aIteratable)
Support A is {a,b}, B is {b,c,d}, then C = A ∩ B = {b}. In Math
∀ e ∈ C= A ∩ B, meaing e ∈ A and e ∈ B.
Parameters
- aSet: Iteratable
Returns Set.
Examples
test('set.intersection(aother)', () => {
let set = new Set([1]);
let set2 = new Set([2]);
let set3 = new Set([1, 2]);
let inters = set.intersection(set2);
expect(inters.size).toBe(0);
let inters2 = set.intersection(set3);
expect([...inters2]).toMatchObject([1]);
})
Set.prototype.disjunctive(aIteratable)
A is {a,b}, B is {b,c,d} The C = A Δ B = {a,c,d}.
In Math ∀ e ∈ C== AΔB, e ∈ A and e ∈ B but e ∉ A∪B.
Also name as symDiff
short for symmetric difference.
Parameters
- aSet: Iteratable
Returns Set.
Examples
test('set.disjunctive()', () => {
let set = new Set([1, 3, 4, 5,]);
let set2 = new Set([2, 3, 4, 5]);
let z = set.disjunctive(set2);
expect(z.size).toBe(2);
expect(z.has(1)).toBe(true);
expect(z.has(2)).toBe(true);
})
Set.prototype.symDiff(aIteratable)
symDiff
short for symmetric difference.
Alias of Set.prototype.disjunctive(aSet)
.
whether(v)
Check whehte
v
is something.
Make the code read like English.
whether(v)
return a checker. A checker has fellow attributes:
- a_number
- a_bigint
- a_number_or_bigint
- a_string
- a_boolean
- a_function
- a_object
- a_real_object
- a_empty_object
- a_primary
And a method checker.instanceof(Type)
.
Parameters
v
:any
Returns Checker.
Examples
test("whether(a).a_xxx", () => {
expect(whether(1).a_number).toBe(true);
expect(whether(new Number(1)).a_number);
expect(whether(1).not.a_string).toBe(true);
expect(whether(null).a_object).toBe(true);
expect(whether(null).a_real_object).toBe(false);
expect(whether({}).a_real_object).toBe(true);
expect(whether({}).a_empty_object).toBe(true);
expect(whether([]).a_empty_object).toBe(true);
expect(whether([1]).not.a_empty_object).toBe(true);
expect(whether({ a: 1 }).not.a_empty_object).toBe(true);
expect(whether(1).a_primary).toBe(true);
expect(whether(new Number(1)).not.a_primary).toBe(true);
expect(whether(null).a_primary).toBe(true);
expect(whether(undefined).a_primary).toBe(true);
expect(whether(Symbol()).a_primary).toBe(true);
})
checker.instanceof(aType)
Parameters
- aType:Type
Return boolean.
Examples
const whether = require('./whether').whether;
test('whether(a).instaceof(Type)', () => {
expect(whether({}).instanceof(Object)).toBe(true);
expect(whether(1).instanceof(Number)).toBe(false);
expect(whether(new Number(1)).instanceof(Number)).toBe(true);
expect(whether(null).instanceof(Object)).toBe(false);
})
checker.not: checker
To reverse the result of checer.a_xxx
.
Examaple
expect(whether([1]).not.a_empty_object).toBe(true);
Math
Math.randomRange({[begin,]end})
Return a number ∈ [begin,end).
- begin:
float
default is 0. - end:
float
.
Examples
const { start, stop } = require('./Math.js');
test('randomRange({end})', () => {
let z = [];
start();
for (let i = 0; i < 10000; i++) {
z.push(Math.randomRange({ end: 100 }));
}
stop();
let mean = z.reduce(
(mean, i) => {
return mean + i / z.length;
}, 0
)
for (let e of z) {
expect(e).not.toBeLessThan(0);
expect(e).toBeLessThan(100);
}
expect(Math.abs(mean - 50)).toBeLessThan(1);
})
test('Math.randomRange({begin,end})', () => {
let z = [];
start();
for (let i = 0; i < 10000; i++) {
z.push(Math.randomRange({ begin: 50, end: 100 }));
}
stop();
const mean = z.reduce(
(mean, i) => {
return mean + i / z.length;
}, 0
)
for (let e of z) {
expect(e).not.toBeLessThan(50);
expect(e).toBeLessThan(100);
}
expect(Math.abs(150 / 2 - mean)).toBeLessThan(10);
})
Math.randomInt( {[begin,]end})
Return a int ∈ [begin,end).
- begin:
float
default is 0. - end:
flaot
.