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);
Related
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>
I tried to write a code that prevents 2 creeps (harvester) from going to the same destination and binds them to that destination until its full.
on line 55 I get an error which is understandable
55: creep.memory.targetID = targets[checkTarget].id;
for a reason that I am not seeing targets[checkTarget] is null
Can anyone tell me what i am doing wrong?
var roleHarvester = {
/** #param {Creep} creep **/
run: function(creep) {
if (!creep.memory.targetID) creep.memory.targetID = "not given";
console.log(creep.memory.targetID);
if (creep.carry.energy < creep.carryCapacity) {
var nearestSource = creep.pos.findClosestByPath(FIND_SOURCES_ACTIVE);
if (creep.harvest(nearestSource) == ERR_NOT_IN_RANGE) {
creep.moveTo(nearestSource, {
visualizePathStyle: {
stroke: '#ffaa00'
}
});
}
} else {
if (creep.memory.targetID != "not given") {
console.log("should not be not given");
if (Game.getObjectById(creep.memory.targetID).hits == Game.getObjectById(creep.memory.targetID).hitsMax) {
creep.memory.targetID = "not given";
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_SPAWN ||
structure.structureType == STRUCTURE_EXTENSION ||
structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
}
});
} else {
if (creep.transfer(Game.getObjectById(creep.memory.targetID), RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
creep.moveTo(Game.getObjectById(creep.memory.targetID), {
visualizePathStyle: {
stroke: '#ffffff'
}
});
}
}
} else {
var targets = creep.room.find(FIND_STRUCTURES, {
filter: (structure) => {
return (structure.structureType == STRUCTURE_SPAWN ||
structure.structureType == STRUCTURE_EXTENSION ||
structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
}
});
console.log(targets);
for (var checkTarget in targets) {
console.log(checkTarget);
console.log(targets[checkTarget]);
for (var name in Game.creeps) {
if (targets[checkTarget] = Game.getObjectById(Game.creeps[name].memory.targetID)) {
var fail = true;
break;
}
var fail = false;
}
if (fail == true) continue;
console.log(Game.getObjectById(targets[checkTarget]));
creep.memory.targetID = targets[checkTarget].id;
break;
}
}
}
}
};
module.exports = roleHarvester;
Something wrong in the following if condition:
for(var name in Game.creeps) {
if(targets[checkTarget] = Game.getObjectById(Game.creeps[name].memory.targetID)){
Probably you mean == ?
Create a function called isIsogram that takes one argument, a word to test if it's an isogram. This function should return a boolean indicating whether it is an isogram (true) or not (false) in Javascript. Here is my code:
function isIsogram(word){
if (word !== 'string'){
return 'Argument should be a string';
}
if (word === ' '){
return false;
}
else{
var str = word.toLowerCase();
for(var i=0; i<str.length;i++){
if (charAt[i]>1){
return false;
}
else{
return true;
}
}
}
}
console.log(isIsogram('Dermatoglyphics'));
The code however returns 'Argument, not a string' for Dermatoglyphics which it ought not to
its working fine
whats problem you have face
you pass argu Dermatoglyphics is != to string thats why if condition true and give message Argument should be a string and return
function isIsogram(word) {
if (word !== 'string') {
return 'Argument should be a string';
}
if (word === ' ') {
return false;
} else {
var str = word.toLowerCase();
for (var i = 0; i < str.length; i++) {
if (charAt[i] > 1) {
return false;
} else {
return true;
}
}
}
}
console.log(isIsogram('Dermatoglyphics'));
Assuming you need to check if a letter appears just on times, then you could use an object and take a flag for every found letter. By checking the letter object, the function exit with false if a duplicate letter is found.
function isIsogram(word) {
var str = word.toLowerCase(),
letter = Object.create(null),
i;
if (typeof word !== 'string') {
return 'Argument should be a string';
}
if (word === ' ') {
return false;
}
for (i = 0; i < str.length; i++) {
if (letter[str[i]]) {
return false;
}
letter[str[i]] = true;
}
return true;
}
console.log(isIsogram('Dermatoglyphics'));
here is the question:
Imagine the String() constructor didn't exist. Create a constructor
function, MyString(), that acts like String() as closely as possible.
You're not allowed to use any built-in string methods or properties,
and remember that String() doesn't exist. You can use this code to
test your constructor:
I created constructor however I have no clue how to re-create split method, how to implement that functionality.
If you could give an idea how to implement split method, I would be grateful
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.reverse())
You can convert the string to an array and use Array.prototype and RegExp.prototype methods.
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
function MyString(str) {
var thisObj = this;
var innerLength = 0;
this.length;
function updateLength() {
innerLength = 0;
for (var i = 0; str[i] != undefined; i++) {
innerLength++;
thisObj[i] = str[i];
}
thisObj.length = innerLength;
}
updateLength();
this.toString = function() {
return str;
}
this.split = function(re) {
var arr = Array.prototype.slice.call(this.toString());
if (re === "") {
return arr
}
if (re === " ") {
return arr.filter(function(el) {
return /[^\s]/.test(el)
})
}
if (/RegExp/.test(Object.getPrototypeOf(re).constructor)) {
var regexp = re.source;
return arr.filter(function(el) {
return regexp.indexOf(el) === -1
})
}
}
this.charAt = function(i) {
if (isNaN(parseInt(i))) {
return this[0]
} else {
return this[i]
}
}
this.concat = function(string) {
str += string;
updateLength();
}
this.slice = function(start, end) {
var slicedString = "";
if (start >= 0 && end >= 00) {
for (start; start < end; start++) {
slicedString += str[start];
}
}
return slicedString;
}
this.reverse = function() {
var arr = str.split("");
arr.reverse();
var reversedString = "",
i;
for (i = 0; i < arr.length; i++) {
reversedString += arr[i];
}
return reversedString;
}
}
var ms = new MyString("Hello, I am a string")
console.log(ms.split(""), ms.split(" "), ms.split(/l/))
Iterate and search:
MyString.prototype.split = function(splitter){
var tmp="", result = [];
for(var i = 0; i < this.length; i++){
for(var offset = 0; offset < this.length && offset < splitter.length;offset++){
if(this[i+offset] !== splitter[offset]) break;
}
if(offset === splitter.length){
result.push( tmp );
tmp="";
i += offset -1;
}else{
tmp+=this[i];
}
}
result.push(tmp);
return result;
};
So now you can do:
new MyString("testtest").split("t") //['','es','','','es','']
In action
Working on a Holdem hand evaluator, and part of the yak shaving is writing a "how many combos of 5 do you get from 7 cards" function (pickNofSet()). I've done that, but the way I've done that returns a bunch of duplicates.
So I have to write a removeDuplicates(). Here's the problem... it works with a simple array, but it doesn't work with the "arrays of arrays" that my "pickNofSet" function generates.
-- here's the removeDuplicates code --
var removeDuplicates = function(input){ // takes array
var output = [];
for (i=0; i < input.length; i++){
var unique = true; // all elements are innocent until proven guilty
for(j=i+1; j < input.length; j++){
if(input[j] === input[i]){
unique = false; // guilty!
};// endif
};// end jfor
if(unique){ // if not found guilty,
output.push(input[i]); // you may go free, little element
};// end if
};// end ifor
console.log(output);
return output; };//end function
Here's what I get from the Console:
> removeDuplicates(['a','b','c'],['a','b','c'],['d','e','f'],['g','h','i']);
< undefined
> removeDuplicates([1, 2, 2, 3, 3, 5, 5, 6, 6, 6]);
< [1, 2, 3, 5, 6]
Operator === can't compare array
As you use === to check equality between two elements, this only works with primitive data types, but not array. e.g.
1===1 // true
[1]===[1] // Sorry, you can't
If you want your algorithm to work with both primitive elements and array elements, you may need to upgrade your equality check from === to a customized function.
From this:
if(input[j] === input[i]){
unique = false; // guilty!
};// endif
To this:
if (equals(input[j],input[i]){
unique = false; // guilty!
};// endif
And implement equals function to be capable of comparing both primitive data types and arrays:
function equals(a,b){
if (typeof(a)!=typeof(b))
return false;
else if (typeof(a)=='object'){
if (Object.keys(a).length != Object.keys(b).length)
return false;
else{
for (var keyA of Object.keys(a)){
if (!(keyA in b))
return false;
else if (a[keyA]!==b[keyA])
return false;
else
return true;
}
}
}
else
return a===b;
}
Hint: This solution should, hopefully, also work with JSON element.
Here is an example of a general purpose unique filter that should fill your need. Requires an ES5 compliant environment.
(function () {
'use strict';
function $strictEqual(a, b) {
return a === b;
}
function $isUndefined(inputArg) {
return $strictEqual(typeof inputArg, 'undefined');
}
function $isPrimitive(inputArg) {
var type = typeof inputArg;
return type === 'undefined' || inputArg === null || type === 'boolean' || type === 'string' || type === 'number' || type === 'symbol';
}
function $isFunction(inputArg) {
return typeof inputArg === 'function';
}
function $isDate(inputArg) {
return Object.prototype.toString.call(inputArg) === '[object Date]';
}
function $isRegExp(inputArg) {
return Object.prototype.toString.call(inputArg) === '[object RegExp]';
}
function $isString(inputArg) {
return Object.prototype.toString.call(inputArg) === '[object String]';
}
function $isArguments(inputArg) {
return Object.prototype.toString.call(inputArg) === '[object Arguments]';
}
function $getItem(object, index) {
var item;
if ($isString(object)) {
item = object.charAt(index);
} else {
item = object[index];
}
return item;
}
var de = function (a, b, circ) {
if (a === b) {
return true;
}
var aType,
bType,
aIsArgs,
bIsArgs,
aIsPrim,
bIsPrim,
aCirc,
bCirc,
ka,
kb,
length,
index,
it;
if ($isDate(a) && $isDate(b)) {
return a.getTime() === b.getTime();
}
if ($isRegExp(a) && $isRegExp(b)) {
return a.source === b.source &&
a.global === b.global &&
a.multiline === b.multiline &&
a.lastIndex === b.lastIndex &&
a.ignoreCase === b.ignoreCase &&
a.sticky === b.sticky;
}
aIsPrim = $isPrimitive(a);
bIsPrim = $isPrimitive(b);
if ((aIsPrim || $isFunction(a)) && (bIsPrim || $isFunction(b))) {
/*jslint eqeq: true */
return a == b;
}
if (aIsPrim || bIsPrim) {
return a === b;
}
if (a.prototype !== b.prototype) {
return false;
}
if (circ.a.indexOf(a) === -1) {
circ.a.push(a);
} else {
aCirc = true;
}
if (circ.b.indexOf(b) === -1) {
circ.b.push(b);
} else {
bCirc = true;
}
if (aCirc && bCirc) {
circ.cnt += 1;
} else {
circ.cnt = 0;
}
if (circ.cnt > 200) {
throw new RangeError('Circular reference limit exceeded');
}
aIsArgs = $isArguments(a);
bIsArgs = $isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) {
return false;
}
if (aIsArgs) {
return de(Array.prototype.slice.call(a), Array.prototype.slice.call(b), circ);
}
ka = Object.keys(a);
kb = Object.keys(b);
length = ka.length;
if (length !== kb.length) {
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
} else {
return false;
}
} else {
ka.sort();
kb.sort();
for (index = 0; index < length; index += 1) {
if (ka[index] !== kb[index]) {
return false;
}
}
}
for (index = 0; index < length; index += 1) {
it = ka[index];
if (!de($getItem(a, it), $getItem(b, it), circ)) {
return false;
}
}
aType = typeof a;
bType = typeof b;
return aType === bType;
};
if (!Object.prototype.deepEqual) {
Object.defineProperty(Object.prototype, 'deepEqual', {
enumerable: false,
configurable: true,
writable: true,
value: function (b) {
var a = this;
return de(a, b, {
a: [],
b: [],
cnt: 0
});
}
});
}
if (!Array.prototype.unique) {
Object.defineProperty(Array.prototype, 'unique', {
enumerable: false,
configurable: true,
writable: true,
value: function (equalFn, thisArg) {
var object = Object(this),
length,
index,
eqFn,
arr,
idx,
val,
it;
if ($isUndefined(equalFn)) {
eqFn = $strictEqual;
} else {
eqFn = equalFn;
}
if (!$isFunction(eqFn)) {
throw new TypeError('Argument is not a function: ' + eqFn);
}
arr = [];
length = object.length >>> 0;
for (index = 0; index < length; index += 1) {
if (index in object) {
it = $getItem(object, index);
val = true;
for (idx = 0; idx < length; idx += 1) {
if (idx < index && idx in object && eqFn.call(thisArg, it, $getItem(object, idx))) {
val = false;
break;
}
}
if (val) {
arr.push(it);
}
}
}
return arr;
}
});
}
}());
var data1 = [1, 2, 2, 3, 3, 5, 5, 6, 6, 6],
data2 = [
['a', 'b', 'c'],
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
],
equals = Function.prototype.call.bind(Object.prototype.deepEqual),
pre = document.getElementById('out');
pre.textContent = JSON.stringify(data1.unique(equals), null, 2);
pre.textContent += '\n\n';
pre.textContent += JSON.stringify(data2.unique(equals), null, 2);
<pre id="out"></pre>