测试:
node subseq.js
subseq.js
const {cache,time} = require('./aop');
/**
* 最长公共子序列的问题
* http://www.cnblogs.com/huangxincheng/archive/2012/11/11/2764625.html
*
*/
function mcs(seqA,seqB){
let lenA = seqA.length;
let lenB = seqB.length;
if(lenA==0 || lenB ==0){
return '';
}else{
let tailA = seqA[lenA-1];
let tailB = seqB[lenB-1];
let subA = seqA.substr(0,lenA-1);
let subB = seqB.substr(0,lenB-1);
if(tailA===tailB){
return mcs(subA,subB)+tailA;
}else{
let res1 = mcs(subA,seqB);
let res2 = mcs(seqA,subB);
return res1.length>res2.length?res1:res2;
}
}
}
mcs = cache(mcs);
cache.clear();
function main(){
let seqA = '<artifactId>mybatisplus-spring-boot-starter</artifactId>';
let seqB = '<artifactId>spring-boot-starter-jdbc</artifactId>';
let res = mcs(seqA,seqB);
console.info(`最长公共子序列:${res}`);
}
time(main)();
const costTime = time.costTime;
console.info(`耗时:${costTime}ms`);
aop.js
/**
* 将函数变成具有缓存功能的函数
*
* */
function cache(func){
let mycache = cache.cache;
if(mycache==null){
mycache = cache.cache = {};
}else{
let curFuncName = cache.funcName;
if(curFuncName!=func.name){
cache.cache = {};
cache.funcName = func.name;
}
}
return function(...args){
let key = JSON.stringify(args);
if(mycache[key]!==undefined){
//console.info(`get value form cache, mycache[${key}]=${mycache[key]}`);
return mycache[key];
}else{
mycache[key] = func(...args);
return mycache[key];
}
};
}
cache.clear = function(){
cache.cache = {};
}
/**
* 计时
* */
const time = function(func){
return function(...args){
const begin = Date.now();
const res = func(...args);
const end = Date.now();
time.costTime = end-begin;
return res;
};
};
module.exports = {cache,time};
最新代码地址https://github.com/zhoujiaping/doc/blob/master/nodenode/algol/aop.js