Javascript in_array - javascript

In php this is a nice way of asking is a value is one of a few options
if( in_array($needle, [1,325,'something else']) ){
//do your thing
}
But in the world of javascript is there an equiv. that doesn't require writing a bespoke function such as:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
Use case of the above js bespoke function
if( inArray( somvar, [1,2,'something else']) ){
do the javascript thing
}
FROM THE COMMENTS
this is the most accurate answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

var needle = 325;
if( [1,325,'something else'].indexOf(needle) !== -1 ){
//do your thing
};

You can use Array.prototype.find():
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});

Related

Async function in javascript stops executing all by itself

Here I have an async function in javascript that is used to fill up the sudoku board with numbers (basically its solution). I used a sleeper function between each number insertion so that the user can get a better feel of the recursion and backtracking algorithm, however after the fifteenth number gets inserted, the function stops by itself... What is going on here exactly ?
var finalInd;
function sleep() {
console.log("happy")
return new Promise(resolve => setTimeout(resolve, 100));
}
async function solve () {
allowed = false;
var empty = findEmptySpace();
if(!empty) {
return true;
}
for(let i=1; i<10; i++) {
if(checkDuplicates(board, i, empty)) {
board[empty[0]][empty[1]] = i;
finalInd = (empty[0]*9) + empty[1];
await sleep()
funcId("board").children[finalInd].innerHTML = i;
if(solve(board)) {
return true;
}
board[empty[0]][empty[1]] = 0;
funcId("board").children[finalInd].innerHTML = 0;
}
}
funcId("board").children[0].innerHTML = board[0][0];
return false;
}
function checkDuplicates (board, num, empty) {
for(let i=0; i<9; i++) {
if(board[empty[0]][i] == num && empty[1] != i) {
return false;
}
}
for(let i=0; i<9; i++) {
if(board[i][empty[1]] == num && empty[0] != i) {
return false;
}
}
var x = Math.floor(empty[1]/3);
var y = Math.floor(empty[0]/3);
for(let i=(y*3); i<(y*3)+3; i++) {
for(let j=(x*3); j<(x*3)+3; j++) {
if(board[i][j] == num && i != empty[0] && j != empty[1]) {
return false;
}
}
}
return true;
}
function findEmptySpace () {
for(let i=0; i<9; i++) {
for(let j=0; j<9; j++) {
if(board[i][j] == 0) {
return [i, j];
}
}
}
}
I think you forgot to await the recursive call to solve, so it will always return a promise, which it's truthy, and your function will terminate.

Faster Evaluating IF Condition of JavaScript

Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')

Is there a polyfill for findAll

