Web Speech API in_array - javascript

If have this code and it works like charm, but after the first result the in_array function only gives me "false". I cant find the Problem. Every time I restart the recognition, it works for one phrase...
var myArray = [
'Kontakt',
'gehe zu Kontakt',
'navigiere zu Kontakt',
'navigiere zu Kontakte'
];
function in_array(needle, haystack, argStrict)
{
var key = '',
strict = !! argStrict;
if (strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
return true;
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
return true;
}
}
return false;
};
recognition.onresult = function (event)
{
var pos = textArea.getCursorPosition() - interimResult.length;
textArea.val(textArea.val().replace(interimResult, ''));
interimResult = '';
textArea.setCursorPosition(pos);
for (var i = event.resultIndex; i < event.results.length; ++i)
{
if (event.results[i].isFinal)
{
insertAtCaret(textAreaID, event.results[i][0].transcript);
speak = event.results[i][0].transcript;
index = in_array(speak,myArray,false);
alert(speak);
alert(in_array(speak,myArray,false));
if (index)
{
alert(event.results[i][0].transcript);
}
else
{
alert('Keine Übereinstimmung');
}
}
else
{
isFinished = false;
insertAtCaret(textAreaID, event.results[i][0].transcript + '\u200B');
interimResult += event.results[i][0].transcript + '\u200B';
}
}
};
For testing a jsfiddle:
http://jsfiddle.net/p3Fxc/

Related

unable to find out why the value is undefined

so i have a function that's meant to remove an element tag when its clicked on and remove its respective content/ingredient from a separate list. Everything works fine as it should, partially, on the browser, when i check the console there is a TypeError and i can't seem to find out why. I've been at it for the past 3 hours and can't find a solution, someone please help. Below is the code. You will need to input "," after each word to create a new tag, and due to the no css added you will need to click on the word to remove it (words in the row directly after the input).
const ingredientsInput = document.querySelector('#ingredients'),
ingredientsContainer = document.querySelector('.ingredients__tag');
let ingredientsArray = [];
ingredientsInput.addEventListener('input', () => {
if (ingredientsInput.value.includes(',')) {
let v = ingredientsInput.value.replace(',', '');
if(v != '' && v != ',') {
let s = document.createElement('span');
s.setAttribute('class', 'tag__item');
s.innerHTML = v;
ingredientsContainer.appendChild(s);
ingredientsArray.push(v);
recipesInclude(v, true);
ingredientsInput.value = "";
} else if(v = ',') {
ingredientsInput.value = "";
}
removeItem();
console.log(ingredientsArray);
}
});
function removeItem() {
const ingredientsItem = ingredientsContainer.querySelectorAll('.tag__item');
ingredientsItem.forEach(e => {
e.addEventListener('click', () => {
recipesInclude(e.innerHTML, false);
removeArray(ingredientsArray, e.innerHTML, false);
e.remove();
console.log(ingredientsArray);
});
});
}
function removeArray(array, index, result) {
for(i = 0; i < array.length; i++){
if(array[i] === index) {
array.splice(i, 1);
if(result) {
return array;
}
}
}
}
function recipesInclude(ingredient, statement) {
ingredientLead = document.querySelector('.list');
if(statement) {
if(ingredientLead.innerText.length > 0) {
ingredientLead.innerHTML += ', ' + ingredient;
} else {
ingredientLead.innerHTML += ingredient;
}
} else {
ingredientSplit = ingredientLead.innerText.split(", ");
if(ingredientSplit.length > 1) {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true).join(", ");
} else {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true);
}
}
}
<input type="text" name="ingredients" id="ingredients" onkeyup="this.setAttribute('value', this.value);" placeholder="" class="form__control">
<div class="ingredients__tag"></div>
<p class="list"></p>
Check this code this may Help
I added return array when no condition is matched
const ingredientsInput = document.querySelector('#ingredients'),
ingredientsContainer = document.querySelector('.ingredients__tag');
let ingredientsArray = [];
ingredientsInput.addEventListener('input', () => {
if (ingredientsInput.value.includes(',')) {
let v = ingredientsInput.value.replace(',', '');
if (v != '' && v != ',') {
let s = document.createElement('span');
s.setAttribute('class', 'tag__item');
s.innerHTML = v;
ingredientsContainer.appendChild(s);
ingredientsArray.push(v);
recipesInclude(v, true);
ingredientsInput.value = "";
} else if (v = ',') {
ingredientsInput.value = "";
}
removeItem();
//console.log(ingredientsArray);
}
});
function removeItem() {
const ingredientsItem = ingredientsContainer.querySelectorAll('.tag__item');
ingredientsItem.forEach(e => {
e.addEventListener('click', () => {
recipesInclude(e.innerHTML, false);
removeArray(ingredientsArray, e.innerHTML, false);
e.remove();
console.log(ingredientsArray);
});
});
}
function removeArray(array, index, result) {
for (i = 0; i < array.length; i++) {
if (array[i] === index) {
array.splice(i, 1);
if (result) {
return array;
}
}
}
return array;
}
function recipesInclude(ingredient, statement) {
ingredientLead = document.querySelector('.list');
if (statement) {
if (ingredientLead.innerText.length > 0) {
ingredientLead.innerHTML += ', ' + ingredient;
} else {
ingredientLead.innerHTML += ingredient;
}
} else {
ingredientSplit = ingredientLead.innerText.split(", ");
if (ingredientSplit.length > 1) {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true).join(", ");
} else {
ingredientLead.innerHTML = removeArray(ingredientSplit, ingredient, true);
}
}
}
<input type="text" name="ingredients" id="ingredients" onkeyup="this.setAttribute('value', this.value);" placeholder="" class="form__control">
<div class="ingredients__tag"></div>
<p class="list"></p>

