/**
 * Copyright 2016 the WHATAP project authors. All rights reserved.
 * Use of this source code is governed by a license that
 * can be found in the LICENSE file.
 */

var HashUtil  = require('../util/hashutil');

function ArrayUtil(){
}
function _hash(str) {
    var h = 0, i, chr, len;
    if (str.length === 0) return h;
    for (i = 0, len = str.length; i < len; i++) {
        chr   = str.charCodeAt(i);
        h  = ((h << 5) - h) + chr;
        h |= 0; // Convert to 32bit integer
    }
    return h;
}
function _hashFloat(v) {
    var b  = Buffer.alloc(64);
    b.writeFloatBE(v);
    return b.readInt32BE();
}

ArrayUtil.isExist = function(arr, key){
    if(arr===null || arr === undefined) return false;

    for(var i = 0 ; i < arr.length; i++){
        if(arr[i] === key) return true;
    }
    return false;
};

ArrayUtil.isA = function(arr){
    if(arr===null || arr === undefined) return false;
    return Array.isArray(arr);
};

ArrayUtil.compare = function(v1, v2){
    if(Array.isArray(v1)===false){
        return -1;
    }
    if(Array.isArray(v2)===false){
        return 1;
    }
    
    var l_len = v1.length,
        r_len = v2.length;
    for(var i=0; i<l_len && i < r_len; i++) {
        if(v1[i] > v2[i]) {
            return 1;
        }
        if(v1[i] < v2[i]) {
            return -1;
        }
    }
    return l_len - r_len;
}

ArrayUtil.intHash = function(v1){
    if(Array.isArray(v1)===false){
        return 0;
    }
    var h=0;
    for(var i=0, len = v1.length; i<len; i++) {
        h = h ^ v1[i];
    }
    return h;
}
ArrayUtil.floatHash = function(v1){
    if(Array.isArray(v1)===false){
        return 0;
    }
    var h=0;
    for(var i=0, len = v1.length; i<len; i++) {
        h = h ^ _hashFloat(v1[i]);
    }
    return h;
}
ArrayUtil.strHash = function(v1){
    if(Array.isArray(v1)===false){
        return 0;
    }
    var h=0;
    for(var i=0, len = v1.length; i<len; i++) {
        h = h ^ _hash(v1[i]);
    }
    return h;
}

ArrayUtil.equals = function(v1, v2){
    if(v1===v2){
        return true;
    }else{
        return this.compare(v1,v2)===0;
    }
}
            
module.exports = ArrayUtil;