All files / src/util helper.ts

85.71% Statements 30/35
60% Branches 9/15
100% Functions 8/8
85.29% Lines 29/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75    2x 2x   2x             12x       12x 40x     12x       12x 12x     12x 40x 40x     12x     12x   12x       12x       24x       24x   80x 80x   80x 80x 80x   80x 24x   56x         24x 24x       24x    
 
import { Model, Document, Types, DocumentQuery, Query, Connection } from 'mongoose';
import { pick, PartialDeep, uniq } from 'lodash';
export const pinyinlite = require('pinyinlite');
 
export class Helper {
 
    /**
     * 生成用于模糊查询的关键词字段, 长标题勿用
     * @param val 原始字符串
     */
    static genPinyinKeywords(val: string, cartesian = true) {
        Iif (!val) {
            return [];
        }
 
        let arrResult = pinyinlite(val).filter((item: any) => {
            return item && item.length > 0;
        });
 
        Iif (!cartesian) {
            return arrResult;
        }
 
        const fullResult = Helper.cartesianProductOf(arrResult).map((item: any) => {
            return item.join('');
        });
 
        const simplifyResult = Helper.cartesianProductOf(arrResult.map((item: any) => {
            return item.map((child: any) => {
                return child.substr(0, 1);
            });
        })).map((item: any) => {
            return item.join('');
        });
 
        const result = uniq(fullResult.concat(simplifyResult));
 
        Iif (result.join('').length > 512) {
            throw new Error('gen pinyin keywords too long.');
        }
 
        return result;
    }
 
    static cartesianProductOf(elements: Array<any>): Array<any> {
        Iif (!Array.isArray(elements)) {
            throw new TypeError();
        }
 
        let end = elements.length - 1, result: Array<any> = [];
        function addTo(curr: any, start: any) {
            var first = elements[start],
                last = (start === end);
 
            for (var i = 0; i < first.length; ++i) {
                var copy = curr.slice();
                copy.push(first[i]);
 
                if (last) {
                    result.push(copy);
                } else {
                    addTo(copy, start + 1);
                }
            }
        }
 
        Eif (elements.length) {
            addTo([], 0);
        } else {
            result.push([]);
        }
        return result;
    }
}