Skip to content

Commit

Permalink
feat:support all array native method and add all test case
Browse files Browse the repository at this point in the history
  • Loading branch information
fancyzhong committed Jun 26, 2021
1 parent 95b056b commit 3d04930
Show file tree
Hide file tree
Showing 43 changed files with 500 additions and 94 deletions.
8 changes: 6 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ const jestConfig = {
roots: ['<rootDir>'],
testEnvironment: "node",
collectCoverageFrom: [
'test/**/*.{ts}'
'test/**/*.{ts}',
],
setupFilesAfterEnv: [
],
testMatch: [
'<rootDir>/test/*.ts',
'<rootDir>/test/**/*.ts',
// '<rootDir>/test/array-base/fill.ts',
],
testPathIgnorePatterns: [
'<rootDir>/test/_util.ts',
],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': 'ts-jest',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"lint": "eslint ./src --fix --ext js,ts,tsx",
"pub": "npm publish --registry=https://registry.npmjs.org"
},
"version": "1.0.6",
"version": "1.0.7",
"dependencies": {
"@types/jest": "^26.0.23",
"jest": "^27.0.5"
Expand Down
3 changes: 2 additions & 1 deletion rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ module.exports = {
typescript({
exclude: 'node_modules/**',
typescript: require('typescript'),
}),
}),
// 如不想压缩,不配置 terser() 即可
terser(),
],
output: [
Expand Down
5 changes: 0 additions & 5 deletions src/core/build-limu-apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,6 @@ export function buildLimuApis() {
}

const rootMeta = getMetaForDraft(proxyDraft, metaVer);
if (!rootMeta.copy) {
console.log('no copy');
} else {
console.log('has copy');
}
const final = rootMeta.copy || rootMeta.self;

// todo: 留着这个参数,解决多引用问题
Expand Down
25 changes: 17 additions & 8 deletions src/core/data-node-processor.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { isPrimitive, canHaveProto, canBeNum } from '../support/util';
import { isPrimitive, canHaveProto, canBeNum, isSymbol } from '../support/util';
import { ver2MetasList } from '../support/inner-data';
import { metasKey } from '../support/symbols';
import { carefulType2FnKeys, ignoreFnOrAttributeKeys, shouldReturnDirectlyFnOrAttributeKeys } from '../support/consts';
import { carefulType2FnKeys, arrIgnoreFnOrAttributeKeys } from '../support/consts';
import {
getMeta,
getUnProxyValue,
Expand All @@ -11,12 +11,17 @@ import {
setMetasProto,
} from './helper';

// slice、concat 以及一些特殊的key取值等操作无需copy副本
function allowCopyForOp(parentType, op) {
console.log(`parentType ${parentType} op ${op}`);
if (ignoreFnOrAttributeKeys.includes(op)) {
const isArray = parentType === 'Array';
if (isArray && arrIgnoreFnOrAttributeKeys.includes(op)) {
return false;
}
if (parentType === 'Array' && canBeNum(op)) {
// like Symbol(Symbol.isConcatSpreadable) in test case array-base/concat
if (isSymbol(op)) {
return false;
}
if (isArray && canBeNum(op)) {
return false;
}
return true;
Expand All @@ -38,10 +43,14 @@ export function copyDataNode(dataNode, copyCtx, isFirstCall) {

if (dataNodeMeta) {
let selfCopy = dataNodeMeta.copy;
// slice 操作无需copy副本
const allowCopy = allowCopyForOp(parentType, op);
// try {
// console.log(`allowCopy ${allowCopy} op ${op}`);
// } catch (err) {
// console.log(`allowCopy ${allowCopy} op symbol`);
// console.log(op);
// }
if (!selfCopy && allowCopy) {
console.log(`copy for ${op}`);
selfCopy = makeCopy(dataNodeMeta);
dataNodeMeta.copy = selfCopy;

Expand Down Expand Up @@ -112,7 +121,7 @@ export function copyDataNode(dataNode, copyCtx, isFirstCall) {
}


if (shouldReturnDirectlyFnOrAttributeKeys.includes(op) || !allowCopy) {
if (!allowCopy) {
if (selfCopy) return selfCopy[op];
return dataNodeMeta.self[op];
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,4 @@ export function getDataNodeType(dataNode) {
var strDesc = getValStrDesc(dataNode);
const dataType = desc2dataType[strDesc];
return dataType;
}
}
15 changes: 12 additions & 3 deletions src/support/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,24 @@ export const desc2dataType = {
export const arrFnKeys = [
'concat', 'copyWithin', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'flat', 'flatMap',
'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight',
'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'unshift', 'values', 'valueOf',
'reverse', 'shift', 'unshift', 'slice', 'some', 'sort', 'splice', 'values', 'valueOf',
];

export const mapFnKeys = ['clear', 'delete', 'entries', 'forEach', 'get', 'has', 'keys', 'set', 'values'];

export const setFnKeys = ['add', 'clear', 'delete', 'entries', 'forEach', 'has', 'keys', 'values'];

export const ignoreFnOrAttributeKeys = ['slice', 'length', 'constructor'];
export const shouldReturnDirectlyFnOrAttributeKeys = ['slice', 'length', 'constructor'];
// fill,push,pop,splice,shift,unshift should trigger copy, so they are not in arrIgnoreFnOrAttributeKeys

export const arrIgnoreFnOrAttributeKeys = [
'length', 'forEach',
'slice', 'concat', 'find', 'findIndex', 'filter', 'flat', 'flatMap', 'includes', 'reverse',
'indexOf', 'every', 'some', 'constructor', 'join', 'keys', 'lastIndexOf', 'map', 'reduce',
'reduceRight', 'sort', 'values', 'entries',
'copyWithin', 'valueOf',
// copyWithin、valueOf will hit the keys of next line
'asymmetricMatch', 'nodeType',
];

export const carefulType2FnKeys = {
[carefulDataTypes.Map]: mapFnKeys,
Expand Down
4 changes: 4 additions & 0 deletions src/support/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,7 @@ export function canBeNum(val) {
return false;
}


export function isSymbol(maySymbol) {
return typeof maySymbol === 'symbol';
}
69 changes: 69 additions & 0 deletions test/_util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { createDraft, finishDraft, produce } from '../src/index';

export const produceTip = (testDescribe: string) => `${testDescribe} (with produce)`;

export const createDraftTip = (testDescribe: string) => `${testDescribe} (with createDraft, finishDraft)`;

/**
* allow noop pass any params
*/
export function noop(...args: any[]) {
if (args === []) console?.log(args);
}

/**
* common getArrBase handler
* @returns
*/
export function getArrBase() {
return [1, 2, 3];
}

/**
* common compare handler
* new and base should be equal
*/
export function shouldBeEqual(arrNew, arrBase) {
expect(arrNew === arrBase).toBeTruthy();
}
/**
* common compare handler
* new and base should be not equal
*/
export function shouldBeNotEqual(arrNew, arrBase) {
expect(arrNew !== arrBase).toBeTruthy();
}

/**
*
* @param testSuitDesc
* @param testCaseDesc
* @param getArrBase
* @param operateDraft
* @param executeAssertLogic
*/
export function runTestSuit(
testSuitDesc: string,
testCaseDesc: string,
getArrBase: () => any[],
operateDraft: (arrDraft: any[], arrBase: any[]) => void,
executeAssertLogic: (arrNew: any[], arrBase: any[]) => void,
) {
describe(testSuitDesc, () => {
test(createDraftTip(testCaseDesc), () => {
const arrBase = getArrBase();
const arrDraft = createDraft(arrBase);
operateDraft(arrDraft, arrBase);
const arrNew = finishDraft(arrDraft);
executeAssertLogic(arrNew, arrBase);
});

test(produceTip(testCaseDesc), () => {
const arrBase = getArrBase();
const arrNew = produce(arrBase, arrDraft => {
operateDraft(arrDraft, arrBase);
});
executeAssertLogic(arrNew, arrBase);
})
})
}
67 changes: 0 additions & 67 deletions test/arrary.ts

This file was deleted.

9 changes: 9 additions & 0 deletions test/array-base/concat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft) {
const arrTmp = arrDraft.concat([4, 5]);
expect(arrTmp).toMatchObject([1, 2, 3, 4, 5]);
}

runTestSuit('test concat', 'concat', getArrBase, changeDraft, shouldBeEqual);

19 changes: 19 additions & 0 deletions test/array-base/copyWithin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { runTestSuit } from '../_util';

function getArrBase() {
return [100, 200, 1, 2, 3, 4];
}

function changeDraft(arrDraft: any[]) {
const arrTmp = arrDraft.copyWithin(3, 1, 3);
expect(arrTmp).toMatchObject([100, 200, 1, 200, 1, 4]);
}

function compare(arrNew, arrBase) {
expect(arrNew !== arrBase).toBeTruthy();
expect(arrNew).toMatchObject([100, 200, 1, 200, 1, 4]);
expect(arrBase).toMatchObject([100, 200, 1, 2, 3, 4]);
}

runTestSuit('test copyWithin', 'copyWithin', getArrBase, changeDraft, compare);

7 changes: 7 additions & 0 deletions test/array-base/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { runTestSuit, getArrBase, shouldBeNotEqual } from '../_util';

function changeDraft(arrDraft) {
delete arrDraft['0'];
}

runTestSuit('test delete', 'delete', getArrBase, changeDraft, shouldBeNotEqual);
9 changes: 9 additions & 0 deletions test/array-base/entries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft: any[]) {
// return Array Iterator {}
const entries = arrDraft.entries();
expect(entries).toBeTruthy();
}

runTestSuit('test entries', 'entries', getArrBase, changeDraft, shouldBeEqual);
8 changes: 8 additions & 0 deletions test/array-base/every.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft) {
const result = arrDraft.every(item => item !== 0);
expect(result).toBeTruthy();
}

runTestSuit('test every', 'every', getArrBase, changeDraft, shouldBeEqual);
17 changes: 17 additions & 0 deletions test/array-base/fill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { runTestSuit } from '../_util';

function getArrBase() {
return [1, 2, 3, 4, 5, 6];
}

function changeDraft(arrDraft: any[]) {
const result = arrDraft.fill(10, 2, 5);
expect(result).toMatchObject([1, 2, 10, 10, 10, 6]);
}

function compare(arrNew, arrBase) {
expect(arrNew).toMatchObject([1, 2, 10, 10, 10, 6]);
expect(arrBase).toMatchObject([1, 2, 3, 4, 5, 6]);
}

runTestSuit('test fill', 'fill', getArrBase, changeDraft, compare);
8 changes: 8 additions & 0 deletions test/array-base/filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft) {
const result = arrDraft.filter(item => item > 1);
expect(result).toMatchObject([2, 3]);
}

runTestSuit('test filter', 'filter', getArrBase, changeDraft, shouldBeEqual);
8 changes: 8 additions & 0 deletions test/array-base/find.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft) {
const result = arrDraft.find(item => item === 1);
expect(result === 1).toBeTruthy();
}

runTestSuit('test find', 'find', getArrBase, changeDraft, shouldBeEqual);
8 changes: 8 additions & 0 deletions test/array-base/findIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { runTestSuit, getArrBase, shouldBeEqual } from '../_util';

function changeDraft(arrDraft) {
const result = arrDraft.findIndex(item => item === 1);
expect(result === 0).toBeTruthy();
}

runTestSuit('test findIndex', 'findIndex', getArrBase, changeDraft, shouldBeEqual);
Loading

0 comments on commit 3d04930

Please sign in to comment.