handle multiple conditions on a string

I've created a function which takes a string and replace it's ending substring, so if the string ends with AddFiche, EditFiche or Fiche they should be replaced with Liste, and some other conditions this is what I tried:
function _getParentComponent(component){
if(component.endsWith('AddFiche')){
return component.replace('AddFiche', 'Liste');
}else if(component.endsWith('EditFiche')){
return component.replace('EditFiche', 'Liste');
}else if(component.endsWith('Fiche')){
return component.replace('Fiche', 'Liste');
}else if(component === "selection"){
if($rootRouter._outlet.previousInstruction.componentType === "import"){
return "import";
}
}else if(component === "result"){
if($rootRouter._outlet.previousInstruction.componentType === "selection"){
return "import";
}
}else if(component.startsWith("request")){
if($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting"){
return "dynamicRouting";
}
}else{
return component;
}
}
As you can see there are a lot of if elses, isn't there any other way to do this ? since I might add other conditions later, and the code looks ugly with all those if elses.
var replaces = [{
match: 'AddFiche',
replace: 'Liste'
},
{
match: 'EditFiche',
replace: 'Liste'
},
{
match: 'Fiche',
replace: 'Liste'
}
]
function _getParentComponent(component) {
var done = false;
for (var r of replaces) {
if (component.endsWith(r.match)) {
return component.replace(r.match, r.replace);
}
}
if (component === "selection") {
if ($rootRouter._outlet.previousInstruction.componentType === "import") {
return "import";
}
} else if (component === "result") {
if ($rootRouter._outlet.previousInstruction.componentType === "selection") {
return "import";
}
} else if (component.startsWith("request")) {
if ($rootRouter._outlet.previousInstruction.componentType === "dynamicRouting") {
return "dynamicRouting";
}
} else {
return component;
}
}
console.log("Input: LoremIpsumFiche");
console.log("Output:",_getParentComponent("LoremIpsumFiche"));
Can be this
var ends = ['One', 'Two', 'Wood'];
var words = ['LOne', 'ROnes', 'Two2', 'TwoTwo', 'No Wood', 'Woodless'];
var replaced = "REPLACED";
for(var i = 0; i < words.length; i++) {
for(var j = 0; j < ends.length; j++) {
if(words[i].endsWith(ends[j])) {
words[i] = words[i].replace(new RegExp(ends[j] + '$'), replaced);
break;
}
}
}
console.log(words);

Infinite loop in list iterator

