Future
Future

Reputation: 191

JavaScript npm install Heroku, Refrence Error Undefined

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


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

I am trying to use This hamming code npm libary in my JavaScript code, however i dont have much experience with installing from npm. I have done npm install hamming-code and it managed to install i believe, my package.json has also updated with "hamming-code": "0.0.2". When i begin to type hammingCo... it comes up with the examples, encode and decode etc, however when i try to encode a simple string, i get the console error message 'Uncaught (in promise) ReferenceError: hammingCode is not defined'. The app is deployed via heroku.

Do i need to add any additional source, or include 'var hammingCode = require("hamming-code")'? I have tried to include this, but am still unable to get it working.

I have an index.html where most of my JavaScript is and where i would like to use the hamming code, and an index.js where i believe most of my server code is. Thanks in advance.

Upvotes: 0

Views: 101

Answers (3)

hong4rc
hong4rc

Reputation: 4103

Your file in client, don't have object hammingCode Are you try add to your html:

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

My recommendation is download hamming-code to your server and include it from html

Upvotes: 1

developerKumar
developerKumar

Reputation: 1796

You need to include the hamming-code script in your html file. For example check below example.

/**
 * 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>

Upvotes: 3

Luigi Cordoba Granera
Luigi Cordoba Granera

Reputation: 619

Your code example is a bit poor, I'm guessing you are working in a javascript loaded by a webpage (based on the "document.getElementById...")

Make sure you are loading the script in your html, I suggest you do it in the tag, be sure to load the library before your js and unless you are using a bundling tool like webpack, I doubt using require will work otherwise.

Hope it helps, if it doesn't please give us more info to help you.

Upvotes: 1

Related Questions