I am using JavaScript findAll for a selector engine. Is there any polyfill for the findAll function. I tried to create my own selector engine with this code:
function CTfind(string, context){
var result = [], finalResult = [];
if(typeof string === "object"){
result.push(string);
return result;
}
if(/<([a-zA-Z]+)(\s*)?\/>/ig.test(string)){
var str = string.replace(/<([a-zA-Z]+)(\s*)?\/>/ig, "$1");
var ret = document.createElement(str);
if(typeof context === "object"){
for(i in context)
ret[i] = context[i];
}
document.body.appendChild(ret);
result.push(ret);
return result;
} else{
if(typeof string !== "string" && typeof string !== "object") return false;
var documentElements = context.getElementsByTagName("*"),
toMatch = string.split(", ");
for(i = 0; i < documentElements.length; i++){
for(e = 0; e < toMatch.length; e++){
var stringParts = toMatch[e].split(" ");
for(s = 0; s < stringParts.length; s++){
var parts;
if(/(\.|\#|\:)/g.test(stringParts[s])){
parts = stringParts[s].match(/([A-Za-z]+|[\.\#\:]+[^\.\#\:]+)/g);
} else if(/^(?!(\.|\#|\:)$).*$/g.test(stringParts[s])){
parts = stringParts[s];
var onlyElem = true;
}
if(onlyElem === true){
console.log(documentElements[i].nodeName);
if(documentElements[i].nodeName.toLowerCase() === parts){
result.push(documentElements[i]);
}
} else{
var containsClass = false,
containsElem = false,
containsID = false,
containsPseudo = false,
matchID = false,
matchElem = false,
matchClass = false,
matchPseudo = false;
if(/\./.test(stringParts[s])){
containsClass = true;
}
if(/\#/.test(stringParts[s])){
containsID = true;
}
if(/\:/.test(stringParts[s])){
containsPseudo = true;
}
if(/[^\.\#\:](.*)/.test(stringParts[s])){
containsElem = true;
}
if(containsElem === true){
var elem;
for(g = 0; g < parts.length; g++){
if(/^([^\.\#\:][A-Za-z])*$/.test(parts[g])){
elem = parts[g];
} else{
elem = documentElements[i].nodeName.toLowerCase();
}
}
if(documentElements[i].nodeName.toLowerCase() === elem){
matchElem = true;
}
} else{
matchElem = true;
}
if(containsID === true){
var id = filter(parts, "#");
id = id[0].substr(1);
if(getAttr(documentElements[i], "id") === id){
matchID = true;
}
} else{
matchID = true;
}
if(containsClass === true){
var classes = filter(parts, ".");
if(typeof classes === "string"){
classes = classes[0].split(".");
for(c = 0; c < classes.length; c++){
if(classes[c] !== ""){
if(hasClass(documentElements[i], classes[c])){
matchClass = true;
}
}
}
}
} else{
matchClass = true;
}
if(matchClass && matchID && matchElem){
result.push(documentElements[i]);
}
console.log(result);
}
}
if(stringParts.length > 1){
console.log(result);
if(isDescendant(result[0], result[result.length - 1])){
finalResult.push(result[result.length - 1]);
}
}
}
}
return finalResult;
}
};
But I thought using Javascript findAll would be much easier. Also, I can't use querySelector because sometimes I need to find it in a specific node.

called function refuses to return true

Even when sum === largest in subset(), I don't get a "true" in my console. The true is sent back only to the calling function? Then how do I get the "return true" to behave as a newbie would expect?
function ArrayAdditionI(arr)
{
arr.sort();
var largest = arr.pop()
subset([], arr, largest);
}
function subset(soFar, rest, largest)
{
var sum = 0;
if (rest.length === 0)
{
for(var i=0; i<soFar.length; i++)
{
sum+= soFar[i];
}
if (sum === largest)
{
return true;
}
}
else
{
var soFar2 = soFar.slice(0);
soFar2.push(rest[0]);
subset(soFar,rest.slice(1),largest);
subset(soFar2, rest.slice(1),largest);
}
}
ArrayAdditionI([85,3,88,2])
function ArrayAdditionI(arr)
{
arr.sort();
var largest = arr.pop()
var ret = subset([], arr, largest);
// do something with ret
}
function subset(soFar, rest, largest)
{
var sum = 0;
if (rest.length === 0)
{
for(var i=0; i<soFar.length; i++)
{
sum+= soFar[i];
}
if (sum === largest)
{
return true;
}
}
else
{
var soFar2 = soFar.slice(0);
soFar2.push(rest[0]);
subset(soFar,rest.slice(1),largest);
subset(soFar2, rest.slice(1),largest);
}
return false;
}
ArrayAdditionI([85,3,88,2])

Simple javascript in_array recursive function

So for PHP I have a handy set of function for doing an in_array on multi dim arrays:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
However I have tried to recreate one similar in javascript but I cannot seem to get it to work.. this is what i have:
function in_array_r(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle){
return true;
}
if(typeof haystack[i]=='object'){
if(in_array_r(needle, haystack[i])){
return true;
}
}
}
return false;
}
Can anybody spot why it isn't working as I cannot see why it doesn't..
Thanks,
John
This works.. numeric and non-numeric keys.. doh!
function in_array_r(needle, haystack) {
var length = haystack.length;
for(var key in haystack) {
if(haystack[key] == needle){
return true;
}
if(typeof haystack[key]=='object'){
if(in_array_r(needle, haystack[key])){
return true;
}
}
}
return false;
}

Categories

Resources