I created a list iterator but when trying traverse a list backward the loop runs infinitely. What I did wrong?
function List() {
this.listSize=0;
this.pos=0;
this.dataStore =[];
this.append = append;
this.currPos = currPos;
this.end = end;
this.front = front;
this.length = length;
this.moveTo = moveTo;
this.next = next;
this.prev = prev;
}
function append(element) {this.dataStore[this.listSize++]=element;}
function currPos() {return this.pos;}
function end() {this.pos = this.listSize-1;}
function front() {this.pos =0;}
function length() {return this.listSize;}
function moveTo(position) {this.pos = position;}
function prev() {if(this.pos > 0) --this.pos;}
function next() {if(this.pos < this.listSize) ++this.pos;}
var names = new List();
names.append("A"); names.append("B"); names.append("C");
for(names.end(); names.currPos() >= 0; names.prev()) {console.log(names.getElement());}
Your loop only terminates when the current list position is less than zero, but your .prev() function won't allow that to happen.
To fix it? Well, that's a matter of opinion, but if you're going to the trouble of implementing a list class you might as well make a native .forEach function:
function forEach(callback) {
for (var i = 0; i < this.listSize; ++i)
callback(this.dataStore[i], i);
}
Then you can do:
names.forEach(function(name) { console.log(name); });
I ran into a similar problem when trying to implement a list ADT from the book "Data Structures and Algorithms" and came to find out that the author re-wrote that section in later versions to look like this:
module.exports = List;
function List() {
this.listSize = 0;
this.pos = 0;
this.dataStore = [];
this.clear = clear;
this.find = find;
this.toString = toString;
this.insert = insert;
this.append = append;
this.remove = remove;
this.front = front;
this.end = end;
this.prev = prev;
this.next = next;
this.length = length;
this.currPos = currPos;
this.moveTo = moveTo;
this.getElement = getElement;
this.length = length;
this.contains = contains;
this.hasNext = hasNext;
this.hasPrevious = hasPrevious;
this.insertIf = insertIf;
}
function append(element) {
this.dataStore[this.listSize++] = element;
}
function find(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if (this.dataStore[i] === element) {
return i;
}
}
return -1;
}
function remove(element) {
var foundAt = this.find(element);
if (foundAt > -1) {
this.dataStore.splice(foundAt, 1);
--this.listSize;
return true;
}
return false;
}
function length() {
return this.listSize;
}
function toString() {
return this.dataStore;
}
function insert(element, after){
var insertPos = this.find(after);
if(insertPos > -1){
this.dataStore.splice(insertPos+1, 0, element);
++this.listSize;
return true;
}
return false;
}
function clear() {
delete this.dataStore;
this.dataStore = [];
this.listSize = this.pos = 0;
}
function contains(element) {
for (var i = 0; i < this.dataStore.length; ++i) {
if(this.dataStore[i] === element) {
return true;
}
}
return false;
}
function front() {
this.pos = 0;
}
function end() {
this.pos = this.listSize-1;
}
function prev() {
return this.dataStore[--this.pos];
}
function next(){
return this.dataStore[this.pos++];
}
function hasNext(){
if (this.pos > this.listSize -1) {
return false;
} else {
return true;
}
}
function hasPrevious() {
if(this.pos <= 0) {
return false;
} else {
return true;
}
}
function currPos() {
return this.pos;
}
function moveTo(position) {
this.pos = position;
}
function getElement() {
return this.dataStore[this.pos];
}
function insertIf(element) {
var greaterThan = true;
for(this.front(); this.hasNext(); ){
if(this.next() > element) {
greaterThan = false;
break;
}
}
console.log(element);
if(greaterThan){
this.append(element);
return true;
} else {
return false;
}
}
Your loops will then look like this:
for (list.front(); list.hasNext();) {
var listItem = list.next();
if(listItem instanceof Customer) {
console.log(listItem.name + ", " + listItem.movie);
} else {
console.log(listItem);
}
}
This has proven to be a much more reliable implementation so you may want to consider switching to this.
You need to change your for loop to:
for(names.end(); names.currPos() > 0; names.prev())

Difference between two recursive functions

