Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 判断两个数组嵌套结构一致 #22

Open
sunhengzhe opened this issue May 17, 2018 · 1 comment
Open

javascript 判断两个数组嵌套结构一致 #22

sunhengzhe opened this issue May 17, 2018 · 1 comment

Comments

@sunhengzhe
Copy link
Member

sunhengzhe commented May 17, 2018

在 Array 原型链上添加一个方法 sameStructureAs,用于比较该数组与接收参数的 嵌套结构是否一致

示例:

 // should return true
[ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] );          
[ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] );  

 // should return false 
[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] );  
[ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] );  

// should return true
[ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] ); 

// should return false
[ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] );

// should return false
[ 1, '[' , ']' ].sameStructureAs([ '[', ']', 1 ]);
@sunhengzhe
Copy link
Member Author

Array.prototype.sameStructureAs = function (other) {
	if (!Array.isArray(other)) {
		return false;
	}
	
	const selfStruc = JSON.stringify(this);
	const otherStruc = JSON.stringify(other);
	
	const formatStruc = (str) => str.replace(/(")[\[\]]\1/g, '').replace(/[^\[\],]/g, '');
	
	return formatStruc(selfStruc) === formatStruc(otherStruc);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant