JavaScript npm安装Heroku,参考错误未定义

问题描述 投票:0回答:3

document.getElementById("HC").innerHTML = String(hammingCode.encode("11"));


console.log("Encode 1111: ", hammingCode.encode("1111"));

我试图在我的JavaScript代码中使用This汉明代码npm libary,但是我没有从npm安装的经验。我已经完成了npm install hamming-code并且设法安装我相信,我的package.json也更新了“hamming-code”:“0.0.2”。当我开始输入hammingCo ...它会提供示例,编码和解码等,但是当我尝试编码一个简单的字符串时,我得到控制台错误消息'Uncaught(in promise)ReferenceError:hammingCode is not defined' 。该应用程序通过heroku部署。

我是否需要添加任何其他来源,或者包含'var hammingCode = require(“hamming-code”)'?我试图将其包括在内,但仍然无法使其正常运行。

我有一个index.html,其中我的大多数JavaScript是我想要使用汉明码的地方,还有一个index.js,我相信我的大部分服务器代码都是。提前致谢。

javascript node.js heroku npm
3个回答
2
投票

您需要在html文件中包含hamming-code脚本。例如,检查以下示例。

/**
 * hammingEncode - encode binary string input with hamming algorithm
 * @param {String} input - binary string, '10101'
 * @returns {String} - encoded binary string
 */
function hammingEncode(input) {
	if (typeof input !== 'string' || input.match(/[^10]/)) {
		return console.error('hamming-code error: input should be binary string, for example "101010"');
	}

	var output = input;
	var controlBitsIndexes = [];
	var controlBits = [];
	var l = input.length;
	var i = 1;
	var key, j, arr, temp, check;

	while (l / i >= 1) {
		controlBitsIndexes.push(i);
		i *= 2;
	}

	for (j = 0; j < controlBitsIndexes.length; j++) {
		key = controlBitsIndexes[j];
		arr = output.slice(key - 1).split('');
		temp = chunk(arr, key);
		check = (temp.reduce(function (prev, next, index) {
			if (!(index % 2)) {
				prev = prev.concat(next);
			}
			return prev;
		}, []).reduce(function (prev, next) { return +prev + +next }, 0) % 2) ? 1 : 0;
		output = output.slice(0, key - 1) + check + output.slice(key - 1);
		if (j + 1 === controlBitsIndexes.length && output.length / (key * 2) >= 1) {
			controlBitsIndexes.push(key * 2);
		}
	}

	return output;
}


/**
 * hammingPureDecode - just removes from input parity check bits
 * @param {String} input - binary string, '10101'
 * @returns {String} - decoded binary string
 */
function hammingPureDecode(input) {
	if (typeof input !== 'string' || input.match(/[^10]/)) {
		return console.error('hamming-code error: input should be binary string, for example "101010"');
	}

	var controlBitsIndexes = [];
	var l = input.length;
	var originCode = input;
	var hasError = false;
	var inputFixed, i;
	
	i = 1;
	while (l / i >= 1) {
		controlBitsIndexes.push(i);
		i *= 2;
	}

	controlBitsIndexes.forEach(function (key, index) {
		originCode = originCode.substring(0, key - 1 - index) + originCode.substring(key - index);
	});

	return originCode;
}

/**
 * hammingDecode - decodes encoded binary string, also try to correct errors
 * @param {String} input - binary string, '10101'
 * @returns {String} - decoded binary string
 */
function hammingDecode(input) {
	if (typeof input !== 'string' || input.match(/[^10]/)) {
		return console.error('hamming-code error: input should be binary string, for example "101010"');
	}

	var controlBitsIndexes = [];
	var sum = 0;
	var l = input.length;
	var i = 1;
	var output = hammingPureDecode(input);
	var inputFixed = hammingEncode(output);


	while (l / i >= 1) {
		controlBitsIndexes.push(i);
		i *= 2;
	}

	controlBitsIndexes.forEach(function (i) {
		if (input[i] !== inputFixed[i]) {
			sum += i;
		}
	});

	if (sum) {
		output[sum - 1] === '1' 
			? output = replaceCharacterAt(output, sum - 1, '0')
			: output = replaceCharacterAt(output, sum - 1, '1');
	}
	return output;
}

/**
 * hammingCheck - check if encoded binary string has errors, returns true if contains error
 * @param {String} input - binary string, '10101'
 * @returns {Boolean} - hasError
 */
function hammingCheck(input) {
	if (typeof input !== 'string' || input.match(/[^10]/)) {
		return console.error('hamming-code error: input should be binary string, for example "101010"');
	}

	var inputFixed = hammingEncode(hammingPureDecode(input));

	return hasError = !(inputFixed === input);
}

/**
 * replaceCharacterAt - replace character at index
 * @param {String} str - string
 * @param {Number} index - index
 * @param {String} character - character 
 * @returns {String} - string
 */
function replaceCharacterAt(str, index, character) {
  return str.substr(0, index) + character + str.substr(index+character.length);
}

/**
 * chunk - split array into chunks
 * @param {Array} arr - array
 * @param {Number} size - chunk size
 * @returns {Array} - chunked array
 */
function chunk(arr, size) {
	var chunks = [],
	i = 0,
	n = arr.length;
	while (i < n) {
		chunks.push(arr.slice(i, i += size));
	}
	return chunks;
}

/* 
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD.
        define(factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
        // Browser globals (root is window)
        root.hammingCode = factory();
    }
}(this, function () {
    return {
      encode: hammingEncode,
      pureDecode: hammingPureDecode,
      decode: hammingDecode,
      check: hammingCheck
    };
})); */


console.log();
document.getElementById("code").innerHTML	 =
hammingEncode('101010101');
<div id="code">
</div>

1
投票

你的代码示例有点差,我猜你正在使用网页加载的javascript(基于“document.getElementById ...”)

确保你在你的html中加载脚本,我建议你在标签中进行,确保在你的js之前加载库,除非你使用像webpack这样的捆绑工具,否则我怀疑使用require会起作用。

希望它有所帮助,如果没有,请给我们更多信息来帮助你。


1
投票

您在客户端的文件,没有对象hammingCode您是否尝试添加到您的HTML:

<script src="https://cdn.rawgit.com/georgelviv/hamming-code/master/index.js"></script>

我的建议是将hamming-code下载到您的服务器并从html中包含它

© www.soinside.com 2019 - 2024. All rights reserved.