findElementById
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
return findElementRecursion(inputId, currentChild);
}
}
return false;
}
Would anyone help me debug this recursive function?
It returns false when it should return true. Since I don't see any error message, I am having a hard time trying to figure out what's the problem. It would be helpful if someone told me the steps of debugging this kind of problem.
update:
the problem was that I was returning only after inspecting the first child of currentElement. I fixed that problem but the function still returns false when it should return true.
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
if (findElementRecursion(inputId, currentChild)) {
return true;
}
}
}
return false;
}
Try this from console on this page with findElementRecursion (mainbar, document) and you will see false.
function findElementRecursion (inputId, currentElement) {
var result = false;
if (currentElement.id == inputId) {
return true;
}
for (var i=0; i<currentElement.children.length; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
result = findElementRecursion(inputId, currentChild);
// we can break here
if(result)
return true;
}
return false;
}
If I was going to do this, I wouldn't use a recursive function, I'd just use getElementsByTagName. It would be faster and traverse elements in the same order. It will also only visit elements, whereas other methods may visit text nodes too.
function findElementById(id, root) {
root = root || document;
var elements = root.getElementsByTagName('*');
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (elements[i].id == id) {
return elements[i];
}
}
}
But maybe you just want a recursive function for the exercise.
function findElementByIdRecursive(id, element) {
// If no element passed in, use document
element = element || document;
// If element has id, return it
if (element.id == id) return element;
// Otherwise, keep going
var foundElement;
var childNodes = element.childNodes;
// Not needed on modern browsers but older browsers may throw an error
// if the node can't have children (like a text node)
if (childNodes) {
// Only keep looping while a matching element isn't found
for (var i=0,iLen=childNodes.length; i<iLen && !foundElement; i++) {
// Save a call if this node matches
if (childNodes[i].id == id) {
return childNodes[i];
}
// Otherwise, go down its children
foundElement = findElementByIdRecursive(id, childNodes[i]);
}
return foundElement;
}
}
There are probably better ways to do this - like using jQuery - but this should work:
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
if (!currentElement.children) return false;
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (var i in currentElement.children) {
var currentChild = currentElement.children[i];
console.log(currentChild);
if (findElementRecursion(inputId, currentChild)) return true;
}
}
return false;
}
Notice that you also have to check if the element actually has children
you break the loop early:
function findElementRecursion (inputId, currentElement) {
var result = false;
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
result = findElementRecursion(inputId, currentChild);
if(result){
break;
}
}
}
return result;
}
From the initial code,
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
return findElementRecursion(inputId, currentChild);
}
}
return false;
}
The problem was I was returning too early and breaking out of the loop after only checking the first element of each currentElement.
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
if (findElementRecursion(inputId, currentChild)) return true;
}
}
return false;
}
However, the function still returns false when it should return true. That's because I didn't set i as local variable. It should have been var i so it is contained in each local environment.
function findElementRecursion (inputId, currentElement) {
if (currentElement.id == inputId) {
return true;
}
var numChildren = currentElement.children.length;
if (numChildren > 0) {
for (var i=0; i<numChildren; i++) {
var currentChild = currentElement.children[i];
console.log(currentChild);
if (findElementRecursion(inputId, currentChild)) return true;
}
}
return false;
}
Everything is good!

cross browser compare document position

