javaScript - Add key & value to Object - javascript

There is a forEach in my function for create Object:
Please Run code snippet:
angular.module('myApp', []).controller('myCntl', function($scope) {
$scope.t = '';
var input = "a,b,c,d,e,r \n1,1,1,1,1,1\n2,2,2,2,2,1 \n3,3,3,3,3,1";
var rows = input.split('\n');
var result = {
header: [],
body: []
};
//Get Header
var headerString = rows[0].split(',');
headerString.forEach(function(val) {
result.header.push(val);
});
rows.splice(0, 1);
rows.splice(rows.length - 1, rows.length); //delete "" row, from end array
// Get Body 'a,b,c,d,...'
rows.forEach(function(val, i) {
var bodyString = val.split(',');
var objBody = new Object;
bodyString.forEach(function(val, i) {
var strHeader = result.header[i];
objBody[strHeader] = val;
});
result.body.push(objBody);
});
$scope.result = result.body;
$scope.show = function() {
console.log($scope.result)
$scope.t = $scope.result;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" ng-app="myApp" ng-controller="myCntl">
<button ng-click="show()">click me</button>
<span ng-repeat="item in t">
{{item}}
</span>
</div>
And, this is objBody after forEach:
objBody = {
a: "1",
b: "1",
"c": "1"
}
Now, my problem is in key with double qoutation in last record of objBody.
What is it? and Why?! > ("c")

The problem was arising due to the white space between r and \n in the input string. When you split the string by \n, the rows[0] will be "a,b,c,d,e,r ". And after you split it with comma, then the last element will contain the white space like this "r ".
So just change the following line of code
var input = "a,b,c,d,e,r \n1,1,1,1,1,1\n2,2,2,2,2,1 \n3,3,3,3,3,1";
to
var input = "a,b,c,d,e,r\n1,1,1,1,1,1\n2,2,2,2,2,1\n3,3,3,3,3,1";
to fix the issue.
angular.module('myApp', []).controller('myCntl', function($scope) {
$scope.t = '';
var input = "a,b,c,d,e,r \n1,1,1,1,1,1 \n2,2,2,2,2,1 \n3,3,3,3,3,1";
input = input.replace(" ","");
console.log(input);
var rows = input.split('\n');
var result = {
header: [],
body: []
};
//Get Header
var headerString = rows[0].split(',');
headerString.forEach(function(val) {
result.header.push(val);
});
rows.splice(0, 1);
rows.splice(rows.length - 1, rows.length); //delete "" row, from end array
// Get Body 'a,b,c,d,...'
rows.forEach(function(val, i) {
var bodyString = val.split(',');
var objBody = new Object;
bodyString.forEach(function(val, i) {
var strHeader = result.header[i];
objBody[strHeader] = val;
});
result.body.push(objBody);
});
$scope.result = result.body;
$scope.show = function() {
console.log($scope.result)
$scope.t = $scope.result;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" ng-app="myApp" ng-controller="myCntl">
<button ng-click="show()">click me</button>
<span ng-repeat="item in t">
{{item}}
</span>
</div>
EDIT: You have found some answer. But my way for removing white spaces from the dynamic input string would be
input = input.replace(" ","");

I solved problem with split by regexExp:
var myRegex = new RegExp(/\s*\n/);
var rows = input.split(myRegex);
This command split every ' \n' in string. This work for me.

Related

JS RegExp capture all groups and pos for each match

Statement:
I am new to RegExp and trying to learn capture groups in javascripts
I am using https://regex101.com/r/COYhIc/1 for testing
see attached image for character pos column of each match by https://regex101.com
Objective:
I want to print all matches and groups at console (Done)
I want to print character position of each match [see image](remaining)
JSFIDDLE: https://jsfiddle.net/bababalcksheep/p28fmdk4/68/
JavaScript:
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try {
query = new RegExp(isRE[1], isRE[2]);
} catch (e) {}
}
return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
match_no++;
output += `\nMatch ${match_no}\n`;
output += `Full Match, ${ result[0]} , Pos\n`;
for (i = 1; i < result.length; i++) {
output += `Group ${i}, ${ result[i]} , Pos\n`;
}
}
console.log(output);
In your output field use index and lastIndex. exec returns an object with a index property.
output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;
Update for the groups:
I have used a small logic to get the indices:
var m = new RegExp(result[i]);
output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;
function parseQuery(query) {
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
if (isRE) {
try {
query = new RegExp(isRE[1], isRE[2]);
} catch (e) {}
}
return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
match_no++;
output += `\nMatch ${match_no}\n`;
output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;
for (i = 1; i < result.length; i++) {
var m = new RegExp(result[i]);
output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;
}
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="form-group">
<label for="str">String:</label>
<input type="text" class="form-control" id="str" value="source=100, delta=2, source=2121, delta=5">
</div>
<div class="form-group">
<label for="regex">Regex:</label>
<input type="text" class="form-control" id="reg" value="/(source=(\d+))/g">
</div>
<div id="result">
</div>
</div>
FIDDLE
According to docs RegExp.exec, you can retrieve it using index property. So I would add this line into your snippet to retrieve column position for your full match:
`${result.index}-${result.index + result[0].length}`
For subgroups, JS doesn't retrieve index, so a workaround can be achieved using indexOf:
const initialSubGroupIndex = str.indexOf(result[i], result.index);
`${initialSubGroupIndex}-${initialSubGroupIndex + result[i].length}`

Compare two last character in a string

I am programming a calculator in AngularJS. I am stuck on a validating user input. I do not want the user to be able to enter two 2 operators ('+','/','*') next to each other.
Thus every time, I try to compare the last character and the second to last character of the string. But I always find I have two operator characters.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.expression = "";
var liste = ['+', '/', '*'];
$scope.add = function (ope) {
$scope.expression += String(ope);
var der = $scope.expression[$scope.expression.length - 1];
var avantDer = $scope.expression[$scope.expression.length - 2];
if ($scope.expression.length > 3 && liste.includes(der) && liste.includes(avantDer)) {
alert("error");
} else {
$scope.expression += String(ope);
}
};
});
You are very close. The problem is that you are adding the operator to the expression before you have checked if it is valid or not. It is better to check the last character of the existing expression and the new character as a separate variable.
You also want to check if the length of expression is greater than 0 rather than 3 as otherwise, the user could enter two '+' characters straight away when the length is less than 3.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.expression = "";
var liste = ['+', '/', '*'];
$scope.add = function (ope) {
// don't add to expression, just store into der
var der = String(ope);
var avantDer = $scope.expression[$scope.expression.length - 1];
if ($scope.expression.length > 0 && liste.includes(der) && liste.includes(avantDer)) {
alert("error");
} else {
$scope.expression += der;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<button ng-click="add('+')">+</button>
<button ng-click="add('*')">*</button>
<button ng-click="add('/')">/</button>
</div>
<div>
<button ng-click="add('1')">1</button>
<button ng-click="add('2')">2</button>
<button ng-click="add('3')">3</button>
</div>
{{expression}}
</div>
There were two things wrong.
$scope.expression.length > 3 should have been
$scope.expression.length > 2
You were calling $scope.expression += String(ope); twice
I made a minor change below so I could run it in the code snippet window.
I also added subtraction to liste.
var $scope = {
expression: ""
};
var liste = ['+', '/', '*', '-'];
debugger
$scope.add = function (ope) {
var temp = $scope.expression + String(ope);
console.log(temp);
var len = temp.length - 1;
if (len > 1) {
var der = temp[len];
var avantDer = temp[len - 1];
if (liste.includes(der) && liste.includes(avantDer)) {
console.log("error");
} else {
$scope.expression = temp;
}
}
else {
$scope.expression = temp;
}
};
$scope.add('3');
$scope.add('+');
$scope.add('-');
When I call $scope.add('-'); it displays the error like you expect.

How to make a list randomizer

I have been working on a fairly pointless website where there are multiple "random" generators. You can check it out here: randomwordgen.net16.net
As you can see there is an unfinished generator at the bottom, that's what I'm here for. I want to get it to generate a list from things you input. My idea is to add the input field's value to the array that will make the list when you hit "Add to List." Then I will have a separate button that will generate the list using that array. The only problem is that I don't know how to add the string to the array when I only know the name of the variable, not the value. If anyone could help me with any of this, that would be great!
This is the code for the whole site:
<!DocType html>
<html>
<head>
<link rel="shortcut icon" href="https://cdn2.iconfinder.com/data/icons/thesquid-ink-40-free-flat-icon-pack/64/rubber-duck-512.png" type="image/x-icon">
<title>Random Word Generator</title>
<style>
body {
background-color:pink;
}
button.10letter {
background-color: blue;
}
button.5letter {
background-color: blue;
position:relative;
top:50px;
}
button.4letter {
background-color: blue;
position:relative;
top:100px;
}
button.3letter {
background-color: blue;
position:relative;
top:150px;
}
button.Add {
position:relative;
top:50px;
}
</style>
</head>
<body>
<h1 style="color:grey">Random word generator:</h1>
<button class="10letter" onclick="doAlert();" style="color:orange">Generate with 10 letters.</button>
<script>
function createRandomWord(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert() {
alert( "Your word is: "+createRandomWord(10)+" (bonus points if your word is real)." );
}
</script>
<button class="5letter" onclick="doAlert5();" style="color:orange">Generate with 5 letters.</button>
<script>
function createRandomWord5(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert5() {
alert( "Your word is: "+createRandomWord(5)+" (bonus points if your word is real)." );
}
</script>
<button class="4letter" onclick="doAlert4();" style="color:orange">Generate with 4 letters.</button>
<script>
function createRandomWord4(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz♀☺☻ƒ=ù"?',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert4() {
alert( "Your word is: "+createRandomWord(4)+" (bonus points if your word is real)." );
}
</script>
<button class="3letter" onclick="doAlert3();" style="color:orange">Generate with 3 letters.</button>
<script>
function createRandomWord3(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random()*limit);
},
i, word='', length = parseInt(length,10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
function doAlert3() {
alert( "Your word is: "+createRandomWord(3)+" (bonus points if your word is real)." );
}
</script>
<h1 style="color:grey">Name Generator:</h1>
<button style="color:orange" onclick="generator();">Generate</button>
<script>
function generator(){
var first = ["Kick","Stupid","Random Name","Officer","School-Related","Unoriginal","Original","Mousey","Website to name things?","n00b","Error","var first=name.first","Bob","Joe","Boris","Duck","Cheese","Pablo","Stimuli","Last Test Grade","First Word","Puss","Cat","Cherokee", "Jerry", "[Insert Weird First Name Here]"]
var last = ["Me","Idiot","dummy.dummy","randomwordgen.net16.net (shameless advertising)","he went that way","it was him!","DESTRUCTION...","Rats","You need advice for a name, use a website or something! Oh wait.","Opposition","Apple","404 not found","var last=name.last","You sure you want to pick this name?","McGuire","Rox","Knox","Bobert","Green","Raul","Damend","Milk","Positive","Negative","Rocky","Boots","Cherry","Parakeet","[Insert Weird Last Name Here]"]
var randomNumber1 = parseInt(Math.random() * first.length);
var randomNumber2 = parseInt(Math.random() * last.length);
var name = first[randomNumber1] + " " + last[randomNumber2];
alert(name);
}
</script>
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
</body>
</html>
And this is the code for the list part:
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
var arr = [];
arr.push(Word);
}
</script>
</div>
Thanks in advance!
Here is an example in which we take the input value, add it to an array, shuffle the array and then put it in a list <ul>. Every added value is added to the array and re-shuffles the list.
Try this:
EDIT
I added the shuffle function for when you just want to shuffle without adding new values.
var randomList = [];
function appendToArray() {
var word = document.getElementById("Words").value;
randomList.push(word);
updateList(randomList);
document.getElementById("Words").value = "";
}
function updateList(wordsArr) {
shuffleArr(wordsArr);
var list = document.getElementById('list');
list.innerHTML = "";
for (var i =0; i < wordsArr.length; i++) {
var word = wordsArr[i];
var li = document.createElement('li');
li.innerText = word;
list.appendChild(li);
}
}
function shuffleArr(arr) {
var j,
x,
i;
for (var i = arr.length; i; i--) {
j = Math.floor(Math.random() * i);
x = arr[i - 1];
arr[i - 1] = arr[j];
arr[j] = x;
}
}
function shuffleList() {
var list = randomList;
updateList(list);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Shuffle" onClick="shuffleList()">Shuffle List</button>
<h3>List</h3>
<ul id="list"></ul>
You will need to make your array variable global so you can access it from multiple functions:
// declare this only once
var arr = [];
function appendToArray() {
var word = document.getElementById("Words").value;
// check to make sure something was entered
if (word && word.length) {
arr.push(word);
// clear the input box if added to the array
document.getElementById("Words").value = '';
}
}
Then you can have another function that picks whatever you need out of the array, which is now accessible because we moved it to the global scope of your document. You could have another button to empty the array then as well.
Is this what are you looking for?
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
function showArray() {
console.log(arr);
}
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<button id="Add" onClick="showArray()">Show List</button>
</div>
Initialize array outside the function. Otherwise you are making it empty every time you call the function.
<h1 style="color:grey">List Randomizer</h1>
<div>
<input type="text" id="Words">
<button id="Add" onClick="appendToArray()">Add To List</button>
<script>
var arr = [];
function appendToArray() {
var Words = document.getElementById("Words");
var Word = Words.value
arr.push(Word);
}
</script>
</div>

My ng-click is not firing

I'm new to Angular, so please bear with me.
I have an app I'm building where you can hit an "X" or a heart to dislike/like something. I'm using a swipe library called ng-swippy.
I'm trying to use ng-click="clickLike()"for the "Like" button and ng-click="clickDislike()"but neither are firing. I can't figure out what's going on.
Here's the URL:
http://430designs.com/xperience/black-label-app/deck.php
deck.php code
<ng-swippy collection='deck' item-click='myCustomFunction'
data='showinfo' collection-empty='swipeend' swipe-left='swipeLeft'
swipe-right='swipeRight' cards-number='4' label-ok='Cool'
label-negative='Bad'>
</ng-swippy>
The template is called from card-tpl.html:
<div class="ng-swippy noselect">
<div person="person" swipe-directive="swipe-directive" ng-repeat="person in peopleToShow" class="content-wrapper swipable-card">
<div class="card">
<div style="background: url({{person.thumbnail}}) no-repeat 50% 15%" class="photo-item"></div>
<div class="know-label">{{labelOk ? labelOk : "YES"}}</div>
<div class="dontknow-label">{{labelNegative ? labelNegative : "NO"}}</div>
</div>
<div class="progress-stats" ng-if="data">
<div class="card-shown">
<div class="card-shown-text">{{person.collection}}</div>
<div class="card-shown-number">{{person.subtitle}}</div>
</div>
<div class="card-number">{{collection.length - (collection.indexOf(person))}}/{{collection.length}}
</div>
</div>
<div class="container like-dislike" >
<div class="circle x" ng-click="clickDisike()"></div>
<div class="icon-like" ng-click="clickLike()"></div>
<div class="clearfix"></div>
</div>
</div><!-- end person-->
<div class="clearfix"></div>
Controller.js
angular.module('black-label', ['ngTouch', 'ngSwippy'])
.controller('MainController', function($scope, $timeout, $window) {
$scope.cardsCollection = [
{
thumbnail: 'images/deck/thor_01.jpg',
collection: 'thoroughbred',
}, {
thumbnail: 'images/deck/thor_02.jpg',
collection: 'thoroughbred',
},
];
// Do the shuffle
var shuffleArray = function(array) {
var m = array.length,
t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
};
$scope.deck = shuffleArray($scope.cardsCollection);
$scope.myCustomFunction = function(person) {
$timeout(function() {
$scope.clickedTimes = $scope.clickedTimes + 1;
$scope.actions.unshift({ name: 'Click on item' });
$scope.swipeRight(person);
});
};
$scope.clickLike = function(person) {
console.log($scope.count);
// swipeRight(person);
};
$scope.count = 0;
$scope.showinfo = false;
$scope.clickedTimes = 0;
$scope.actions = [];
$scope.picks = [];
var counterRight = 0;
var counterLeft = 0;
var swipes = {};
var picks = [];
var counts = [];
var $this = this;
$scope.swipeend = function() {
$scope.actions.unshift({ name: 'Collection Empty' });
$window.location.href = 'theme-default.html';
};
$scope.swipeLeft = function(person) {
//Essentially do nothing
$scope.actions.unshift({ name: 'Left swipe' });
$('.circle.x').addClass('dislike');
$('.circle.x').removeClass('dislike');
$(this).each(function() {
return counterLeft++;
});
};
$scope.swipeRight = function(person) {
$scope.actions.unshift({ name: 'Right swipe' });
// Count the number of right swipes
$(this).each(function() {
return counterRight++;
});
// Checking the circles
$('.circle').each(function() {
if (!$(this).hasClass('checked')) {
$(this).addClass('checked');
return false;
}
});
$('.icon-like').addClass('liked');
$('.icon-like').removeClass('liked');
$scope.picks.push(person.collection);
// console.log('Picks: ' + $scope.picks);
// console.log("Counter: " + counterRight);
if (counterRight === 4) {
// Calculate and store the frequency of each swipe
var frequency = $scope.picks.reduce(function(frequency, swipe) {
var sofar = frequency[swipe];
if (!sofar) {
frequency[swipe] = 1;
} else {
frequency[swipe] = frequency[swipe] + 1;
}
return frequency;
}, {});
var max = Math.max.apply(null, Object.values(frequency)); // most frequent
// find key for the most frequent value
var winner = Object.keys(frequency).find(element => frequency[element] == max);
$window.location.href = 'theme-' + winner + '.html';
} //end 4 swipes
}; //end swipeRight
});
Any thoughts and help is greatly appreciated!
The ng-click directive is inside an ng-repeat directive inside a directive with isolate scope. To find the clickLike() function it needs to go up two parents:
<!--
<div class="icon-like" ng-click="clickLike()"></div>
-->
<div class="icon-like" ng-click="$parent.$parent.clickLike()"></div>
For information, see AngularJS Wiki - Understanding Scopes.

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Categories

Resources