DOM4 compareDocumentPosition
I want to implement compareDocumentPosition. Resig has made a great start at doing just this. I've taken his code and neatened it up
function compareDocumentPosition(other) {
var ret = 0;
if (this.contains) {
if (this !== other && this.contains(other)) {
ret += 16;
}
if (this !== other && other.contains(this)) {
ret += 8;
}
if (this.sourceIndex >= 0 && other.sourceIndex >= 0) {
if (this.sourceIndex < other.sourceIndex) {
ret += 4;
}
if (this.sourceIndex > other.sourceIndex) {
ret += 2;
}
} else {
ret += 1;
}
}
return ret;
}
This works for Element but does not for Text or DocumentFragment. This is because IE8 does not give .sourceIndex on those nodes. (It doesn't give .contains either but I've fixed that problem already)
How do I efficiently write the +=4 and +=2 bit which correspond to DOCUMENT_POSITION_FOLLOWING and DOCUMENT_POSITION_PRECEDING.
For extra reference those two are defined by tree-order which DOM4 defines as
An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order.
An object A is following an object B if A and B are in the same tree and A comes after B in tree order.
The tree order is preorder, depth-first traversal.
Most modern browsers implement this (including IE9). So you only need something that works in IE8 (I don't care about IE6/7, but if it works awesome!)
function recursivelyWalk(nodes, cb) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var ret = cb(node);
if (ret) {
return ret;
}
if (node.childNodes && node.childNodes.length) {
var ret = recursivelyWalk(node.childNodes, cb);
if (ret) {
return ret;
}
}
}
}
function testNodeForComparePosition(node, other) {
if (node === other) {
return true;
}
}
function compareDocumentPosition(other) {
function identifyWhichIsFirst(node) {
if (node === other) {
return "other";
} else if (node === reference) {
return "reference";
}
}
var reference = this,
referenceTop = this,
otherTop = other;
if (this === other) {
return 0;
}
while (referenceTop.parentNode) {
referenceTop = referenceTop.parentNode;
}
while (otherTop.parentNode) {
otherTop = otherTop.parentNode;
}
if (referenceTop !== otherTop) {
return Node.DOCUMENT_POSITION_DISCONNECTED;
}
var children = reference.childNodes;
var ret = recursivelyWalk(
children,
testNodeForComparePosition.bind(null, other)
);
if (ret) {
return Node.DOCUMENT_POSITION_CONTAINED_BY +
Node.DOCUMENT_POSITION_FOLLOWING;
}
var children = other.childNodes;
var ret = recursivelyWalk(
children,
testNodeForComparePosition.bind(null, reference)
);
if (ret) {
return Node.DOCUMENT_POSITION_CONTAINS +
Node.DOCUMENT_POSITION_PRECEDING;
}
var ret = recursivelyWalk(
[referenceTop],
identifyWhichIsFirst
);
if (ret === "other") {
return Node.DOCUMENT_POSITION_PRECEDING;
} else {
return Node.DOCUMENT_POSITION_FOLLOWING;
}
}
I wrote it myself. I thought this implementation was bugged but it was a bug in some other code of mine. Seems pretty solid.
The answer from Raynos is a top start, but is not runnable out of the box. Node.* cannot be found and .bind is not available in IE8.
Here is the code ready for use in Internet Explorer 8:
function recursivelyWalk(nodes, cb) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var ret = cb(node);
if (ret) {
return ret;
}
if (node.childNodes && node.childNodes.length) {
var ret = recursivelyWalk(node.childNodes, cb);
if (ret) {
return ret;
}
}
}
}
function testNodeForComparePosition(node, other) {
if (node === other) {
return true;
}
}
var DOCUMENT_POSITION_DISCONNECTED = 1;
var DOCUMENT_POSITION_PRECEDING = 2;
var DOCUMENT_POSITION_FOLLOWING = 4;
var DOCUMENT_POSITION_CONTAINS = 8;
var DOCUMENT_POSITION_CONTAINED_BY = 16;
function compareDocumentPosition(thisNode, other) {
function identifyWhichIsFirst(node) {
if (node === other) {
return "other";
} else if (node === reference) {
return "reference";
}
}
var reference = thisNode,
referenceTop = thisNode,
otherTop = other;
if (this === other) {
return 0;
}
while (referenceTop.parentNode) {
referenceTop = referenceTop.parentNode;
}
while (otherTop.parentNode) {
otherTop = otherTop.parentNode;
}
if (referenceTop !== otherTop) {
return DOCUMENT_POSITION_DISCONNECTED;
}
var children = reference.childNodes;
var ret = recursivelyWalk(
children,
function(p) {
(function() {
var localOther = other;
return testNodeForComparePosition(localOther, p);
})();
}
);
if (ret) {
return DOCUMENT_POSITION_CONTAINED_BY +
DOCUMENT_POSITION_FOLLOWING;
}
var children = other.childNodes;
var ret = recursivelyWalk(
children,
function(p) {
(function() {
var localOther = reference;
return testNodeForComparePosition(localOther, p);
})();
}
);
if (ret) {
return DOCUMENT_POSITION_CONTAINS +
DOCUMENT_POSITION_PRECEDING;
}
var ret = recursivelyWalk(
[referenceTop],
identifyWhichIsFirst
);
if (ret === "other") {
return DOCUMENT_POSITION_PRECEDING;
} else {
return DOCUMENT_POSITION_FOLLOWING;
}
}
You call it like this:
compareDocumentPosition(sourceElement, elementToTest)
(It's like calling sourceElement.compareDocumentPosition(elementToTest))

Categories